diff --git "a/6386.jsonl" "b/6386.jsonl" new file mode 100644--- /dev/null +++ "b/6386.jsonl" @@ -0,0 +1,682 @@ +{"seq_id":"394564564","text":"# Copyright 2017 The Bazel 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\nload(\n \"@io_bazel_rules_go//go/private:context.bzl\",\n \"go_context\",\n)\nload(\n \"@io_bazel_rules_go//go/private:providers.bzl\",\n \"GoLibrary\",\n)\n\ndef _go_source_impl(ctx):\n \"\"\"Implements the go_source() rule.\"\"\"\n go = go_context(ctx)\n library = go.new_library(go)\n source = go.library_to_source(go, ctx.attr, library, ctx.coverage_instrumented())\n return [\n library,\n source,\n DefaultInfo(\n files = depset(source.srcs),\n ),\n ]\n\ngo_source = rule(\n implementation = _go_source_impl,\n attrs = {\n \"data\": attr.label_list(allow_files = True),\n \"srcs\": attr.label_list(allow_files = True),\n \"deps\": attr.label_list(providers = [GoLibrary]),\n \"embed\": attr.label_list(providers = [GoLibrary]),\n \"gc_goopts\": attr.string_list(),\n \"_go_config\": attr.label(default = \"//:go_config\"),\n \"_cgo_context_data\": attr.label(default = \"//:cgo_context_data_proxy\"),\n },\n toolchains = [\"@io_bazel_rules_go//go:toolchain\"],\n)\n# See go/core.rst#go_source for full documentation.\n","sub_path":"go/private/rules/source.bzl","file_name":"source.bzl","file_ext":"bzl","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"50185962","text":"import logging\nimport sys\n\nLOG_FILE_NAME = 'person.log'\n\ndef get_logger():\n logger = logging.getLogger(__name__)\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(funcName)s - %(message)s')\n\n screen_handler = logging.StreamHandler(sys.stdout)\n screen_handler.setLevel(logging.DEBUG)\n screen_handler.setFormatter(formatter)\n\n logfile_handler = logging.FileHandler(filename=LOG_FILE_NAME)\n logfile_handler.setLevel(logging.DEBUG)\n logfile_handler.setFormatter(formatter)\n\n logger.addHandler(logfile_handler)\n logger.addHandler(screen_handler)\n\n logger.setLevel(logging.DEBUG)\n\n return logger\n","sub_path":"task_18/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"601070345","text":"from gurobipy import tuplelist\nclass UraniumMineProblem:\n \"\"\"\n This class contains the data of the Uranium Mine Problem.\n An instance of this class represents an instance of the problem.\n \"\"\"\n def __init__(self,blocks: list,costs:dict,values:dict,precedences:tuplelist):\n self.blocks = blocks\n self.costs = costs\n self.values = values\n self.precedences = precedences\n","sub_path":"solutions/python_files/uranium/uranium_problem.py","file_name":"uranium_problem.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"43853933","text":"#-*- coding: utf-8 -*-\n\n# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org\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 cl_client import client, __app__, __version__\nfrom cl_opt import opt\nimport sys\nfrom cl_share_cmd import share_cmd\n\n# Перевод сообщений для программы\nfrom cl_lang import lang\nlang().setLanguage(sys.modules[__name__])\n\n# Использование программы\nUSAGE = _(\"%prog [options] domain\")\n\n# Коментарии к использованию программы\nCOMMENT_EXAMPLES = _(\"Add settings for connecting to \"\n \"domain server.calculate.ru\")\n\n# Пример использования программы\nEXAMPLES = _(\"%prog server.calculate.ru\")\n\n# Описание программы (что делает программа)\nDESCRIPTION = _(\"Changes settings for connecting to the domain\")\n\n# Опции командной с��роки\nCMD_OPTIONS = [{'shortOption':\"r\",\n 'help':_(\"remove the settings for connecting to the domain\")},\n {'longOption':\"mount\",\n 'help':_(\"mount the [remote] domain resource\")},\n {'longOption':\"set\"},\n {'longOption':\"install\",\n 'help':_(\"install the package\")},\n {'longOption':\"uninstall\",\n 'help':_(\"uninstall the package\")}]\n\nclass client_cmd(share_cmd):\n def __init__(self):\n # Объект опций командной строки\n setpos = \\\n filter(lambda x:x[1].get('longOption')==\"set\",\n enumerate(CMD_OPTIONS))[0][0]\n CMD_OPTIONS[setpos] = opt.variable_set[0]\n self.optobj = opt(\\\n package=__app__,\n version=__version__,\n usage=USAGE,\n examples=EXAMPLES,\n comment_examples=COMMENT_EXAMPLES,\n description=DESCRIPTION,\n option_list=CMD_OPTIONS + opt.variable_view+opt.color_control,\n check_values=self.checkOpts)\n # Создаем объект логики\n self.logicObj = client()\n # Создаем переменные\n self.logicObj.createClVars()\n # Названия несовместимых опций\n self.optionsNamesIncompatible = [\"r\", \"mount\", \"install\", \"uninstall\"]\n # Названия опций несовмесимых с именем домена\n self.optionsNamesNotDomain = self.optionsNamesIncompatible\n\n def getOptionsNotDomain(self, optObj):\n \"\"\"Получаем опции несовместимые с именем домена\"\"\"\n retList = []\n for nameOpt in self.optionsNamesNotDomain:\n retList.append(getattr(optObj, nameOpt))\n return retList\n\n def _getNamesAllSetOptions(self):\n \"\"\"Выдает словарь измененных опций\"\"\"\n setOptDict = self.optobj.values.__dict__.items()\n defaultOptDict = self.optobj.get_default_values().__dict__.items()\n return dict(set(setOptDict) - set(defaultOptDict)).keys()\n\n def getStringIncompatibleOptions(self):\n \"\"\"Форматированная строка несовместимых опций разделенных ','\"\"\"\n listOpt = list(set(self.optionsNamesIncompatible) &\\\n set(self._getNamesAllSetOptions()))\n return \", \".join(map(lambda x: len(x) == 1 and \"'-%s'\"%x or \"'--%s'\"%x,\\\n listOpt))\n\n def checkOpts(self, optObj, args):\n \"\"\"Проверка опций командной строки\"\"\"\n optionsNotDomain = self.getOptionsNotDomain(optObj)\n if not args:\n options = optionsNotDomain + [optObj.color, optObj.v,\n optObj.filter, optObj.xml]\n if not filter(lambda x: x, options):\n errMsg = _(\"no such argument\")+\":\"+\" %s\" %USAGE.split(\" \")[-1]\n self.optobj.error(errMsg)\n return False\n elif len(filter(lambda x: x, optionsNotDomain))>1:\n errMsg = _(\"incompatible options\")+\":\"+\" %s\"\\\n %self.getStringIncompatibleOptions()\n self.optobj.error(errMsg)\n return False\n elif filter(lambda x: x, optionsNotDomain):\n errMsg = _(\"unnecessary argument\")+\":\"+\" %s\" %USAGE.split(\" \")[-1]\n self.optobj.error(errMsg)\n return False\n if len(args)>1:\n errMsg = _(\"incorrect argument\") + \":\" + \" %s\" %\" \".join(args)\n self.optobj.error(errMsg)\n return False\n if not optObj.v:\n if optObj.filter:\n errMsg = _(\"incorrect option\") + \":\" + \" %s\" %\"--filter\" +\\\n \": \" + _(\"used with option '-v'\")\n self.optobj.error(errMsg)\n return False\n if optObj.xml:\n errMsg = _(\"incorrect option\") + \":\" + \" %s\" %\"--xml\" +\\\n \": \" + _(\"used with option '-v'\")\n self.optobj.error(errMsg)\n return False\n return optObj, args\n\n def addDomain(self, domainName):\n \"\"\"Ввод в домен\"\"\"\n if domainName:\n return self.logicObj.addDomain(domainName)\n else:\n self.printERROR(_(\"No domain name found as argument\"))\n return False\n\n def delDomain(self):\n \"\"\"Вывод из домена\"\"\"\n return self.logicObj.delDomain()\n\n def mountRemote(self):\n \"\"\"Монтирование remote и домашней директории если компьютер в домене\n\n а так-же ввод в домен если найдено имя хоста и пароль для подключения\n \"\"\"\n return self.logicObj.mountRemote()\n\n def install(self):\n \"\"\"Инсталяция программы\"\"\"\n return self.logicObj.installProg()\n\n def updateEnvFiles(self):\n \"\"\"Апдейт env файлов до новой версии\"\"\"\n return self.logicObj.updateEnvFiles()\n\n def uninstall(self):\n \"\"\"Удаление программы\"\"\"\n return self.logicObj.uninstallProg()\n","sub_path":"pym/cl_client_cmd.py","file_name":"cl_client_cmd.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498404205","text":"#!/usr/bin/env python\n\nimport os, string, sys, time, re, math, fileinput, glob, shutil, codecs\nimport threading, platform\n\n#adb cmd appops set\n#\n#\n\n# Copyright (C) 2017 Roy Chen\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# increment this whenever we make important changes to this script\nVERSION = (0, 1)\n\n#--------------------------------------------------------------------------------------------------\n#\n\n#--------------------------------------------------------------------------------------------------\ndef get_tmp_out() :\n\tret = os.getenv('OUT_TMP')\n\tif ( None != ret ):\n\t\treturn ret\n\tif ( 'Windows' in platform.system() ):\n\t\tret = str(\"d:/out_tmp\")\n\telse :\n\t\tret = \"~/out_tmp\"\n\treturn ret\n\ndef now() :\n\treturn str( time.strftime( '%Y%m%d-%H%M%S' , time.localtime() ) )\n\ndef rm_make_dirs(g_out_dir) :\n\tif os.path.exists(g_out_dir):\n\t\tshutil.rmtree(g_out_dir)\n\tos.makedirs(g_out_dir)\n\ndef run_cmd(cmd):\n\tprint(\"run: \" + cmd)\n\tos.system(cmd)\n\t#os.popen(cmd)\n\n#--------------------------------------------------------------------------------------------------\ndef start_thread(func):\n\t#print(\"start_thread: \" + arg1)\n\tth = threading.Thread(target = func, )\n\tth.start()\n\treturn th\n\ndef start_thread_arg1(func, arg1):\n\t#print(\"start_thread: \" + cmd)\n\tth = threading.Thread(target = func, args = (arg1,))\n\tth.start()\n\treturn th\n#--------------------------------------------------------------------------------------------------\n\n\n#--------------------------------------------------------------------------------------------------\ndef pull_apk_by_thpool(out_dir, apk_file, third_apk):\n\tthpool = []\n\n\tinput_file = out_dir + \"/\" + apk_file\n\tif os.access(input_file, os.R_OK) == 0:\n\t\tprint(\"no file: \" + input_file + \"\\n\")\n\t\treturn\n\tfp = codecs.open(input_file, 'r', \"'utf-8'\")\n\tlines = fp.readlines()\n\tfp.close()\n\n\tthread_count = 0\n\tthread_sum = 7\n\n\tfor line in lines:\n\t\tline = line.strip()\n\t\tif (len(line) < len(\"package:/\")):\n\t\t\tcontinue\n\t\t#print (\"line: \" + line)\n#package:/data/app/com.banshenghuo.mobile-1/base.apk=com.banshenghuo.mobile\n\t\twords = line.split(\":\")\n#\t\tprint (words)\n\t\tline = words[1]\n\t\twords = line.split(\"=\")\n\t\tpackage_name = words[1]\n#\t\tprint (data_app)\n#\t\tprint (out_app)\n#\t\tcontinue\n\n\t\tprint (package_name)\n\t\tcmd = \"adb shell cmd appops get \" + package_name + \" > \" + out_dir + \"/\" + package_name + \"_appops_origin.txt\"\n\t\trun_cmd(cmd)\n\n\t\t#if (third_apk):\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" RUN_IN_BACKGROUND ignore\"\n\n\t\tif ((package_name.find(\"android.mms\")!=-1) or (package_name.find(\"android.contacts\")!=-1) ):\n\t\t\tprint (\"skip-------------------:\" + package_name)\n\t\t\tcontinue\n#\t\tcontinue\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" READ_SMS ignore\"\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" SEND_SMS ignore\"\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" READ_MMS ignore\"\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" SEND_MMS ignore\"\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" READ_CONTACTS ignore\"\n\t\trun_cmd(cmd)\n\t\tcmd = \"adb shell cmd appops set \" + package_name + \" READ_CALL_LOG ignore\"\n\t\trun_cmd(cmd)\n#\t\tif (third_apk):\n#\t\t\tcmd = \"adb shell cmd appops set \" + package_name + \" READ_EXTERNAL_STORAGE ignore\"\n#\t\trun_cmd(cmd)\n#\t\tif (third_apk):\n#\t\t\tcmd = \"adb shell cmd appops set \" + package_name + \" WRITE_EXTERNAL_STORAGE ignore\"\n#\t\trun_cmd(cmd)\n\n\t\tcmd = \"adb shell cmd appops get \" + package_name + \" > \" + out_dir + \"/\" + package_name + \"_appops_new.txt\"\n\t\trun_cmd(cmd)\n\n\treturn\n\n#--------------------------------------------------------------------------------------------------\ndef main(argv):\n\trun_cmd(\"adb wait-for-device\" )\n\trun_cmd(\"adb root\")\n\trun_cmd(\"adb wait-for-device\" )\n\n\tout_class = \"appops/\"\n\tout_dir = \tget_tmp_out() + \"/\" + out_class + now() + \"/\"\n\tprint( \"out_dir: \" + out_dir )\n\trm_make_dirs( out_dir )\n\n\tapk_file = \"apk_file.txt\"\n\n\trun_cmd(\"adb shell cmd package list packages -f > \" + out_dir + \"/\" + apk_file)\n\tpull_apk_by_thpool(out_dir, apk_file, False)\n\n#\trun_cmd(\"adb shell cmd package list packages -f -3 > \" + out_dir + \"/\" + apk_file)\n#\tpull_apk_by_thpool(out_dir, apk_file, True)\n\n\treturn\n\nif __name__ == '__main__':\n main(sys.argv)\n\n\n\n","sub_path":"a_android/p_package/appops.py","file_name":"appops.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389726650","text":"#\r\n# @lc app=leetcode.cn id=1260 lang=python3\r\n#\r\n# [1260] 二维网格迁移\r\n#\r\n# https://leetcode-cn.com/problems/shift-2d-grid/description/\r\n#\r\n# algorithms\r\n# Easy (55.56%)\r\n# Likes: 2\r\n# Dislikes: 0\r\n# Total Accepted: 1.2K\r\n# Total Submissions: 2.2K\r\n# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]\\n1'\r\n#\r\n# 给你一个 n 行 m 列的二维网格 grid 和一个整数 k。你需要将 grid 迁移 k 次。\r\n#\r\n# 每次「迁移」操作将会引发下述活动:\r\n#\r\n#\r\n# 位于 grid[i][j] 的元素将会移动到 grid[i][j + 1]。\r\n# 位于 grid[i][m - 1] 的元素将会移动到 grid[i + 1][0]。\r\n# 位于 grid[n - 1][m - 1] 的元素将会移动到 grid[0][0]。\r\n#\r\n#\r\n# 请你返回 k 次迁移操作后最终得到的 二维网格。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n#\r\n#\r\n# 输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\r\n# 输出:[[9,1,2],[3,4,5],[6,7,8]]\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n#\r\n#\r\n# 输入:grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\r\n# 输出:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\r\n# 输出:[[1,2,3],[4,5,6],[7,8,9]]\r\n#\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 1 <= grid.length <= 50\r\n# 1 <= grid[i].length <= 50\r\n# -1000 <= grid[i][j] <= 1000\r\n# 0 <= k <= 100\r\n#\r\n#\r\n#\r\n\r\ntry:\r\n from typing import *\r\nexcept Exception as err:\r\n print('Import failed: ' + str(err))\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\r\n n, m = len(grid), len(grid[0])\r\n for _ in range(k):\r\n cur = grid[n - 1][m - 1]\r\n for r in range(len(grid)):\r\n newcur = grid[r][m - 1]\r\n grid[r] = [cur] + grid[r][:m - 1]\r\n cur = newcur\r\n return grid\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Solution().shiftGrid(grid=[[3, 8, 1, 9], [19, 7, 2, 5],\r\n [4, 6, 11, 10], [12, 0, 21, 13]],\r\n k=4))\r\n# @lc code=end\r\n","sub_path":"Easy/1260.二维网格迁移.py","file_name":"1260.二维网格迁移.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"4075719","text":"from django.shortcuts import render\nfrom django.utils.safestring import mark_safe\nfrom first_app.models import NewsModel\nfrom django.http import HttpResponse\n# Create your views here.\n\ndef index(request):\n\n NewsModel.objects.create(\n ResponseUrl='http://www.qq.com/123456.html',\n Title='-----国家发展和改革委员会_中国政府网----'\n )\n print('insert')\n return render(request,'index.html')\n\ndef find(request):\n print('find')\n result = NewsModel.objects.filter(Title='国家发展和改革委员会_中国政府网')\n print(result['ResponseUrl'])\n return HttpResponse('Insert Done')\n","sub_path":"django/basic_usage/first_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"200179546","text":"from django.contrib import admin\n\nfrom .models import Ad\n\n\ndef make_published(modeladmin, request, queryset):\n queryset.update(is_published=True)\n\n\nmake_published.short_description = \"Опубликовать выбранные Объявления\"\n\n\nclass AdAdmin(admin.ModelAdmin):\n list_display = (\n 'title', 'author', 'city', 'number_of_person', 'number_of_girls',\n 'number_of_boys', 'party_date', 'is_published', 'create_ad'\n )\n list_filter = ('city', 'party_date', 'is_published')\n\n readonly_fields = (\n 'title', 'author', 'city', 'number_of_person', 'number_of_girls',\n 'number_of_boys', 'party_date', 'geolocation', 'participants', 'create_ad'\n )\n\n actions = (make_published,)\n\n\nadmin.site.register(Ad, AdAdmin)\n","sub_path":"rest_api_backend_va_project/ad/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342375220","text":"class Solution(object):\n def summaryRanges(self, nums):\n summary = []\n for num in nums:\n if not summary or num > summary[-1][1] + 1:\n summary.append([num, num])\n else:\n summary[-1][1] = num\n result = [str(i) if i == j else str(i) + '->' + str(j) for i, j in summary]\n return result\n","sub_path":"228/228.summary-ranges.625841471.Accepted.leetcode.python3.py","file_name":"228.summary-ranges.625841471.Accepted.leetcode.python3.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"393328548","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 29 08:09:55 2018\n\n@author: minlam\n\"\"\"\nimport numpy as np\n\nh = 5.5\n\nu = np.log10(h)\n\nv = np.sign(u) * np.ceil(np.abs(u))\n\nnice_h = 10 ** v\n\nprint('The Nice Bin-Width = ', nice_h)","sub_path":"Old Materials/Additional Github/vigneshkrv/CS-584-Machine-Learning/ML/Assignments (1)/Assignments/week 2/Week 2 NiceBinWidth.py","file_name":"Week 2 NiceBinWidth.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"400563029","text":"from PySide2.QtWidgets import QWidget, QLabel, QTextEdit, QGridLayout, QVBoxLayout\n\n\nclass StatisticsWidget(QWidget):\n def __init__(self):\n super().__init__()\n self.setLayout(QVBoxLayout())\n self.layout().addWidget(DBViewWidget())\n\n\nclass DBViewWidget(QWidget):\n def __init__(self):\n super().__init__()\n self.entriesnum = QLabel('Entriesnum')\n self.tablename = QLabel('Tablename')\n self.entries = QTextEdit()\n self._widgets = ((QLabel('Entries'), 1, 1),\n (self.entriesnum, 2, 1),\n (QLabel('Table'), 1, 2),\n (self.tablename, 2, 2),\n (self.entries, 3, 1, 2, 2),\n )\n self._init_ui()\n\n def _init_ui(self):\n self.setLayout(QGridLayout())\n for widget in self._widgets:\n self.layout().addWidget(*widget)\n\n def _fill_values(self, values):\n self.entriesnum.setText(values.entriesnum)\n self.tablename.setText(values.tablename)\n for entry in values.entries:\n self.entries.insertPlainText(str(entry))\n","sub_path":"Gui/StatisticsPage/MainWidget.py","file_name":"MainWidget.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"428324400","text":"#Hayden Coffey\n#COSC 425: Project 2\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\n#Calculate and return max intracluster and min intercluster distances\n\n\ndef cluster_distances(set):\n if len(set) == 0:\n return 0, 0\n\n minInter = 100000\n maxIntra = 0\n\n #maxIntracluster distance\n for i in range(len(set)):\n clusterM = np.matrix(set[i])\n\n for j in range(len(clusterM)):\n for z in range(len(clusterM)):\n if j == z:\n continue\n tmp = np.linalg.norm(clusterM[j] - clusterM[z])\n if tmp > maxIntra:\n maxIntra = tmp\n\n #minIntercluster distance\n for i in range(len(set)):\n clusterM = np.matrix(set[i])\n\n for j in range(len(clusterM)):\n\n for z in range(len(set)):\n if z == i:\n continue\n\n clusterM2 = np.matrix(set[z])\n for v in range(len(clusterM2)):\n tmp = np.linalg.norm(clusterM[j] - clusterM2[v])\n if tmp < minInter:\n minInter = tmp\n\n return maxIntra, minInter\n\n#Performs k-means clustering on df with k clusters\n\n\ndef k_means(df, k):\n #initialize\n theta = 0.01\n bound = 1000 # If iterations exceeds, could not converge\n\n cluster = []\n maxVal = list(df.max(axis=0))\n minVal = list(df.min(axis=0))\n\n #Generate random values of m\n for i in range(k):\n cluster.append([])\n for j in range(len(df[0])):\n cluster[i].append(random.uniform(minVal[j], maxVal[j]))\n\n iterations = 0\n converged = False\n\n #Update values\n while not converged:\n bt = []\n for i in range(k):\n bt.append([])\n\n #Determine b boolean matrix for sets\n for i in range(len(df)):\n mDis = []\n for j in range(k):\n mDis.append(np.linalg.norm(df[i] - cluster[j]))\n bt[j].append(0)\n\n bt[mDis.index(min(mDis))][i] = 1\n\n #Calculate new m values\n new_m = []\n for i in range(k):\n sumMatrix = np.zeros(df.shape[1])\n for j in range(len(df)):\n sumMatrix += bt[i][j]*df[j]\n\n new_m.append(sumMatrix/np.sum(bt[i]))\n\n #Test for convergence\n converged = True\n for i in range(k):\n if np.linalg.norm(new_m[i] - cluster[i]) < theta:\n continue\n else:\n cluster[i] = new_m[i]\n converged = False\n iterations += 1\n if iterations > bound:\n break\n\n print(\"Iterations:\", iterations)\n if not converged:\n print(\"Could not converge, try running the program again\")\n return\n\n #Plot clusters\n sets = []\n for i in range(k):\n sets.append([])\n for j in range(len(df)):\n if bt[i][j]:\n sets[i].append(list(df[j]))\n\n #Determine cluster distances\n maxIntra, minInter = cluster_distances(sets)\n print(\"Max Intracluster Distance:\", maxIntra)\n print(\"Min Intercluster Distance:\", minInter)\n print(\"Dunn index:\", minInter/maxIntra)\n\n for i in range(k):\n plt.plot(np.matrix(sets[i])[:, 0], np.matrix(sets[i])[:, 1], '+')\n for i in range(k):\n plt.scatter(cluster[i][0], cluster[i][1])\n\n plt.title(\"k-means Clustering\")\n plt.xlabel(\"PC 1\")\n plt.ylabel(\"PC 2\")\n plt.grid(linestyle='--', color='gray')\n plt.show()\n\n #Plot with annotations\n for i in range(k):\n plt.plot(np.matrix(sets[i])[:, 0], np.matrix(sets[i])[:, 1], '+')\n for i in range(k):\n plt.scatter(cluster[i][0], cluster[i][1])\n for i in range(len(df)):\n plt.annotate(i, (pcScores[i, 0], pcScores[i, 1]))\n\n plt.title(\"k-means Clustering\")\n plt.xlabel(\"PC 1\")\n plt.ylabel(\"PC 2\")\n plt.grid(linestyle='--', color='gray')\n plt.show()\n\n\nif __name__ == \"__main__\":\n #Number of clusters to plot and dimensionality to reduce to\n cluster_num = 3\n k = 11\n\n #Read in standardized data and convert to numeric matrix\n original_df = pd.read_csv(\"UTK-peers-stand.csv\")\n df = original_df.copy()\n df = df.drop(columns=['Name'])\n matrix = df.values\n\n #Perform SVD on matrix and derive eigenvalues\n u, s, vh = np.linalg.svd(matrix)\n eigen = s**2\n\n #Plot Scree Graph of eigenvalues\n plt.plot(range(1, len(eigen)+1), eigen, marker='+')\n plt.xlabel(\"Eigenvectors\")\n plt.ylabel(\"Eigenvalues\")\n plt.title(\"Scree Graph\")\n plt.grid(linestyle='--', color='gray')\n plt.show()\n\n #Calculate and plot proportion of variance graph\n eigen_total = sum(eigen)\n s_total = sum(s)\n\n prop_var = []\n sum = 0\n for i in range(len(eigen)):\n sum += eigen[i]\n prop_var.append(sum/eigen_total)\n\n plt.plot(range(1, len(eigen)+1), prop_var, marker='+')\n plt.xlabel(\"Eigenvectors\")\n plt.ylabel(\"Prop. of var.\")\n plt.title(\"Proportion of Variance\")\n plt.grid(linestyle='--', color='gray')\n plt.show()\n\n #Calculate PC Scores and plot first 2 PC's\n pcScores = u.dot(np.diag(s))\n plt.plot(pcScores[:, 0], pcScores[:, 1], 'b+')\n\n #Label universities by number in dataset\n for i in range(len(df)):\n plt.annotate(i, (pcScores[i, 0], pcScores[i, 1]))\n\n plt.title(\"PCA Plot\")\n plt.xlabel(\"PC 1\")\n plt.ylabel(\"PC 2\")\n plt.grid(linestyle='--', color='gray')\n plt.show()\n\n #Perform k-means clustering with all data, reduced data, and first two PC's\n k_means(pcScores, cluster_num)\n\n newV = pcScores[:, :k]\n k_means(newV, cluster_num)\n\n newV = pcScores[:, :2]\n k_means(newV, cluster_num)\n","sub_path":"hc-project2.py","file_name":"hc-project2.py","file_ext":"py","file_size_in_byte":5684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"458578372","text":"show_in_list = True\ntitle = 'Detector Configuration'\nmotor_names = ['collect.detector_configuration', 'xray_scope.setup', 'laser_scope.setup']\nnames = ['detectors', 'xray_scope_setup', 'laser_scope_setup', 'motor2']\nmotor_labels = ['Detectors', 'X-ray Scope Setup', 'Laser Scope Setup']\nwidths = [280, 170, 170]\nline0.xray_scope.setup = 'NIH SAXS-WAXS'\nline0.laser_scope.setup = 'NIH SAXS-WAXS'\nline0.updated = '2019-05-28 20:24:36'\nline1.xray_scope.setup = 'NIH FPGA diagnostics'\nline1.laser_scope.setup = 'FPGA diagnostics'\nline1.updated = '2019-01-28 18:17:10'\nline0.description = 'SAXS/WAXS'\nline1.description = 'FPGA diagnostics'\ncommand_rows = [0]\nline0.detectors = 'xray_detector, xray_scope, laser_scope'\nline0.collect.detector_configuration = 'xray_detector, xray_scope, laser_scope'\nnrows = 9\nline2.description = 'SAXS/WAXS static'\nline2.collect.detector_configuration = 'xray_detector, xray_scope'\nline2.xray_scope.setup = 'NIH SAXS-WAXS'\nline2.laser_scope.setup = ''\nline2.updated = '2019-05-28 19:49:55'\nline3.description = 'NIH:Channel-Cut-Scan'\nline3.collect.detector_configuration = 'xray_scope'\nline3.updated = '2019-01-28 18:16:58'\nline3.xray_scope.setup = 'NIH Channel Cut Scan'\nline4.description = 'NIH:Slit-Scan'\nline4.collect.detector_configuration = 'xray_scope'\nline4.updated = '2019-03-18 17:06:12'\nline4.xray_scope.setup = 'NIH Slit Scan'\nline5.description = 'X-Ray Alignment'\nline5.collect.detector_configuration = ''\nline5.updated = '2019-01-29 08:48:16'\nline5.xray_scope.setup = 'Alignment'\nline5.laser_scope.setup = ''\nrow_height = 20\nline6.xray_scope.setup = 'APS Channel Cut Scan'\nline6.updated = '2019-01-29 17:04:44'\nline6.description = 'APS:Channel-Cut-Scan'\ndescription_width = 180\nline7.description = 'NIH:X-Ray Beam Check'\nline7.collect.detector_configuration = 'xray_scope'\nline7.updated = '2019-01-29 22:55:00'\nline7.xray_scope.setup = 'NIH X-Ray Beam Check'\nline8.collect.detector_configuration = 'xray_detector'\nline8.updated = '2019-02-04 11:50:52'\nline8.xray_scope.setup = 'Rob Test'\nline8.laser_scope.setup = ''\nline8.description = 'Rob Test'","sub_path":"settings/detector_configuration_settings.py","file_name":"detector_configuration_settings.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554608457","text":"import nltk\r\nimport re\r\nfrom nltk.corpus import sentiwordnet as swn\r\n\r\n\r\ndef sentiwordnet_lex(tweets):\r\n pos_tweets = {}\r\n for id in tweets:\r\n pos_tweets[id]=nltk.pos_tag(tweets[id])\r\n\r\n sentiwordnet={}\r\n for tweet_id in pos_tweets:\r\n pos_score = 0\r\n neg_score = 0\r\n for word in pos_tweets[tweet_id]:\r\n flag = False\r\n pos=''\r\n if re.match(\"^VB\",word[1]):\r\n pos = 'v'\r\n flag=True\r\n elif re.match(\"^NN|^PR\",word[1]):\r\n pos = 'n'\r\n flag = True\r\n elif re.match(\"^RB\",word[1]):\r\n pos = 'r'\r\n flag = True\r\n elif re.match(\"^JJ\",word[1]):\r\n pos = 'a'\r\n flag = True\r\n list_synsets=list(swn.senti_synsets(word[0],pos))\r\n if flag and len(list_synsets) != 0:\r\n syn=word[0]+'.'+pos+'.01'\r\n #print(syn)\r\n #print(swn.senti_synset(syn))\r\n synset=list_synsets[0]\r\n pos_score+= synset.pos_score()\r\n neg_score+= synset.neg_score()\r\n sentiwordnet[tweet_id]=[pos_score,neg_score]\r\n return sentiwordnet\r\n\r\n#TESTING\r\n#print(list(swn.senti_synsets('starting','v')))\r\n#print(list(swn.senti_synsets('start','v')))\r\n#print(list(swn.senti_synsets('love','v')))\r\n#list1=list(swn.senti_synsets('loving','v'))\r\n#print(list1[1])\r\n\r\n#text = ['I','do','not','love','pizza']\r\n#text2 = ['starting','hate','pizza']\r\n#tweets = {'1':text,'2':text2}\r\n#print(sentiwordnet_lex(tweets))\r\n","sub_path":"Part_A/sentiwordnet.py","file_name":"sentiwordnet.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"396265602","text":"import operator\nfrom functools import reduce\n\n\ndef is_prime(n):\n if n < 2:\n return False\n return all(n % i for i in range(2, n // 2 + 1))\n\n\ndef gen_prime_bigger(n):\n next_num = n + 1\n \"\"\"While breaks when finding a prime number\"\"\"\n while not is_prime(next_num):\n next_num += 1\n \"\"\"Prime number is retured\"\"\"\n return (next_num)\n\n\ndef print_godldbach_conjecture(n):\n if n % 2 != 0:\n print(\"Numarul nu este par\")\n return\n \"\"\"Generate a list of primes until n\"\"\"\n primes = [num for num in range(1, n) if is_prime(num)]\n \"\"\" Go trough the list of primes\"\"\"\n for prim1 in primes:\n \"\"\"Go trough the list of primes a second time\"\"\"\n for prim2 in primes[0:len(primes) // 2 + 1]:\n if (prim1 + prim2 == n):\n print(\"%d + %d = %d\" % (prim1, prim2, n))\n\n\ndef year_to_days(years):\n if years < 0:\n return False\n \"\"\"Calculate number of leap years\"\"\"\n leap_years = years // 4\n \"\"\"Add number of leap years to total days\"\"\"\n return (years * 365 + leap_years)\n\n\ndef prime_sibling(n):\n \"\"\"Generate the next prime number \"\"\"\n prime_num = gen_prime_bigger(n)\n while True:\n if is_prime(prime_num + 2):\n return prime_num, prime_num + 2\n prime_num = gen_prime_bigger(prime_num)\n\n\n\"\"\"Returns a list containing dividers of n\"\"\"\ndef get_dividers(n):\n return [d for d in range(1, (n // 2) + 1) if n % d == 0]\n\n\ndef prod_factor(n):\n dividers = get_dividers(n)\n prod = reduce(operator.mul, dividers) # Multiply all the dividers in list\n return prod\n\n\ndef calc_palindrom(n):\n \"\"\"Return reversed number\"\"\"\n return(int(str(n)[::-1]))\n\n\ndef is_perfect(n):\n dividers = get_dividers(n)\n if dividers:\n suma = reduce(operator.add, dividers) # Sum up all the dividers in list\n if suma == n:\n return True\n return False\n\n\ndef bigger_perfect(n):\n n += 1\n while not is_perfect(n):\n n += 1\n return(n)\n\n\n\"\"\"Return smaller prime number than n\"\"\"\ndef smaller_prime(n):\n n -= 1\n while not is_prime(n):\n n -= 1\n if n <= 0:\n return False\n return n\n\n\"\"\"\nReturn smaller perfect number than n\nIf not found return False\n\"\"\"\ndef smaller_perfect(n):\n n += 1\n while not is_perfect(n):\n n -= 1\n if n <= 0:\n return False\n return(n)\n\n\n\"\"\"Calculate greater than n number that is part of fibonacci series\"\"\"\ndef greater_fibo(n):\n f1 = 0\n f2 = 1\n while f2 <= n:\n f1, f2 = f2, f1 + f2\n return f2\n\n\"\"\"\nReturn product of prime numbers from list\nReturn False if no primes are present in list\n\"\"\"\ndef prime_list_product(nums):\n primes = [n for n in nums if is_prime(n)]\n if primes:\n return reduce(operator.mul, primes)\n return False\n\n\"\"\"\nReturn sum of prime numbers from list\nReturn False if no primes are present in list\n\"\"\"\ndef prime_list_sum(nums):\n primes = [n for n in nums if is_prime(n)]\n if primes:\n return reduce(operator.add, primes)\n return False\n\n\"\"\"\nReturn max prime number from list\nReturn False if no primes are present in list\n\"\"\"\ndef max_prime_list(nums):\n primes = [n for n in nums if is_prime(n)]\n if primes:\n return max(primes)\n return False\n\n\"\"\"\nReturn min prime number from list\nReturn False if no primes are present in list\n\"\"\"\ndef min_prime_list(nums):\n primes = [n for n in nums if is_prime(n)]\n if primes:\n return min(primes)\n return False\n\n\n\"\"\"\nReturn sum of non-prime numbers from list\nReturn False if no non-prime are present in list\n\"\"\"\ndef non_prime_list_sum(nums):\n non_primes = [n for n in nums if is_prime(n) is False]\n if non_primes:\n return reduce(operator.add, non_primes)\n return False\n","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"271567309","text":"'''\r\n75-Percent Free Space On Fixed Drives\r\n\r\nTaken from:http://timgolden.me.uk/python/wmi/cookbook.html\r\nUpgraded to Python 3 by Steve Shambles.\r\n\r\nYou may need to \"pip install wmi\" first.\r\n'''\r\nimport wmi\r\nc = wmi.WMI ()\r\nlong = int\r\nfor disk in c.Win32_LogicalDisk (DriveType=3):\r\n print (disk.Caption, \"%0.2f%% free\" % \\\r\n (100.0 * long (disk.FreeSpace) / long (disk.Size)))\r\n","sub_path":"Python-code-snippets-001-100/075-Percent Free Space On Fixed Drives.py","file_name":"075-Percent Free Space On Fixed Drives.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"192965761","text":"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nfrom .base import baseDecoder\r\nfrom ...registry import DECODER\r\n__author__ = \"Yu-Hsiang Huang\"\r\n\r\nclass ScaledDotProductAttention(nn.Module):\r\n ''' Scaled Dot-Product Attention '''\r\n\r\n def __init__(self, temperature, attn_dropout=0.1):\r\n super().__init__()\r\n self.temperature = temperature\r\n self.dropout = nn.Dropout(attn_dropout)\r\n self.softmax = nn.Softmax(dim=2)\r\n\r\n def forward(self, q, k, v, mask=None):\r\n\r\n attn = torch.bmm(q, k.transpose(1, 2))\r\n attn = attn / self.temperature\r\n\r\n if mask is not None:\r\n attn = attn.masked_fill(mask, -np.inf)\r\n\r\n attn = self.softmax(attn)\r\n attn = self.dropout(attn)\r\n output = torch.bmm(attn, v)\r\n\r\n return output, attn\r\n\r\n''' Define the sublayers in encoder/decoder layer '''\r\nimport numpy as np\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n#from transformer.Modules import ScaledDotProductAttention\r\n\r\n__author__ = \"Yu-Hsiang Huang\"\r\n@DECODER.register_module\r\nclass MultiHeadAttention(nn.Module):\r\n ''' Multi-Head Attention module '''\r\n\r\n def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):\r\n super().__init__()\r\n\r\n self.n_head = n_head\r\n self.d_k = d_k\r\n self.d_v = d_v\r\n\r\n self.w_qs = nn.Linear(d_model, n_head * d_k)\r\n self.w_ks = nn.Linear(d_model, n_head * d_k)\r\n self.w_vs = nn.Linear(d_model, n_head * d_v)\r\n nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))\r\n nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))\r\n nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))\r\n\r\n self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))\r\n self.layer_norm = nn.LayerNorm(d_model)\r\n\r\n self.fc = nn.Linear(n_head * d_v, d_model)\r\n nn.init.xavier_normal_(self.fc.weight)\r\n\r\n self.dropout = nn.Dropout(dropout)\r\n\r\n\r\n def forward(self, x):\r\n N, C, H, W = x.shape\r\n x = x.reshape(N, C, -1)\r\n x = x.contiguous().permute(0, 2, 1)\r\n q, k, v =x , x, x\r\n mask = None\r\n d_k, d_v, n_head = self.d_k, self.d_v, self.n_head\r\n\r\n sz_b, len_q, _ = q.size()\r\n sz_b, len_k, _ = k.size()\r\n sz_b, len_v, _ = v.size()\r\n\r\n residual = q\r\n\r\n q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)\r\n k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)\r\n v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)\r\n\r\n q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk\r\n k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk\r\n v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv\r\n if mask is not None:\r\n mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..\r\n output, attn = self.attention(q, k, v, mask=mask)\r\n\r\n output = output.view(n_head, sz_b, len_q, d_v)\r\n output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)\r\n\r\n output = self.dropout(self.fc(output))\r\n output = self.layer_norm(output + residual)\r\n\r\n output = output.contiguous().permute(0,2,1)\r\n output = output.reshape(N,C,H,W)\r\n return output\r\n\r\nclass PositionwiseFeedForward(nn.Module):\r\n ''' A two-feed-forward-layer module '''\r\n\r\n def __init__(self, d_in, d_hid, dropout=0.1):\r\n super().__init__()\r\n self.w_1 = nn.Conv1d(d_in, d_hid, 1) # position-wise\r\n self.w_2 = nn.Conv1d(d_hid, d_in, 1) # position-wise\r\n self.layer_norm = nn.LayerNorm(d_in)\r\n self.dropout = nn.Dropout(dropout)\r\n\r\n def forward(self, x):\r\n residual = x\r\n output = x.transpose(1, 2)\r\n output = self.w_2(F.relu(self.w_1(output)))\r\n output = output.transpose(1, 2)\r\n output = self.dropout(output)\r\n output = self.layer_norm(output + residual)\r\n return output\r\n\r\n\r\n\r\n@DECODER.register_module\r\nclass FullSelfAttention(baseDecoder):\r\n def __init__(self, n_head,d_model,d_k,d_v,dropout=0.1,\\\r\n predict_len=2, shared=True, in_channels=1024, fw=True, bw=True, res_connect=False):\r\n super(FullSelfAttention, self).__init__()\r\n self.res_connect = res_connect\r\n self.fw = fw\r\n self.bw = bw\r\n self.shared = shared\r\n self.predict_len = predict_len\r\n if bw:\r\n self.backward_blocks = nn.ModuleList()\r\n if shared:\r\n\r\n tmp = nn.Sequential(MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout))\r\n for i in range(predict_len):\r\n self.backward_blocks.append(tmp)\r\n else:\r\n for i in range(predict_len):\r\n print(\"the TMM is not shared\")\r\n self.backward_blocks.append(nn.Sequential(MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout)))\r\n if fw:\r\n self.forward_blocks = nn.ModuleList()\r\n if shared:\r\n tmp = nn.Sequential(MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout))\r\n for i in range(predict_len):\r\n self.forward_blocks.append(tmp)\r\n else:\r\n for i in range(predict_len):\r\n print(\"the TMM is not shared\")\r\n self.forward_blocks.append(nn.Sequential(MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout),\r\n MultiHeadAttention(n_head,d_model,d_k,d_v,dropout)))\r\n def forward(self, x ):\r\n # N C H W\r\n x = self.baseforward(x)\r\n return x\r\n","sub_path":"mmaction/models/tenons/decoder/selfattention.py","file_name":"selfattention.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"43553202","text":"import boto3\nfrom sqlalchemy.orm import Query\nfrom sqlalchemy import func\nfrom pydataapi import Result, DataAPI\nfrom typing import (\n Any,\n Dict,\n Optional,\n Type,\n Union,\n)\nfrom sqlalchemy.sql import Insert, Delete, Select, Update\nfrom WrappedResult import WrappedResult\n\n\nclass WrappedDataAPI(DataAPI):\n\n def __init__(self,\n *,\n secret_arn: str,\n resource_arn: Optional[str] = None,\n resource_name: Optional[str] = None,\n database: Optional[str] = None,\n transaction_id: Optional[str] = None,\n client: Optional[boto3.session.Session.client] = None,\n rollback_exception: Optional[Type[Exception]] = None,\n rds_client: Optional[boto3.session.Session.client] = None,):\n\n super().__init__(secret_arn=secret_arn, resource_arn=resource_arn,\n resource_name=resource_name, database=database,\n transaction_id=transaction_id, client=client,\n rollback_exception=rollback_exception,\n rds_client=rds_client)\n\n def _get_start_end(self, end, start=0, limit=999):\n while True:\n if start + limit >= end:\n yield (start, end)\n break\n tmp_end = start + limit\n yield (start, tmp_end)\n start = tmp_end\n start += 1\n\n def execute(self,\n query: Union[Query, Insert, Update, Delete, Select, str],\n parameters: Optional[Dict[str, Any]] = None,\n transaction_id: Optional[str] = None,\n continue_after_timeout: bool = True,\n database: Optional[str] = None,\n ) -> WrappedResult:\n if isinstance(query, (Query, Select)):\n qCount: Query = query.statement.with_only_columns([func.count()])\\\n .order_by(None)\n result: Result = super().execute(qCount)\n query_total: int = result.scalar()\n final_result = list()\n for start, end in self._get_start_end(query_total):\n sliceQuery: Query = query.slice(start, end)\n result: Result = super().execute(sliceQuery, parameters,\n transaction_id,\n continue_after_timeout,\n database)\n final_result.append(result)\n wResult: WrappedResult = WrappedResult(final_result)\n else:\n result: Result = super().execute(query, parameters, transaction_id,\n continue_after_timeout, database)\n wResult: WrappedResult = WrappedResult([result])\n return wResult\n","sub_path":"pydataapi/WrappedDataAPI.py","file_name":"WrappedDataAPI.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289432494","text":"import numpy as np \nimport os\nimport time\nimport datetime\nimport gc\nimport multiprocessing\nimport config\nimport random\n\n\ndef save_stock_return(stock_id, path, return_list = [1,2,4,8], Threshold = 0.2, fre = 5, day_num = 242, day_delete_num = 2, skip = 1):\n # 保存本地所有股票的收益率\n sto_path = path + \"/\" + stock_id\n x_finally_data = []\n y_finally_data = []\n for _ in return_list:\n y_finally_data.append([])\n # y_finally_data_1min = []\n # y_finally_data_2min = []\n # y_finally_data_4min = []\n # y_finally_data_8min = []\n id_date = []\n day_len = day_num - day_delete_num\n\n # 数据的整合过程\n init_data = np.load(sto_path)\n index1 = np.arange(int(len(init_data) / day_num)) * day_num\n index2 = index1 + 1\n index3 = (np.arange(int(len(init_data) / day_num)) + 1) * day_num - 1\n index4 = index3 - 1\n index5 = np.argwhere(init_data[index1, 1] == 0)\n index6 = [i + 1 for i in index5]\n index7 = np.argwhere(init_data[index3, 1] == 0)\n index8 = [i - 1 for i in index7]\n\n if len(index5) > 0:\n init_data[index5, 1] = init_data[index6, 1]\n init_data[index7, 4] = init_data[index8, 4]\n init_data[index2, 1] = init_data[index1, 1]\n init_data[index3, 4] = init_data[index1, 4]\n init_data[index2, 5] = init_data[index2, 5] + init_data[index1, 5]\n init_data[index4, 5] = init_data[index4, 5] + init_data[index3, 5]\n\n data_use_sub = np.delete(init_data, [index1, index3], axis=0)\n # 剔除全天停牌数据\n delete_index = []\n for i in np.arange(int(len(data_use_sub) / day_len)):\n sta_data = np.sum(data_use_sub[day_len * i:day_len * (i + 1), 1:])\n if sta_data == 0:\n delete_index.extend(np.arange(day_len * i, day_len * (i + 1)))\n\n # 保留剔除数据的时间和所在位置\n delete_day = np.unique(np.floor(np.array(delete_index) / day_len).astype(np.int))\n delete_day_date = data_use_sub[delete_day * day_len, 0]\n data_use = np.delete(data_use_sub, delete_index, axis=0)\n\n # 数据的整合过程\n i = 0\n while i < int(len(data_use) / day_len - fre - 1):\n # 切片数据\n sub_data_date = data_use[(day_len * (i + fre) - 1), 0].strftime(\"%Y%m%d\")\n sub_data_use = data_use[(day_len * i):(day_len * (i + fre) + max(return_list)), 1:]\n sub_time = data_use[(day_len * i):(day_len * (i + fre)), 0]\n index = np.argwhere(np.min(sub_data_use[:, :4], 1) == 0)\n\n # 剔除x_data不连续的切片数据\n if len(index) != 0:\n no_use = int(index[-1] / day_len + 1)\n i += no_use\n continue\n\n logit = np.logical_and(data_use[i * day_len, 0] < delete_day_date,\n data_use[(i + fre - 1) * day_len, 0] > delete_day_date)\n if any(logit):\n skip_date = delete_day_date[np.argwhere(logit > 0)[0]][0]\n data_day = data_use[np.arange(i * day_len, day_len * (i + fre), day_len), 0]\n breakpoint_position = np.array([i.days for i in (skip_date - data_day)])\n skip_mun = np.argwhere(breakpoint_position < 0)[0]\n\n if skip_mun == 4:\n skip = 2\n elif skip_mun == 3:\n skip = 1\n\n i += skip\n continue\n\n res_data = sub_data_use[(day_len * (fre - 1)):(day_len * fre + max(return_list)), 3]\n res_1 = ((res_data[1:] - res_data[:-1]) / res_data[:-1]).astype(np.float32)\n\n if len(np.argwhere(res_1 == 0)) < (len(res_1) * Threshold):\n for res in np.arange(len(return_list)):\n return_data = ((res_data[return_list[res]:] - res_data[:-return_list[res]]) / res_data[:-return_list[\n res]]).astype(np.float32)\n if (res + 1) == len(return_list):\n y_finally_data[res].append(return_data)\n else:\n y_finally_data[res].append(return_data[:-(return_list[-1] - return_list[res])])\n\n # res_2 = ((res_data[2:] - res_data[:-2])/res_data[:-2]).astype(np.float32)\n # res_4 = ((res_data[4:] - res_data[:-4])/res_data[:-4]).astype(np.float32)\n # res_8 = ((res_data[8:] - res_data[:-8])/res_data[:-8]).astype(np.float32)\n\n time_d = []\n for j in np.arange(len(sub_time)):\n sec = time.mktime(sub_time[j].timetuple()) / (60 * 60 * 24) - int(\n time.mktime(sub_time[j].timetuple()) / (60 * 60 * 24))\n time_d.append(sec)\n\n # y_finally_data_1min.append(res_1[:-7])\n # y_finally_data_2min.append(res_2[:-6])\n # y_finally_data_4min.append(res_4[:-4])\n # y_finally_data_8min.append(res_8)\n x_finally_data.append(np.hstack((sub_data_use[:-max(return_list)],\n np.array(time_d).reshape(len(time_d), 1))))\n id_date.append(np.array([stock_id[:-4], sub_data_date]))\n\n i += 1\n ####返回原始数据和收益率数据\n return (x_finally_data, y_finally_data, id_date)\n\n\ndef get_filelist(path):\n ####获取文件列表\n for dirpath, dirnames, filenames in os.walk(path):\n print(filenames)\n return filenames\n \n\ndef add_data(data): \n print(len(data[0]))\n x_data.extend(data[0])\n# y1_data.extend(data[1])\n# y2_data.extend(data[2])\n# y4_data.extend(data[3])\n# y8_data.extend(data[4])\n for list_n in np.arange(len(y_data)):\n y_data[list_n].extend(data[1][list_n])\n \n stock_inf.extend(data[2])\n print(len(x_data))\n \n if len(x_data) >100000:\n order.append(len(x_data))\n print(len(order))\n if(not os.path.exists(save_path + str(len(order)))):\n os.makedirs(save_path + str(len(order)))\n np.save(save_path + str(len(order)) + \"/x_data\", np.float32(x_data))\n# np.save(save_path + str(len(order)+1) + \"-y1_data\", np.float32(y1_data))\n# np.save(save_path + str(len(order)+1) + \"-y2_data\", np.float32(y2_data))\n# np.save(save_path + str(len(order)+1) + \"-y4_data\", np.float32(y4_data))\n# np.save(save_path + str(len(order)+1) + \"-y8_data\", np.float32(y8_data))\n for data in np.arange(len(return_list)):\n np.save(save_path + str(len(order)) + \"/y\" + str(return_list[data])+ \"_data\", y_data[data])\n \n np.save(save_path + str(len(order)) + \"/stock_inf\", stock_inf)\n \n x_data.clear()\n# y1_data.clear()\n# y2_data.clear()\n# y4_data.clear()\n# y8_data.clear()\n for mint in np.arange(len(return_list)):\n y_data[mint].clear()\n\n stock_inf.clear() \n gc.collect()\n \n \n\n\nif __name__ == \"__main__\":\n path = '/data/qin/stock_all/stock_minute'\n save_path = config.all_npy_path+'/'\n return_list = [1,3,7,15]\n# y1_data = []\n# y2_data = []\n# y4_data = []\n# y8_data = []\n stock_inf = []\n order = []\n x_data = []\n y_data = []\n for _ in return_list:\n y_data.append([])\n# slice_len = 50 ##所有股票的每次切片长度\n filelist = get_filelist(path = path)\n \n ###用30只股票测试 \n pool = multiprocessing.Pool(26)\n for i in np.arange(len(filelist)):\n stock_code = filelist[i]\n pool.apply_async(save_stock_return,\n (stock_code, path, return_list,), callback=add_data)\n\n pool.close()\n pool.join()\n\n print(\"计算结束\")\n # test = save_stock_return(\"000004.SZ.npy\", path = path)\n # print(test[2])\n order.append(len(x_data))\n print(len(order))\n if(not os.path.exists(save_path + str(len(order)))):\n os.makedirs(save_path + str(len(order)))\n np.save(save_path + str(len(order)) + \"/x_data\", np.float32(x_data))\n# np.save(save_path + str(len(order)+1) + \"-y1_data\", np.float32(y1_data))\n# np.save(save_path + str(len(order)+1) + \"-y2_data\", np.float32(y2_data))\n# np.save(save_path + str(len(order)+1) + \"-y4_data\", np.float32(y4_data))\n# np.save(save_path + str(len(order)+1) + \"-y8_data\", np.float32(y8_data))\n for data in np.arange(len(return_list)):\n np.save(save_path + str(len(order)) + \"/y\" + str(return_list[data])+ \"_data\", y_data[data])\n \n np.save(save_path + str(len(order)) + \"/stock_inf\", stock_inf)\n\n\n\n\n\n \n \n''' \n for i in np.arange(int(len(filelist)/slice_len)+1):\n pool = multiprocessing.Pool(4)\n data_result = pool.map(partial(save_stock_return, path = \"D:/hjq/Python/stock_minute\"),\n filelist[(i*slice_len):((i+1)*slice_len)])\n \n pool.close()\n pool.join()\n print(i)\n \n for j in np.arange(len(filelist[(i*slice_len):((i+1)*slice_len)])):\n x_data.extend(data_result[j][0])\n y1_data.extend(data_result[j][1])\n y2_data.extend(data_result[j][2])\n y4_data.extend(data_result[j][3])\n y8_data.extend(data_result[j][4])\n stock_inf.extend(data_result[j][5])\n \n print(len(x_data)) \n np.save(save_path + str(i) +\"-x_data.npy\", x_data)\n np.save(save_path + str(i) +\"-y1_data.npy\", y1_data)\n np.save(save_path + str(i) +\"-y2_data.npy\", y2_data)\n np.save(save_path + str(i) +\"-y4_data.npy\", y4_data)\n np.save(save_path + str(i) +\"-y8_data.npy\", y8_data)\n np.save(save_path + str(i) +\"-stock_inf.npy\", stock_inf)\n \n x_data.clear()\n y1_data.clear()\n y2_data.clear()\n y4_data.clear()\n y8_data.clear()\n stock_inf.clear()\n \n gc.collect()\n \n print(\"计算结束\")\n\n''' \n\n\n\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Interface/load_min_cta20180803_0945.py","file_name":"load_min_cta20180803_0945.py","file_ext":"py","file_size_in_byte":9813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"528579966","text":"import numbers\nimport scanner\n\nclass LoxRuntimeError(Exception):\n \"\"\"Raise when the Lox interpreter encounters a runtime error.\"\"\"\n def __init__(self, token, message):\n self.message = message\n self.token = token\n\n\ndef _stringify(obj):\n if obj is None:\n return \"nil\"\n else:\n return str(obj)\n\ndef _isTrue(obj):\n \"\"\"Nil and false are false, everything else is true.\"\"\"\n if obj is None:\n return False\n elif isinstance(obj, bool):\n return bool(obj)\n else:\n return True\n\ndef _isEqual(left, right):\n if left is None:\n if right is None:\n return True\n else:\n return False\n else:\n return left == right\n\ndef _concatOrAdd(operator, left, right):\n if isinstance(left, numbers.Number) and isinstance(right, numbers.Number):\n return float(left) + float(right)\n elif isinstance(left, str) and isinstance(right, str):\n return left + right\n else:\n raise LoxRuntimeError(operator, \"Operands must be two numbers or two strings.\")\n\ndef _checkNumberOperand(operator, operand):\n if isinstance(operand, numbers.Number):\n return\n\n raise LoxRuntimeError(operator, \"Operand must be a number.\")\n\ndef _checkNumberOperands(operator, left, right):\n if isinstance(left, numbers.Number) and isinstance(right, numbers.Number):\n return\n raise LoxRuntimeError(operator, \"Operands must be numbers.\")\n\n\nclass Interpreter:\n\n def __init__(self, lox):\n self._lox = lox\n\n def interpret(self, expression):\n try:\n value = self._evaluate(expression)\n print(_stringify(value))\n except LoxRuntimeError as error:\n self._lox.runtime_error(error)\n\n def _evaluate(self, expr):\n return expr.accept(self)\n\n\n\n def visitLiteral(self, expr):\n return expr.value\n\n def visitGrouping(self, expr):\n return self._evaluate(expr.expression)\n\n def visitUnary(self, expr):\n right = self._evaluate(expr.right)\n\n op_type = expr.operator.token_type\n\n if op_type is scanner.TokenType.MINUS:\n _checkNumberOperand(expr.operator, right)\n return -float(right)\n elif op_type is scanner.TokenType.BANG :\n return isTrue(right)\n\n return None\n\n def visitBinary(self, expr):\n left = self._evaluate(expr.left)\n right = self._evaluate(expr.right)\n\n op_type = expr.operator.token_type\n\n if op_type is scanner.TokenType.GREATER:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) >= float(right)\n\n elif op_type is scanner.TokenType.GREATER:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) >= float(right)\n\n elif op_type is scanner.TokenType.LESS:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) < float(right)\n\n elif op_type is scanner.TokenType.LESS_EQUAL:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) <= float(right)\n\n elif op_type is scanner.TokenType.EQUAL_EQUAL:\n return _isEqual(left, right)\n\n elif op_type is scanner.TokenType.BANG_EQUAL:\n return not _isEqual(left, right)\n\n elif op_type is scanner.TokenType.MINUS:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) - float(right)\n\n elif op_type is scanner.TokenType.PLUS:\n return _concatOrAdd(expr.operator, left, right)\n\n elif op_type is scanner.TokenType.SLASH:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) / float(right)\n\n elif op_type is scanner.TokenType.STAR:\n _checkNumberOperands(expr.operator, left, right)\n return float(left) * float(right)\n\n return None\n\n\n","sub_path":"interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"311757897","text":"import math\nimport statistics\n\nn = int(input())\nxL = list(map(int, input().split(\" \")))\n\nxL2 = []\nfor i in range(n):\n xL2.append([i, xL[i]])\nxL2 = sorted(xL2, key=lambda x: x[1])\n\nif n % 2 == 0:\n center = n // 2\n centers = [xL2[center - 1], xL2[center]]\n for i in range(n):\n if i == centers[0][0] or i == centers[1][0]:\n print(statistics.median(xL[:i] + xL[i + 1:]))\n else:\n if centers[0][1] < xL[i]:\n print(centers[0][1])\n else:\n print(centers[1][1])\nelse:\n center = n // 2\n centers = [xL2[center - 1], xL2[center], xL2[center + 1]]\n for i in range(n):\n if i == centers[0][0] or i == centers[1][0] or i == centers[2][0]:\n print(statistics.median(xL[:i] + xL[i + 1:]))\n else:\n if centers[0][1] < xL[i]:\n print((centers[0][1] + centers[1][1]) / 2)\n else:\n print((centers[1][1] + centers[2][1]) / 2)","sub_path":"brown_diff/abc094_c.py","file_name":"abc094_c.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"625755777","text":"from time import sleep\n\nimport schedule\n\n\ndef scheduled(duration):\n def decorator(function):\n def new_function(*args, **kwargs):\n d = int(duration[:-1])\n d_l = duration[-1]\n d_l_c = \"\"\n if d_l == \"s\":\n d_l_c = \"seconds\"\n elif d_l == \"m\":\n d_l_c = \"minutes\"\n elif d_l == \"h\":\n d_l_c = \"hour\"\n sch = getattr(schedule.every(d) ,d_l_c)\n sch.do(function)\n return function(*args, **kwargs)\n return new_function\n return decorator","sub_path":"services/scheduleJob/schedule_job.py","file_name":"schedule_job.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"645389847","text":"import serialization.codec_binary as BinaryCodec\nfrom serialization.serializator_base import BaseSerializator\nfrom uct.algorithm.mc_node import MonteCarloNode\nfrom uct.algorithm.mc_node_details import MonteCarloNodeDetails\n\n\nclass BinarySerializator(BaseSerializator):\n def __init__(self):\n super().__init__()\n self.extension = \"tree\"\n\n def save_node_to_path(self, node, path):\n bin_arrays = []\n self._encode_node(bin_arrays, node)\n\n with open(path, 'wb+') as file:\n for bin_array in bin_arrays:\n file.write(bin_array)\n\n def get_node_from_path(self, path):\n with open(path, \"rb\") as file:\n node, _ = self._decode_node(file)\n return node\n\n def _encode_node(self, bin_list, node):\n BinaryCodec.write_string(bin_list, node.details.state_name)\n BinaryCodec.write_integer(bin_list, len(node.children))\n for child in node.children:\n s = child.details\n if len(s.move_name) > 0:\n BinaryCodec.write_string(bin_list, s.move_name)\n BinaryCodec.write_integer(bin_list, s.visits_count)\n BinaryCodec.write_integer(bin_list, s.visits_count_pre_modified)\n BinaryCodec.write_float(bin_list, s.average_prize)\n self._encode_node(bin_list, child)\n\n def _decode_node(self, file):\n rc = MonteCarloNode()\n state_name = BinaryCodec.read_string(file)\n rc.details.state_name = state_name\n\n children_count = BinaryCodec.read_integer(file)\n for i in range(children_count):\n details = MonteCarloNodeDetails()\n details.move_name = BinaryCodec.read_string(file)\n details.visits_count = BinaryCodec.read_integer(file)\n details.visits_count_pre_modified = BinaryCodec.read_integer(file)\n details.average_prize = BinaryCodec.read_float(file)\n child, child_state_name = self._decode_node(file)\n details.state_name = child_state_name\n child.details = details\n rc.add_child_by_node(child)\n\n return rc, state_name\n","sub_path":"src/main/python/serialization/serializator_binary.py","file_name":"serializator_binary.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"241531730","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport numbers\nimport torch.nn.functional as F\nfrom models.GCN import *\n\n\nclass nconv(nn.Module):\n def __init__(self):\n super(nconv, self).__init__()\n\n def forward(self, x, A):\n x = x.permute(0, 2, 1)\n x = torch.einsum('cwl,vw->cvl', (x, A))\n x = x.transpose(1, 2)\n return x.contiguous()\n\n\nclass linear(nn.Module):\n def __init__(self, c_in, c_out, bias=True):\n super(linear, self).__init__()\n self.mlp = torch.nn.Conv1d(c_in, c_out, kernel_size=3, padding=2, dilation=2, padding_mode='circular')\n\n def forward(self, x):\n x = x.permute(0, 2, 1)\n return self.mlp(x).transpose(1, 2)\n\n\nclass mixprop(nn.Module):\n def __init__(self, c_in, c_out, gdep, dropout, alpha):\n # 16 16 2 0.3 0.05\n super(mixprop, self).__init__()\n self.nconv = nconv()\n self.mlp = linear(c_in, c_out)\n self.gdep = gdep\n self.dropout = dropout\n self.alpha = alpha\n\n def forward(self, x, adj):\n x = x.float()\n adj = adj.float()\n adj = adj + torch.eye(adj.size(0)).to(x.device)\n d = adj.sum(1)\n h = x\n out = [h]\n a = adj / d.view(-1, 1)\n for i in range(self.gdep):\n h = self.alpha * x + (1 - self.alpha) * self.nconv(h, a)\n out.append(h)\n ho = torch.cat(out, dim=1)\n ho = self.mlp(ho)\n return ho\n\n\nclass imp(nn.Module):\n def __init__(self, c_in, adj):\n # 16 16 2 0.3 0.05\n super(imp, self).__init__()\n self.adj = adj\n self.mlp = linear(c_in, c_in)\n self.lin = nn.Linear(c_in, c_in)\n\n\n def forward(self, x):\n self.adj = self.adj.float().to(x.device)\n x = x.permute(0, 2, 1)\n x = torch.einsum('cwl,vw->cvl', (x, self.adj))\n x = torch.tanh(x)\n x = x.transpose(1, 2)\n x = self.mlp(x)\n return self.lin(x)\n","sub_path":"models/mixprop.py","file_name":"mixprop.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"617243261","text":"#!/usr/bin/python3\n\n\"\"\"Island Parameter Task\"\"\"\n\n\ndef island_perimeter(grid):\n \"\"\"This will return the perimeter of the island\"\"\"\n x = 0\n nearby = 0\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if grid[r][c] == 1:\n x += 1\n if r > 0 and grid[r-1][c] == 1:\n nearby += 1\n if c > 0 and grid[r][c-1] == 1:\n nearby += 1\n return x * 4 - nearby * 2\n","sub_path":"0x1B-island_perimeter/0-island_perimeter.py","file_name":"0-island_perimeter.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"375991218","text":"import datetime\nimport math\nimport geopyspark as gps\nimport pytest\nfrom openeogeotrellis.geopysparkdatacube import GeopysparkDataCube\n\n\ndef test_resample_cube_spatial_single_level(imagecollection_with_two_bands_and_three_dates,imagecollection_with_two_bands_and_three_dates_webmerc):\n #print(imagecollection_with_two_bands_and_three_dates.pyramid.levels[0].to_spatial_layer(datetime.datetime(2017, 9, 25, 11, 37)).stitch())\n resampled = imagecollection_with_two_bands_and_three_dates.resample_cube_spatial(imagecollection_with_two_bands_and_three_dates_webmerc,method='cube')\n\n assert resampled.pyramid.levels[0].layer_metadata.crs == '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +no_defs '\n\n stitched = resampled.pyramid.levels[0].to_spatial_layer(datetime.datetime(2017, 9, 25, 11, 37)).stitch()\n print(stitched)\n assert stitched.cells[0][0][0] == 1.0\n assert stitched.cells[1][0][0] == 2.0\n\n\ndef test_resample__spatial_single_level(imagecollection_with_two_bands_and_three_dates, tmp_path):\n #print(imagecollection_with_two_bands_and_three_dates.pyramid.levels[0].to_spatial_layer(datetime.datetime(2017, 9, 25, 11, 37)).stitch())\n resampled = imagecollection_with_two_bands_and_three_dates.resample_spatial(resolution=100000,projection=3857)\n crs:str = resampled.pyramid.levels[0].layer_metadata.crs\n assert crs.startswith('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m')\n\n path = tmp_path / \"resampled.tiff\"\n resampled.save_result(path, format=\"GTIFF\")\n from osgeo.gdal import Info\n info = Info(str(path), format='json')\n print(info)\n assert math.floor(info['geoTransform'][1]) == 100000.0\n\ndef test_compute_new_layout():\n\n extent = gps.Extent(xmin=32.7901792, ymin=3.01934520952576, xmax=48.79017919999744, ymax=15.2098214)\n target_res = 0.008928571428569999\n newLayout = GeopysparkDataCube._layout_for_resolution(extent, gps.TileLayout(layoutCols=21, layoutRows=16, tileCols=256, tileRows=256), None,\n target_res)\n\n newExtent = newLayout.extent\n width = newExtent.xmax - newExtent.xmin\n height = newExtent.ymax - newExtent.ymin\n\n tileLayout = newLayout.tileLayout\n currentResolutionX = width / (tileLayout.tileCols * tileLayout.layoutCols)\n currentResolutionY = height / (tileLayout.tileRows * tileLayout.layoutRows)\n assert currentResolutionX == pytest.approx(target_res, 0.00000001)\n assert currentResolutionY == pytest.approx(target_res, 0.00000001)\n","sub_path":"tests/test_resample.py","file_name":"test_resample.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"228658119","text":"class stack:\n def __init__(self, size, init=None):\n self.top_index=-1\n self.size=size\n self.init=init\n self.storage=[init]*size\n\n def push(self, item):\n if self.top_index==self.size-1:\n print(\"OverflowError\")\n return\n self.top_index+=1\n self.storage[self.top_index]=item\n return True\n\n def pop(self):\n if self.top_index==-1:\n print(\"UnderflowError\")\n return \"UnderflowError\"\n pop_item=self.storage[self.top_index]\n self.storage[self.top_index]=self.init\n self.top_index-=1\n return pop_item\n \n def isEmpty(self):\n return True if self.top_index==-1 else False\n \n def top(self):\n return self.storage[self.top_index] if self.isEmpty() else \"EmptyStack\"\n\nclass node:\n def __init__(self):\n self.near=[]\n def add(self,item):\n if not self.check(item):\n self.near.append(item)\n def check(self, item):\n for i in self.near:\n if i==item:\n return True\n return False\n\ninput_list=list(map(int,input().split(\",\")))\n# 1,2,1,3,2,4,2,5,4,6,5,6,6,7,3,7\nmaximum=0\nfor i in input_list:\n if i>maximum:\n maximum=i\n\nnodes=[node() for _ in range(maximum+1)]\ntemp1,temp2=0,0\nfor i in range(len(input_list)):\n if i%2:\n temp2=input_list[i]\n nodes[temp1].add(temp2)\n nodes[temp2].add(temp1)\n else:\n temp1=input_list[i]\n\nstart=int(input())\nvisited=[False for _ in range(maximum+1)]\ns=stack(maximum+1)\nresult=[]\nv=start\nvisited[v]=True\nresult.append(str(v))\n\nwhile(True):\n temp=[]\n for i in nodes[v].near:\n if not visited[i]:\n temp.append(i)\n if temp!=[]:\n s.push(v)\n minimum=temp[0]\n for i in temp:\n if minimum>i:\n minimum=i\n v=minimum\n visited[v]=True\n result.append(str(v))\n else:\n if s.isEmpty():\n break\n else:\n v=s.pop()\nprint(\"-\".join(result))","sub_path":"SSAFY/data_stucture_and_algorithms/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"237047327","text":"from django import forms\nfrom MyUserApp.models import UserSignup\nfrom MyUserApp.models import ContactUs\n\n\nclass UserSignupForm(forms.ModelForm):\n class Meta:\n model = UserSignup\n exclude = [\"roleId\",\n \"userFullName\",\n \"userEmail\",\n \"userPassword\",\n \"userMobile\",\n \"userAge\",\n \"userAddress\",\n \"userCity\",\n \"userState\",\n \"userImage\",\n \"userOtp\",\n \"userOtptime\",\n \"userConfirmationlink\",\n \"userToken\",\n \"isAvailable\",\n \"isQueue\",\n \"isVerified\",\n \"isActive\",\n ]\n\n\nclass ContactUsForm(forms.ModelForm):\n class Meta:\n model = ContactUs\n exclude = [\"userEmail\",\n \"subject\",\n \"contactDate\",\n \"textArea\",\n ]\n\n\n\n","sub_path":"MyUserApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"200749623","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom collections import Counter\n\ndef home(request):\n return render(request, 'home.html')\n\ndef count(request):\n fulltext = request.GET['fulltext']\n wordlist = Counter(fulltext.split())\n mostcommon = wordlist.most_common(n=1)[0]\n\n return render(request, 'count.html', {\"fulltext\": fulltext, \n \"count\": len(wordlist), \n \"mostcommonword\": mostcommon[0],\n \"mostcommonwordoccurence\": mostcommon[1]})","sub_path":"wordcount/wordcount/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88579630","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 06 14:23:08 2016\n\n@author: engrs\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nx=np.arange(0,4*np.pi,0.1)\n\nf1=np.sin(x)\nf2=np.exp(-0.1*x)\nf3=f1*f2\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif') \na=plt.plot(x,f3)\nplt.title(r\"\\ Non-Convex Cost Function \",\n fontsize=20, color='black')\nplt.xlabel(r'\\textbf{$\\theta$}', fontsize=22)\nplt.ylabel(r'\\texbf{$j(\\theta)$}',fontsize=22)\nplt.grid()\n","sub_path":"non_convex_cost_function.py","file_name":"non_convex_cost_function.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"170471704","text":"#!/usr/bin/env python\n\"\"\"\nWords stat\n\"\"\"\npat_len = 2 # количество символов в комбинации для поиска\noutput = \"report\" + str(pat_len) + \".txt\"\nimport os\n\nMASS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\\\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\"'\"]\nSCRIPT = os.path.realpath(__file__)\nPATH = os.path.dirname(SCRIPT)\nWORDS = open(os.path.join(PATH, \"words.txt\"), \"rt\")\n\ndef arrayGen(chars, num):\n num = num - 1\n if num == 0:\n return chars\n i = 0\n tmp_dict = chars\n while i < num:\n i = i + 1\n new_dict = []\n for c in tmp_dict:\n for char in chars:\n new_dict.append(c+char)\n tmp_dict = new_dict\n return tmp_dict\n\npattern_dict = arrayGen(MASS, pat_len)\nret = {}\nfor word in WORDS:\n for pattern in pattern_dict:\n if ret.get(pattern, 0) == 0:\n ret[pattern] = 0\n upword = word.upper()\n ret[pattern] += upword.count(pattern)\nWORDS.close()\n\nreport = open(os.path.join(PATH, output), \"w\")\nreport.write(str(ret))\nreport.close()\n","sub_path":"submissions/5746c78163905b3a11d97bf9/src/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"351993271","text":"import time, json\nfrom collections import OrderedDict\n\nstart_time = time.time() # 初始时间戳\nrefer_file_path = \"/Users/alicewish/我的坚果云/图床表.txt\"\nhtml_file_path = '/Users/alicewish/我的坚果云/图床表HTML.txt' # TXT文件名\nmarkdown_file_path = '/Users/alicewish/我的坚果云/图床表Markdown.txt' # TXT文件名\n\n# ================按行读取参考文本并字典化================\ninput_dict = {} # 创建一个字典\ntitle_list = []\nwith open(refer_file_path) as fin:\n for line in fin:\n input_line = (line.replace('\\n', ''))\n if \"【\" in input_line: #标题\n title_name = input_line\n title_list.append(title_name)\n input_dict[title_name] = {}\n elif \"\\t\" in input_line: # 接受key value格式\n split_line = input_line.split(\"\\t\")\n key = split_line[0].zfill(2)\n markdown_value = split_line[1]\n if '', ')')\n input_dict[title_name][key] = markdown_value\n input_dict[title_name] = OrderedDict(input_dict[title_name])\n\ninput_dict = OrderedDict(input_dict)\nprint(input_dict)\n\n# ================写入TXT================\nmarkdown_line_list = []\nhtml_line_list = []\ntitle_list.sort()\nfor title_name in title_list:\n markdown_line_list.append(title_name)\n html_line_list.append(title_name)\n for k, v in input_dict[title_name].items():\n markdown_line_list.append(k + \"\\t\" + v)\n html_value = v.replace('![](', '')\n html_line_list.append(k + \"\\t\" + html_value)\n\ninfo = \"\\r\\n\".join(markdown_line_list)\nf = open(markdown_file_path, 'w')\ntry:\n f.write(info)\nfinally:\n f.close()\n\ninfo = \"\\r\\n\".join(html_line_list)\nf = open(html_file_path, 'w')\ntry:\n f.write(info)\nfinally:\n f.close()\n\n# f = open('/Users/alicewish/我的坚果云/图床表JSON.txt', 'w')\n# json.dump(input_dict, f)\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":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363147606","text":"#program prognose randome number\nimport random\nmax_numb = int(input(\"Enter max number for a game:\\n\"))\nnumber = random.randint(1, max_numb)\ntries = 1\nmax_tries = int(input(\"Max tries - \"))\ndef ask_number():\n\tusernumb = \"\"\n\twhile usernumb != number:\n\t\tglobal tries\n\t\tprint(\"Enter your number 1 - \", max_numb, \".Trie: \", tries, \"\\n\")\n\t\tusernumb = int(input())\n\t\ttries += 1\n\t\tif tries != max_tries:\n\t\t\tif usernumb > number:\n\t\t\t\tprint(\"Number is bigger\")\n\t\t\telse:\n\t\t\t\tprint(\"Number is smaller\")\n\t\telse:\n\t\t\tbreak\ndef congr():\n\tif tries != max_tries:\n\t\tprint(\"Congritulations!!!\")\n\telse:\n\t\tprint(\"You are looser\")\ndef main():\n\task_number()\n\tcongr()\nmain()\n","sub_path":"part6/test_6_2_random_number.py","file_name":"test_6_2_random_number.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"268439678","text":"# Put your solution here.\nimport networkx as nx\nimport random\nimport numpy as np\nfrom numpy import inf\n\n##find the nearest neighbour from u\ndef findneighbour(client,map1,u):\n neighbourlist=[]\n for i in range(1,client.v+1):\n if map1[i][u]!=0:\n neighbourlist.append(i)\n return neighbourlist\n\ndef MW(all_students,map1, client, epsilon):\n #print(all_students)\n botslocation = [] # record all bots locations\n remainbots = client.bots # record number of bots unfounded yet\n h = client.home # home\n all = set([i + 1 for i in range(client.v)])\n visited = set([h]) # visited vertices set\n unvisited = all - visited # unvisited vertices set\n xx = [1 / client.students] * (client.students) # Multi-Weight:x\n weight = xx.copy() # Multi-Weight:weight\n #I want to do the same for home, not the nearest\n ##first iertation: find the nearest neighbor from h\n mindis1 = inf\n v1 = 0 # store nearest neighbor from h\n for vv in findneighbour(client, map1, h):\n if map1[vv][h] < mindis1:\n mindis1 = map1[vv][h]\n v1 = vv\n break\n visited.add(v1) # add v1 into visited set\n\n ##first iteration: scout, remote and update\n weightsum = 0\n claim = client.scout(v1, all_students)\n #print(\"claim: \",claim)\n if client.remote(v1, h) == 0:\n for stu in range(client.students):\n if claim[stu + 1] == True:\n weight[stu] = xx[stu] * (1 - epsilon)\n weightsum += weight[stu]\n for stu in range(client.students):\n xx[stu] = weight[stu] / weightsum\n else:\n #botslocation.append(h)\n remainbots -= 1\n for stu in range(client.students):\n if claim[stu + 1] == False:\n weight[stu] = xx[stu] * (1 - epsilon)\n weightsum += weight[stu]\n for stu in range(client.students):\n xx[stu] = weight[stu] / weightsum\n visited.add(v1)\n unvisited.remove(v1)\n\n ##pick next vertex:\n while remainbots > 0:\n maxvote = 0 # mark the maximum score that a bot will be there\n un = 0 # unvisited vertex\n vn = 0 # visited vertex\n ##find the most possible vertex that a bot will be there\n wanted=[]\n for v in visited:\n for u in unvisited:\n if u in findneighbour(client, map1, v) and u not in wanted:\n wanted.append(u)\n for u in wanted:\n claim = client.scout(u, all_students)\n currvote = 0 # mark the current score that a bot will be there\n for stu in range(client.students):\n if claim[stu + 1] == True:\n currvote += xx[stu]\n if currvote > maxvote:\n maxvote = currvote\n vn = v\n un = u\n if un == 0: #very rare case, you may omit\n print(\"something goes wrong here\")\n un = unvisited.pop()\n visited.add(un)\n else:\n visited.add(un)\n unvisited.remove(un)\n claim = client.scout(un, all_students)\n if client.remote(un, vn) == 0:\n for stu in range(client.students):\n if claim[stu + 1] == True:\n weight[stu] = xx[stu] * (1 - epsilon)\n weightsum += weight[stu]\n for stu in range(client.students):\n xx[stu] = weight[stu] / weightsum\n else:\n botslocation.append(vn)\n remainbots -= 1\n for stu in range(client.students):\n if claim[stu + 1] == False:\n weight[stu] = xx[stu] * (1 - epsilon)\n weightsum += weight[stu]\n for stu in range(client.students):\n xx[stu] = weight[stu] / weightsum\n return client.bot_locations\n\ndef solve(client):\n client.end()\n client.start()\n\n all_students = list(range(1, client.students + 1))\n non_home = list(range(1, client.home)) + list(range(client.home + 1, client.v + 1))\n s = [] # the visited vertices\n logo = [0] * (client.v + 1) # initialize all vertices for chosen points\n map1 = np.zeros((client.v + 1, client.v + 1)) # matrix storing all the edge values\n summ = 0 # seek for dist in descending order\n dist = [inf] * (client.v + 1)\n prev = [inf] * (client.v + 1) # RECORD the previous vertex\n for u, v in client.G.edges:\n map1[u][v] = client.G[u][v]['weight']\n map1[v][u] = map1[u][v]\n if u == client.home:\n dist[v] = map1[u][v]\n prev[v] = u\n dist[client.home] = 0\n logo[client.home] = 1\n\n for t in range(1, client.v): # run v-1 iterations to get the edges\n now = inf # should be modified if the graph is connected\n min1 = inf\n pre = inf\n previous = 0 # initial\n for v in range(1, client.v + 1):\n if logo[v] == 0: # min among all not picked v and finite h->v\n for w in range(1, client.v + 1):\n if map1[w][v] < min1 and logo[w] == 1 and map1[w][v]!=0:\n now = v\n pre = w\n min1 = map1[w][v] # edge prev[v],v\n prev[now] = pre\n if now == inf: # not updated\n print(\"no!!!\")\n break\n logo[now] = 1 # as picked in the MST\n dist[now] = dist[prev[now]] + min1\n students=list(range(1,client.students+1))\n\n MW(students,map1,client,0.1)\n #print(client.bot_locations)\n #client.end()#break point here\n found=[0]*(client.v+1)\n for location in client.bot_locations:\n found[location]=1\n \n for t in range(1, len(dist) - 1):\n maxx = -1\n u = -1\n for v in range(1, len(dist)):\n if maxx < dist[v]:\n u = v\n maxx = dist[v]\n dist[u] = -1\n if found[u]:#u has one\n #print(\"u is \"+str(int(u))+\" prev u is \"+str(int(prev[u])))\n temp = client.remote(u, prev[u])\n #print(\"temp is \",temp)\n found[u]=0\n found[prev[u]]=1\n## if prev[u] == client.h:\n## summ += temp\n client.end()\n","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":6238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575233595","text":"import json\nimport logging\nimport requests\nimport sys\nfrom colorama import init, Fore, Back, Style\nfrom WopiValidatorExecutor.constants import *\nfrom xml.etree import ElementTree\n\ndef GetIndentedJsonDump(inputJson):\n return json.dumps(inputJson, sort_keys=True, indent=4, separators=(',', ': '))\n\ndef GetWopiTestEndpoint(wopiDiscoveryServiceUrl):\n logging.info(\"WOPI Discovery Service Url: \" + wopiDiscoveryServiceUrl)\n discoveryServiceResponse = requests.get(wopiDiscoveryServiceUrl)\n\n try:\n discoveryServiceResponse.raise_for_status()\n except requests.exceptions.HTTPError as exception:\n print(Fore.RED + \"Failed to retrieve WOPI Discovery Service XML: Check Logs for more information\")\n logging.critical(\"Failed to retrieve WOPI Discovery Service XML - HTTP ErrorCode: \", exception.Code)\n sys.exit(1)\n\n try:\n discoveryXml = ElementTree.fromstring(discoveryServiceResponse.content)\n wopiTestEndPointUrl = discoveryXml.find(WOPITESTAPPLICATION_NODE_PATH).attrib[WOPITESTAPPLICATION_URLSRC_ATTRIBUTE]\n except Exception as exception:\n print(Fore.RED + \"Failed to parse WOPI Discovery Service XML: Check Logs for more information\")\n logging.critical(\"Failed to parse WOPI Discovery Service XML - Exception Details:\", exception)\n sys.exit(1)\n\n return wopiTestEndPointUrl[:wopiTestEndPointUrl.find('?')]\n\ndef ExecuteWopiValidator(wopiDiscoveryServiceUrl, payload):\n # Initialize colorama to allow applying colors to the output text.\n init(autoreset=True)\n\n wopiTestEndPoint = GetWopiTestEndpoint(wopiDiscoveryServiceUrl)\n logging.info(\"WopiValidator TestEndpoint Url: \" + wopiTestEndPoint)\n\n print(Fore.CYAN + \"..........................WopiValidator Execution Starts....................................\\n\")\n\n # Get the TestUrls by calling WopiValidator Endpoint.\n testUrlResponse = requests.get(wopiTestEndPoint, params=payload)\n\n try:\n testUrlResponse.raise_for_status()\n except requests.exceptions.HTTPError as exception:\n print(Fore.RED + \"Execution Failed: Check Logs for more information\")\n logging.critical(\"Failed to retrieve TestUrls - HTTP ErrorCode: \", exception.Code)\n sys.exit(1)\n\n testurls = testUrlResponse.json()\n logging.info(\"TestUrls to be Executed : \\n\" + GetIndentedJsonDump(testurls))\n\n # Execute tests.\n for testurl in testurls:\n testResultResponse=requests.get(testurl)\n try:\n testResultResponse.raise_for_status()\n except requests.exceptions.HTTPError as exception:\n print(Fore.RED + \"Execution Failed: Check Logs for more information\")\n logging.critical(\"HTTP ErrorCode:\", exception.Code)\n sys.exit(1)\n\n # Log the json response for the test being executed.\n testResult = testResultResponse.json();\n logging.info(\"Result for TestUrl:\" + testurl + '\\n')\n logging.info(GetIndentedJsonDump(testResult))\n\n # Print the test result and failure reasons if any.\n testCase = testResult[TEST_NAME]\n errorMsg = testResult[TEST_ERROR_MSG]\n msgColor = Fore.GREEN\n if errorMsg:\n if errorMsg == TEST_ERROR_SKIPPED:\n msgColor = Fore.YELLOW\n print(testCase + msgColor + \"...Skipped...\\n\")\n else:\n msgColor = Fore.RED\n print(testCase + msgColor + \"...Failed...\\n\")\n print(msgColor + errorMsg + '\\n')\n requestDetails = testResult[REQUEST_DETAILS]\n for requestDetail in requestDetails:\n validationFailures = requestDetail[REQUEST_VALIDATION_FAILURE]\n failedRequestName = requestDetail[REQUEST_NAME]\n if validationFailures:\n print(msgColor + \"Request Failed: \" + failedRequestName)\n print(msgColor + \"*****************FailureReason Starts*********************\")\n for validationFailure in validationFailures:\n print(msgColor + validationFailure)\n print(msgColor + \"*****************FailureReason Ends***********************\\n\")\n else:\n print(testCase + msgColor + \"...Passed...\\n\")\n\n print(Fore.CYAN + \"..........................WopiValidator Execution Ends....................................\")","sub_path":"WopiValidatorExecutor/WopiValidatorExecutor/WopiValidatorExecutor.py","file_name":"WopiValidatorExecutor.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"20103386","text":"import torch\nimport torch.nn.functional as F\nimport numpy as np\nimport cv2\n\ndef warp_img(homography_mtx,tgt_img):\n \"\"\"\n\n homography_mtx is assumed to be 3 * 3\n tgt_img is assumed to be 1 * C * H * W\n \"\"\"\n mod_mtx = homography_mtx[0:2]\n mod_mtx = torch.unsqueeze(mod_mtx,0)\n grid = F.affine_grid(mod_mtx, tgt_img.shape)\n result = F.grid_sample(tgt_img,grid)\n return result\n\nif __name__ == '__main__':\n img = cv2.imread('Lenna.png')\n homography_mtx = torch.Tensor([[1,0,-1],[0,1,-1],[0,0,1]])\n \"\"\"\n Little note on warping in pytorch:\n Positive values indicate moving up/left\n Negative values indicate moving down/right\n Axis values are bounded between -2 and 2\n \"\"\"\n img_transpose = np.ascontiguousarray(img.transpose((2, 0, 1)))\n img = np.expand_dims(img_transpose,0)\n img = torch.from_numpy(img).float()\n result = warp_img(homography_mtx,img)\n result = torch.squeeze(result,0)\n result_img = result.numpy()\n result_img = result_img.transpose((1,2,0))\n cv2.imwrite('result.png',result_img)","sub_path":"warp_utils.py","file_name":"warp_utils.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"367925884","text":"\"\"\"create intervention table\n\nRevision ID: 75ecf480f5d3\nRevises: 03b1736791f4\nCreate Date: 2020-10-26 12:02:04.509654\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"75ecf480f5d3\"\ndown_revision = \"03b1736791f4\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"intervention\",\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"tree_id\", sa.Integer()),\n sa.Column(\"organization_id\", sa.Integer()),\n sa.Column(\"intervention_type\", sa.String()),\n sa.Column(\"intervenant\", sa.String()),\n sa.Column(\"intervention_start_date\", sa.DateTime()),\n sa.Column(\"intervention_end_date\", sa.DateTime()),\n sa.Column(\"date\", sa.DateTime(), nullable=True),\n sa.Column(\"done\", sa.Boolean, nullable=True),\n sa.Column(\"estimated_cost\", sa.Float()),\n sa.Column(\"required_documents\", sa.dialects.postgresql.JSONB()),\n sa.Column(\"required_material\", sa.dialects.postgresql.JSONB()),\n sa.Column(\"properties\", sa.dialects.postgresql.JSONB(), nullable=True),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.ForeignKeyConstraint([\"tree_id\"], [\"tree.id\"], ondelete=\"CASCADE\"),\n sa.ForeignKeyConstraint(\n [\"organization_id\"], [\"organization.id\"], ondelete=\"CASCADE\"\n ),\n )\n op.create_index(op.f(\"ix_intervention_id\"), \"intervention\", [\"id\"], unique=True)\n\n\ndef downgrade():\n op.drop_index(op.f(\"ix_intervention_id\"), table_name=\"intervention\")\n op.drop_table(\"intervention\")\n","sub_path":"backend/app/alembic/versions/75ecf480f5d3_create_intervention_table.py","file_name":"75ecf480f5d3_create_intervention_table.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"253400073","text":"\n\nfrom xai.brain.wordbase.nouns._scandalmonger import _SCANDALMONGER\n\n#calss header\nclass _SCANDALMONGERS(_SCANDALMONGER, ):\n\tdef __init__(self,): \n\t\t_SCANDALMONGER.__init__(self)\n\t\tself.name = \"SCANDALMONGERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"scandalmonger\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_scandalmongers.py","file_name":"_scandalmongers.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"614713100","text":"# cog.py\n\nfrom discord import File\nfrom discord.ext import commands\nfrom random import randrange\n\n# My OpenWeatherAPI module\nfrom openweathermapapi import requestWeatherData\n\nclass API(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name= 'weather', help= 'Given a zip code returns the weather.')\n async def weather(self, ctx, zipCode: int):\n await ctx.send(requestWeatherData(zipCode))\n\n\nclass BasicCommands(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name= 'copy', help= 'Sends a copy of the specified message to the same channel.')\n async def copy(self, ctx, *args):\n await ctx.send(' '.join(args))\n\n @commands.command(name= 'hello', help= 'Greets the user.')\n async def hello(self, ctx):\n await ctx.send(f\"Hello, {ctx.message.author}.\")\n\n @commands.command(name= 'image', help= 'Sends a picture of a python.')\n async def image(self, ctx):\n filePath = \"images\\\\snake1.jpg\"\n discordFile = File(filePath)\n await ctx.send(file= discordFile)\n\n @commands.command(name= 'roll', help= 'Rolls X (numDice) with max value of Y (maxDiceValue).')\n async def roll(self, ctx, numDice: int, maxDiceValue: int):\n outputString = ''\n sum = 0\n for i in range(numDice):\n randomInteger = randrange(maxDiceValue)\n sum += randomInteger + 1\n outputString += f\"Dice #{i + 1}: {randomInteger + 1}\\n\"\n outputString += f\"Sum is: {sum}\"\n await ctx.send(outputString)\n","sub_path":"cog.py","file_name":"cog.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"556589996","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2020 James\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nfrom typing import TYPE_CHECKING, Any, Dict, Optional, Tuple\n\nfrom ...abc import Message, Messageable\n\nif TYPE_CHECKING:\n from .bot import Bot\n from .commands import Command\n from .utils import Shlex\n\n\n__all__ = (\"Context\",)\n\n\nclass Context(Messageable):\n \"\"\"Represents the context of a command.\n\n Attributes\n ----------\n message: :class:`~steam.Message`\n The message the context was generated from.\n prefix: :class:`str`\n The prefix of the message the context was generated from\n author: :class:`~steam.User`\n The author of the message.\n channel: :class:`~steam.abc.BaseChannel`\n The channel the message was sent in.\n clan: Optional[:class:`~steam.Clan`]\n The clan the message was sent in ``None`` if the message wasn't sent in a clan.\n group: Optional[:class:`~steam.Group`]\n The group the message was sent in ``None`` if the message wasn't sent in a group.\n bot: :class:`~steam.ext.commands.Bot`\n The bot instance.\n command: Optional[:class:`~steam.ext.commands.Command`]\n The command the context is attached to.\n cog: Optional[:class:`~steam.ext.commands.Cog`]\n The cog the command is in.\n \"\"\"\n\n def __init__(self, **attrs):\n self.bot: \"Bot\" = attrs.get(\"bot\")\n self.message: Message = attrs.get(\"message\")\n self.command: Optional[\"Command\"] = attrs.get(\"command\")\n self.shlex: Optional[\"Shlex\"] = attrs.get(\"shlex\")\n self.prefix = attrs.get(\"prefix\")\n self.invoked_with: Optional[str] = attrs.get(\"invoked_with\")\n\n self.author = self.message.author\n self.channel = self.message.channel\n self.clan = self.message.clan\n self.group = self.message.group\n self._state = self.message._state\n\n if self.command is not None:\n self.cog = self.command.cog\n self.args: Optional[Tuple[Any, ...]] = None\n self.kwargs: Optional[Dict[str, Any]] = None\n\n def _get_message_endpoint(self):\n return self.channel._get_message_endpoint()\n\n def _get_image_endpoint(self):\n return self.channel._get_image_endpoint()\n","sub_path":"steam/ext/commands/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277210955","text":"#Author: Marta CICCARELLA\n#Univeristé Paris Diderot\n#Projet court: Septembre\n\n\ndef traduci_configurazioni_in_complex(c):\n \"\"\"\n Translate coordinates in complex numbers.\n \"\"\"\n c1=[]\n for myi in range(len(c)-1):\n #if myi==0:\n #c1.append(complex(c[myi][0]+c[myi][1]*1j))\n c1.append(complex(-c[myi][0]-c[myi][1]*1j+c[myi+1][0]+c[myi+1][1]*1j))\n # else:\n # c1.append(complex(c[myi][0]+c[myi][1]*1j-c[myi-1][0]-c[myi-1][1]*1j))\n return c1\n\n\ndef traduci_configurazioni_in_coordinate(c):\n \"\"\"\n Translate complex numbers in coordinates.\n \"\"\"\n c1 = [(0,0)]\n z=0.\n for myi in range(len(c)):\n #if myi>0:\n z=c[myi]+z\n #else:\n # z=0.\n #print(z)\n c1.append((int(z.real),int(z.imag)))\n return c1\n\n","sub_path":"code/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"148678880","text":"# external imports\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\n\n# internal import\nfrom reformat.aliases import reformat_aliases\nfrom create_log import ErrorLogModel\n\n\ndef get_aliases(driver, person_name):\n try:\n # search for aliases on babe\n xpath_aliases = driver.find_element_by_xpath(f\"//div[@id='bioarea']/h2\").text\n\n except (NoSuchElementException, TimeoutException):\n aliases = None\n log_message = \"Couldn't find {}'s known names on Beibisida\".format(person_name)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n else:\n log_message = \"{} aliases were found on Beibisida\".format(person_name)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n # reformat all the found aliases\n aliases = reformat_aliases(aliases=xpath_aliases, person_name=person_name)\n\n return aliases\n","sub_path":"beibisida/parts/get_aliases.py","file_name":"get_aliases.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"124711829","text":"#Count the number of appereances of an item in a list\n\ndef count_appeareances(l):\n \"\"\" take a list arg and count how many times the elements appear in the list\"\"\"\n d= {}\n for i in l:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n print ('the maximum no of apeareances is', max(d.values()))\n return d\n","sub_path":"FunNotFun/no_appear.py","file_name":"no_appear.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"515380826","text":"# https://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/\n\n# Complete the function below.\nN = 0\nE = 1\nS = 2\nW = 3\ndef isCircular(path):\n \n # Initialize starting point for robot as (0, 0) and starting\n # direction as N North\n x = 0\n y = 0\n dir = N\n \n # Traverse the path given for robot\n for i in range(len(path)):\n \n # Find current move\n move = path[i]\n \n # If move is left or right, then change direction\n if move == 'R':\n dir = (dir + 1)%4\n elif move == 'L':\n dir = (dir - 1)%4\n \n # If move is Go, then change x or y according to\n # current direction\n else: # if move == 'G'\n if dir == N:\n y += 1\n elif dir == E:\n x += 1\n elif dir == S:\n y -= 1\n else:\n x -= 1\n \n return (x == 0 and y == 0)\n\ndef doesCircleExist(commands):\n res = []\n dirs = [(1,0), (0,1), (-1,0), (0,-1)]\n for command in commands:\n if \"G\" not in command:\n res += \"YES\",\n continue\n new = command * 4\n di, p = 0, (0,0)\n for c in new:\n if c == \"G\":\n p = (p[0]+dirs[di][0], p[1]+dirs[di][1])\n elif c == \"R\":\n di = (di + 1) % 4\n elif c == \"L\":\n di = (di - 1) % 4\n if p == (0,0):\n res += \"YES\",\n else:\n res += \"NO\",\n return res\n# def doesCircleExist(commands):\n# res = []\n# for command in commands:\n# if isCircular(command*4):\n# res += \"YES\",\n# else:\n# res += \"NO\",\n# return res\n\nif __name__ == '__main__':\n from minitest import *\n\n with test(doesCircleExist):\n doesCircleExist([\"RGGRGGRGGRG\"]).must_equal([\"NO\"])\n doesCircleExist([\"LR\"]).must_equal([\"YES\"])\n\n\n\n","sub_path":"python/leetcode/hackerrank/encircular.py","file_name":"encircular.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"62016159","text":"#!/usr/bin/env python3\n\nimport sys\nsys.path.append(\"/usr/local/lib/\")\n\nimport os\nimport time\nfrom threading import Thread\nimport transformations as tf\nimport numpy as np\nimport math as m\nimport csv\n\nimport pyrealsense2 as rs\nfrom mycelium.components import Camera, RedisBridge\n\n\nclass CameraT265(Camera):\n\n def __init__(self):\n self.enable_pose_stream = False\n super().__init__(Camera.TYPE_T265) \n self._setup_save_dir()\n\n def _setup_parameters(self):\n self.scale_factor = self.cfg.t265['scale_factor']\n self.jump_threshold = self.cfg.t265['jump_threshold']\n self.jump_speed_threshold = self.cfg.t265['jump_speed_threshold']\n self.compass_enabled = self.cfg.t265['compass_enabled']\n self.heading_north_yaw = None\n self.rb_0 = RedisBridge(db=self.rd_cfg.databases['robot'])\n\n if self.compass_enabled:\n att = self.rb_0.get_key('ATTITUDE')\n if att is not None:\n self.heading_north_yaw = att['yaw']\n else:\n self.compass_enabled = False\n self.logger.log_warn(\"Failed to enable compass, could not retrieve attitude yaw\")\n \n self._initialize_compute_vars()\n # body offset - see initial script\n \n self.metadata = ['enable_pose_stream']\n\n def _initialize_compute_vars(self):\n self.prev_data = None\n self.reset_counter = 1\n self.current_confidence_level= None\n\n # Initialize with camera orientation\n self.H_aeroRef_T265Ref = np.array([[0,0,-1,0],[1,0,0,0],[0,-1,0,0],[0,0,0,1]])\n xr = m.radians(self.cfg.t265['camera_rot_x'])\n yr = m.radians(self.cfg.t265['camera_rot_y'])\n zr = m.radians(self.cfg.t265['camera_rot_z'])\n self.H_T265body_aeroBody = (tf.euler_matrix(xr, yr, zr)).dot(np.linalg.inv(self.H_aeroRef_T265Ref))\n self.H_aeroRef_aeroBody = None\n\n # V_aeroRef_aeroBody # vision speed estimate message\n # H_aeroRef_PrevAeroBody # vision position delta message\n\n self.frames = None\n self.pose_estimate_data = None\n\n def _setup_threads(self):\n super()._setup_threads()\n self.threads.append(Thread(target=self._save_pos_estimate))\n\n def _save_pos_estimate(self):\n csv_file = self.save_data_dir + 't265_pos_estimate.csv'\n file_exists = os.path.exists(csv_file)\n with open(csv_file, 'a+', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n if not file_exists:\n header = [\n 'current_time_us', \n 'local_x_pos',\n 'local_y_pos',\n 'local_z_pos',\n 'roll_angle',\n 'pitch_angle',\n 'yaw_angle',\n 'covariance',\n 'reset_counter',\n 'gps_1_lat',\n 'gps_1_lon',\n 'gps_1_fix_type',\n 'gps_2_lat',\n 'gps_2_lon',\n 'gps_2_fix_type'\n ]\n csvwriter.writerow(header) \n \n while not self.exit_threads:\n self.rb_i.add_key(self.pose_estimate_data, self.camera_type, 'vision_position_estimate', expiry=self.cfg.t265['save_redis_expiry'])\n self._save_csv(csvwriter, self.pose_estimate_data)\n\n def _save_csv(self, csvwriter, data):\n if data:\n try:\n data += self._get_gps_data()\n csvwriter.writerow(data)\n except Exception as e:\n self.logger.log_warn(\"Could not write pose data to csv: %s\" % e)\n\n def _realsense_notification_callback(notif):\n self.logger.log_info(notif)\n\n def _open_pipe(self):\n self.pipe = rs.pipeline()\n config = rs.config()\n config.enable_stream(rs.stream.pose)\n device = config.resolve(self.pipe).get_device()\n pose_sensor = device.first_pose_sensor()\n pose_sensor.set_notifications_callback(self._realsense_notification_callback)\n self.enable_pose_stream = True\n self.pipe.start(config)\n\n def _process_frames(self):\n self.frames = self.pipe.wait_for_frames()\n pose = self.frames.get_pose_frame()\n if pose:\n # Pose data consists of translation and rotation\n data = pose.get_pose_data()\n \n # Confidence level value from T265: 0-3, remapped to 0 - 100: 0% - Failed / 33.3% - Low / 66.6% - Medium / 100% - High \n self.current_confidence_level = float(data.tracker_confidence * 100 / 3) \n\n # In transformations, Quaternions w+ix+jy+kz are represented as [w, x, y, z]!\n H_T265Ref_T265body = tf.quaternion_matrix([data.rotation.w, data.rotation.x, data.rotation.y, data.rotation.z]) \n H_T265Ref_T265body[0][3] = data.translation.x * self.scale_factor\n H_T265Ref_T265body[1][3] = data.translation.y * self.scale_factor\n H_T265Ref_T265body[2][3] = data.translation.z * self.scale_factor\n\n # Transform to aeronautic coordinates (body AND reference frame!)\n self.H_aeroRef_aeroBody = self.H_aeroRef_T265Ref.dot(H_T265Ref_T265body.dot(self.H_T265body_aeroBody))\n \n # vision_speed_estimate_message\n # Calculate GLOBAL XYZ speed (speed from T265 is already GLOBAL)\n # V_aeroRef_aeroBody = tf.quaternion_matrix([1,0,0,0])\n # V_aeroRef_aeroBody[0][3] = data.velocity.x\n # V_aeroRef_aeroBody[1][3] = data.velocity.y\n # V_aeroRef_aeroBody[2][3] = data.velocity.z\n # V_aeroRef_aeroBody = H_aeroRef_T265Ref.dot(V_aeroRef_aeroBody)\n\n # Check for pose jump and increment reset_counter\n if self.prev_data is not None:\n delta_translation = [data.translation.x - self.prev_data.translation.x, data.translation.y - self.prev_data.translation.y, data.translation.z - self.prev_data.translation.z]\n delta_velocity = [data.velocity.x - self.prev_data.velocity.x, data.velocity.y - self.prev_data.velocity.y, data.velocity.z - self.prev_data.velocity.z]\n position_displacement = np.linalg.norm(delta_translation)\n speed_delta = np.linalg.norm(delta_velocity)\n\n if (position_displacement > self.jump_threshold) or (speed_delta > self.jump_speed_threshold):\n if position_displacement > self.jump_threshold:\n self.logger.log_warn(\"Position jumped by: %s\" % position_displacement)\n elif speed_delta > self.jump_speed_threshold:\n self.logger.log_warn(\"Speed jumped by: %s\" % speed_delta)\n self._increment_reset_counter()\n \n self.prev_data = data\n\n # Take offsets from body's center of gravity (or IMU) to camera's origin into account\n # if self.body_offset_enabled == 1:\n # H_body_camera = tf.euler_matrix(0, 0, 0, 'sxyz')\n # H_body_camera[0][3] = body_offset_x\n # H_body_camera[1][3] = body_offset_y\n # H_body_camera[2][3] = body_offset_z\n # H_camera_body = np.linalg.inv(H_body_camera)\n # H_aeroRef_aeroBody = H_body_camera.dot(H_aeroRef_aeroBody.dot(H_camera_body))\n\n # Realign heading to face north using initial compass data\n if self.compass_enabled:\n self.H_aeroRef_aeroBody = self.H_aeroRef_aeroBody.dot( tf.euler_matrix(0, 0, self.heading_north_yaw, 'sxyz'))\n\n self._compute_pose_estimate(data)\n\n def _increment_reset_counter(self):\n if self.reset_counter >= 255:\n self.reset_counter = 1\n self.reset_counter += 1\n\n def _compute_pose_estimate(self, data):\n if self.H_aeroRef_aeroBody is not None:\n current_time_us = int(round(time.time() * 1000000))\n\n # Setup angle data\n rpy_rad = np.array( tf.euler_from_matrix(self.H_aeroRef_aeroBody, 'sxyz'))\n\n # Setup covariance data, which is the upper right triangle of the covariance matrix, see here: https://files.gitter.im/ArduPilot/VisionProjects/1DpU/image.png\n # Attemp #01: following this formula https://github.com/IntelRealSense/realsense-ros/blob/development/realsense2_camera/src/base_realsense_node.cpp#L1406-L1411\n cov_pose = self.cfg.t265['linear_accel_cov'] * pow(10, 3 - int(data.tracker_confidence))\n cov_twist = self.cfg.t265['angular_vel_cov'] * pow(10, 1 - int(data.tracker_confidence))\n covariance = [cov_pose, 0, 0, 0, 0, 0,\n cov_pose, 0, 0, 0, 0,\n cov_pose, 0, 0, 0,\n cov_twist, 0, 0,\n cov_twist, 0,\n cov_twist]\n \n self.pose_estimate_data = [\n current_time_us,\n self.H_aeroRef_aeroBody[0][3], # Local X position\n self.H_aeroRef_aeroBody[1][3], # Local Y position\n self.H_aeroRef_aeroBody[2][3], # Local Z position\n rpy_rad[0],\t # Roll angle\n rpy_rad[1],\t # Pitch angle\n rpy_rad[2],\t # Yaw angle\n covariance, # Row-major representation of pose 6x6 cross-covariance matrix\n self.reset_counter # Estimate reset counter. Increment every time pose estimate jumps.\n ]\n self.logger.log_debug(\"Captured pose estimate data: %s\" % str(self.pose_estimate_data))","sub_path":"mycelium/camera_t265.py","file_name":"camera_t265.py","file_ext":"py","file_size_in_byte":9792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127331233","text":"#!/usr/bin python3\n\nimport scipy.io as sio\nfrom scipy import signal\nimport obspy\nfrom obspy import read\nfrom obspy.core import Stream\nfrom obspy.core import Trace\nfrom obspy.core import event\nfrom obspy import UTCDateTime\nimport obspy.signal\nimport matplotlib.pyplot as plt\nimport os.path\nimport time\nimport glob\nimport shutil\nimport numpy as np\nimport sys\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nimport matplotlib\n#matplotlib.rcParams.update({'font.size':20}) # Sets fontsize in figure\n\n\n## Norm\nnormlization = ''\nwhile (normlization != 'y' and normlization != 'n'):\n normlization = input('Do you want to norm (y/n)?')\n if (normlization == 'y'):\n if_norm = True\n if (normlization == 'n'):\n if_norm = False\n\nsig_freq = [12.0, 18.0, 5.0] # Second, Hz^-1 \n# Set phase to plot\nphase = 'Sdiff'\n# Set component to plot\ncomponent = 'BAT'\n# Set distance\ndistance = 106\n# Set models to plot\nevents=['OUT_REF_1s_mtp500kmPICKLES','OUT_ULVZ20km_1s_mtp500kmPICKLES','OUT_ULVZ5km_1s_mtp500kmPICKLES']\ncenterfreq = np.linspace(2,300,200, endpoint = False)\n\nsave_path = '/home/zl382/Documents/MATLAB/'\n\ns = distance\n# Load file\nseisfile = '/raid3/zl382/Data/Synthetics/' + events[0] + '/SYN_' + str(s) + '.PICKLE'\nseis = read(seisfile,format='PICKLE')\nseis.resample(10) # Resampling makes things quicker\n\nSdifftime = seis[0].stats['traveltimes'][phase] # find time of phase\n\nwaveform = sio.loadmat(save_path + 'dispersion.mat')['waveform']\n# toplot = np.reshape(sio.loadmat(save_path + 'dispersion.mat')['toplot'],(-1,1))\n\n# Cut window around phase on selected component\ntr = seis.select(channel=component)[0]\ntr.data[:] = 0\n\n\nw_start = np.argmin(np.abs(tr.times() - Sdifftime + 1300))\nw_end = np.argmin(np.abs(tr.times() - Sdifftime - 2800 + 1300))\n\n\nw0 = np.argmin(np.abs(tr.times() - Sdifftime + 100 + 1300))\nw1 = np.argmin(np.abs(tr.times() - Sdifftime - 2800 + 1300))\n\ntr.data[w_start:w_end] = waveform[0:w_end-w_start]\n\n# Copy trace and create signal\ntr1 = tr.copy()\ntr1 = tr1.filter('bandpass', freqmin=1/40.,freqmax=1/10.)\n\n# Plot reference phase with wide filter\nfig = plt.figure()\nax1 = plt.subplot(121)\nplt.plot(tr1.times()[w0:w1]-Sdifftime,tr1.data[w0:w1]/np.max(np.abs(tr1.data[w0:w1])),'k')\n# Raw Waveform plot normalized with maximum amplitude, Necessary!\n\n# Loop through centerfrequencies\nfor ft in range(len(centerfreq)):\n print(ft)\n f = centerfreq[ft]\n trf = tr.copy()\n # Filter copied trace around center frequency\n trf = trf.filter('bandpass', freqmin=1/(f*1.2),freqmax=1/(f*0.8))\n # Add normalized filtered arrival to the Frequency Fan\n if if_norm:\n norm = np.max(np.abs(trf.data[w0:w1]))/4. # Norm for fan\n else:\n norm = 1.0\n \n if ft == 0:\n toplot = trf.data[w0:w1]/norm\n else: \n toplot = np.vstack((toplot, trf.data[w0:w1]/norm)) # Stack array vertically\n\n plt.plot(trf.times()[w0:w1]-Sdifftime, f + trf.data[w0:w1]/norm, 'k') # Filtered Waveform plot in certain range normalized with maximum amplitude, not that Necessary!\n \n# Plot frequency fan\nax2 = plt.subplot(122)\nplt.pcolor(trf.times()[w0:w1]-Sdifftime,centerfreq,toplot,cmap='Greys')\n# Plot reference phase with wide filter\nplt.plot(tr1.times()[w0:w1]-Sdifftime,tr1.data[w0:w1]/np.max(np.abs(tr1.data[w0:w1])),'k')\n\nax1.set_xlabel('time (s)')\nax1.set_ylim([-1, max(centerfreq)])\nax1.set_xlim([-1400, 1500])\nax1.set_ylabel(r'(centre frequency)$^{-1}$ (s)',fontsize=18)\n\nax2.set_xlabel('time (s)')\nax2.set_ylim([-1, max(centerfreq)])\nax2.set_xlim([-1400, 1500])\nplt.suptitle('Dispersion Test with frequency' + ' Norm = ' + str(if_norm))\nplt.show()\n","sub_path":"Test/dispersion_test.py","file_name":"dispersion_test.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"165706819","text":"import tensorflow as tf \nfrom tools.lazy_property import lazy_property\n\n\nclass ImageCnnModel(object):\n\n def __init__(self):\n self.image = tf.placeholder(tf.float32, (None, 250, 151, 1), name=\"input_image\")\n self.label = tf.placeholder(tf.int64, (None), name=\"input_label\")\n\n #这边这种使用方式是可以的,即将tfread与整个模型直接连接起来,但是目前没有找到好的infer形式\n #self.image = train_image\n #self.label = train_label\n \n self.global_step = tf.Variable(1, trainable=False, name=\"global_steps\")\n self.learning_rate = tf.train.exponential_decay(\n learning_rate=0.01,\n global_step=self.global_step,\n decay_steps=120,\n decay_rate=0.9,\n staircase=True,\n name=\"learning_rate\",\n )\n self.train\n\n @lazy_property\n def train(self):\n # input size: (batch_size, 250, 151, 1)\n conv_layer_one = tf.contrib.layers.conv2d( \n inputs=self.image,\n num_outputs=32,\n kernel_size=(5, 5),\n padding='SAME',\n activation_fn=tf.nn.relu,\n stride=[2, 2],\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n biases_initializer=tf.zeros_initializer(),\n trainable=True,\n )\n #conv_layer_one_shape = conv_layer_one.get_shape()\n # conv_layer_one size: (batch_size, 125, 76, 32)\n pool_layer_one = tf.nn.max_pool(\n conv_layer_one,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME',\n )\n pool_layer_one_shape = pool_layer_one.get_shape()\n # pool_layer_one size: (batch_size, 63, 38, 32)\n conv_layer_two = tf.contrib.layers.conv2d(\n inputs=pool_layer_one,\n num_outputs=64,\n kernel_size=(5, 5),\n padding='SAME',\n activation_fn=tf.nn.relu,\n stride=[2, 2],\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n biases_initializer=tf.zeros_initializer(),\n trainable=True,\n )\n #conv_layer_two_shape = conv_layer_two.get_shape()\n # conv_layer_two size: (batch_size, 32, 19, 64)\n pool_layer_two = tf.nn.max_pool(\n conv_layer_two,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME',\n )\n pool_layer_two_shape = pool_layer_two.get_shape()\n # pool_layer_two size: (batch_size, 16, 10, 64)\n batch_size, image_hight, image_width, channel = pool_layer_two.get_shape()\n flattened = tf.reshape(pool_layer_two, [-1, image_width.value * image_hight.value * channel.value])\n fully_connect_layer_three = tf.contrib.layers.fully_connected(\n flattened,\n 512,\n activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n )\n hidden_layer_three = tf.nn.dropout(\n fully_connect_layer_three,\n 0.5,\n )\n\n final_layer = tf.contrib.layers.fully_connected(\n hidden_layer_three,\n 120,\n activation_fn=tf.nn.relu,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n )\n #return conv_layer_one_shape, pool_layer_one_shape, conv_layer_two_shape, pool_layer_two_shape\n\n return pool_layer_two_shape\n \"\"\"\n @lazy_property\n def loss(self):\n #对于标签是值(不是onehot形式)使用sparse方式\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.train, labels=tf.subtract(self.label, 1))\n loss_data = tf.reduce_mean(loss, name=\"loss\")\n return loss_data\n\n @lazy_property\n def optimize(self):\n #optimizer = tf.train.AdamOptimizer(self.learning_rate)\n optimizer = tf.train.MomentumOptimizer(self.learning_rate, momentum=0.6)\n optimize = optimizer.minimize(self.loss, global_step = self.global_step)\n return optimize\n\n @lazy_property\n def infer(self):\n result = tf.nn.softmax(self.train, name=\"softmax\")\n inference = tf.argmax(result, 1, name=\"inference\")\n return inference\n \"\"\"\n\n","sub_path":"cha5_cnn/model_size.py","file_name":"model_size.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"399434799","text":"import xml.etree.ElementTree as ET\n\nlist_words = []\ndict_words = {}\ndescription = ''\ntree = ET.parse('newsafr.xml')\n\nroot = tree.getroot()\n\ndescription = root.findall('channel/item')\n\nfor i in description:\n list_words.append(i.find('description').text.lower())\n\ndescription = ' '.join(list_words)\ndescription_list = description.split(' ')\n\nfor item in description_list:\n if len(item) > 6:\n dict_words[item] = description_list.count(item)\n\nlist_words = sorted(dict_words.items(), key=lambda item: (-item[1], item[0]))\n\nfor i in range(10):\n print(f'{i + 1}. Слово {list_words[i][0]} используется в тексте {list_words[i][1]} раза')\n","sub_path":"netology_basic_python_tasks/10_work_format_data/file_format_xml.py","file_name":"file_format_xml.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"150901721","text":"import redis\nimport os, sys\nfrom flask import Flask, render_template, jsonify, send_from_directory, request\nfrom flask_socketio import SocketIO, send, emit\nimport time\nfrom threading import Thread, Event\nimport eventlet\nimport json\nfrom datetime import *\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'twitter_pipeline'))\nfrom twitterStreaming import TwitterStreaming\n\neventlet.monkey_patch()\nbase_dir = os.path.abspath('../public')\napp = Flask(__name__, template_folder=base_dir)\nsocketio = SocketIO(app)\nts_thread = None\ns_thread = None\n\nclass sentimentValueStreaming(Thread):\n def __init__(self):\n Thread.__init__(self)\n self.r = redis.StrictRedis(host='localhost', port=6379, db=0)\n print('set up')\n self.p = self.r.pubsub()\n self.p.subscribe('sentimentData')\n self.event = Event()\n\n def run(self):\n print('start calculate value!!')\n time_format = '%a %b %d %H:%M:%S %z %Y'\n preTime = None\n curTime = None\n s_sum = 0\n s_count = 0\n while not self.event.is_set(): # <---- Added\n message = self.p.get_message()\n if message and isinstance(message['data'], bytes):\n sentimentData = json.loads(message['data'].decode('utf8'))\n curTime = datetime.strptime(sentimentData['created_at'], time_format)\n if preTime is None:\n preTime = curTime\n s_count += 1\n else:\n if preTime.time() > curTime.time():\n continue\n elif preTime.time() == curTime.time():\n s_sum += int(sentimentData['sentimentValue'])\n s_count += 1\n else:\n sentimentValue = s_sum / s_count\n created_at = str(curTime.hour).zfill(2) + ':' + \\\n str(curTime.minute).zfill(2) + ':' + \\\n str(curTime.second).zfill(2)\n socketio.emit('message',\n {'created_at': created_at, 'sentimentValue': sentimentValue},\n namespace='/streaming_socket')\n print(created_at + ' ' + str(sentimentValue))\n s_sum = int(sentimentData['sentimentValue'])\n s_count = 1\n preTime = curTime\n\n socketio.sleep(0.00001)\n def stop(self):\n print('stop calculate value!!')\n self.event.set()\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/')\ndef serve_static(filename):\n return send_from_directory(base_dir, filename)\n\n@app.route('/api/streaming/start', methods=['POST'])\ndef start_streaming():\n kws = []\n data = request.get_json()\n kws.append(data['query'])\n global ts_thread\n global s_thread\n if ts_thread is None and s_thread is None:\n print('start streaming!!')\n ts_thread = TwitterStreaming()\n s_thread = sentimentValueStreaming()\n ts_thread.start(keywords=kws)\n s_thread.start()\n else:\n print('stop first, then start streaming!!')\n ts_thread.stop()\n ts_thread.start(keywords=kws)\n\n return 'start streaming'\n\n@app.route('/api/streaming/stop', methods=['POST'])\ndef stop_streaming():\n global ts_thread\n global s_thread\n\n print('stop streaming!!')\n if ts_thread is not None:\n ts_thread.stop()\n if s_thread is not None:\n s_thread.stop()\n\n return 'stop streaming'\n\n\n\n\nif __name__ == '__main__':\n socketio.run(app, debug=True)\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"83756844","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 28 11:12:43 2018\r\n\r\n@author: lin\r\n\"\"\"\r\nimport numpy as np\r\n\r\nclass lin_bp:\r\n \r\n '''@\r\n x = (n_samples,feature)\r\n y = (n_samples,out_dim)\r\n nn_architecture is a list like [x.shape[-1],int,...,out_dim]\r\n nn_length dosn't count input x\r\n '''\r\n def __init__(self,x,y,nn_architecture,lr=0.001): \r\n self.weight_list = []\r\n self.bias_list = []\r\n self.shape_list = nn_architecture\r\n self.n_samples = x.shape[0]\r\n self.nn_length = len(nn_architecture)-1\r\n self.x = x.T\r\n self.y = y.T\r\n self.lr =lr\r\n #初始化 权值和偏置\r\n for i in range(len(nn_architecture)-1):\r\n self.weight_list.append(0.01*np.random.randn(nn_architecture[i+1],nn_architecture[i]))\r\n self.bias_list.append(0.01*np.random.randn(nn_architecture[i+1],1))\r\n \r\n def sigmoid(self,x,derivative=False):\r\n if derivative ==False:\r\n return 1/(1+np.exp(-x))\r\n else:\r\n return x*(1-x)\r\n #正向传播返回每层的Z 和非线性变换的结果 \r\n def prop(self):\r\n layers_z_list =[]\r\n layers_a_list =[]\r\n \r\n for i,W in enumerate(self.weight_list):\r\n if i==0:\r\n Z = np.dot(W,self.x)+self.bias_list[i]\r\n A = self.sigmoid(Z)\r\n else:\r\n Z = np.dot(W,layers_a_list[-1])+self.bias_list[i]\r\n A = self.sigmoid(Z)\r\n layers_z_list.append(Z)\r\n layers_a_list.append(A)\r\n return layers_z_list,layers_a_list\r\n \r\n def bprop(self):\r\n dw_list = []\r\n db_list = []\r\n dz_list = []\r\n layers_z_list,layers_a_list = self.prop()\r\n layers_z_list.reverse()\r\n layers_a_list.reverse()\r\n layers_a_list.append(self.x)\r\n \r\n for i in range(self.nn_length):\r\n if i ==0:\r\n dz = layers_a_list[0] - self.y\r\n dw = (np.dot(dz,layers_a_list[i+1].T))/self.n_samples\r\n db = (np.sum(dz,axis=1,keepdims=True))/self.n_samples\r\n else:\r\n dz = np.dot(self.weight_list[self.nn_length-i].T,dz_list[-1])*self.sigmoid(layers_a_list[i],derivative=True)\r\n dw = (np.dot(dz,layers_a_list[i+1].T))/self.n_samples\r\n db = (np.sum(dz,axis=1,keepdims=True))/self.n_samples\r\n\r\n dz_list.append(dz)\r\n dw_list.append(dw)\r\n db_list.append(db)\r\n dw_list.reverse()\r\n db_list.reverse()\r\n return dw_list,db_list\r\n\r\n def upgrade_wb(self):\r\n self.weight_list = [i-self.lr*j for i,j in zip(self.weight_list,self.bprop()[0])]\r\n self.bias_list = [i-self.lr*j for i,j in zip(self.bias_list,self.bprop()[1])]\r\n \r\n #预测函数 \r\n def predict(self,input_data):\r\n layers_a_list =[] \r\n for i,W in enumerate(self.weight_list):\r\n if i==0:\r\n Z = np.dot(W,input_data.T)+self.bias_list[i]\r\n A = self.sigmoid(Z)\r\n else:\r\n Z = np.dot(W,layers_a_list[-1])+self.bias_list[i]\r\n A = self.sigmoid(Z)\r\n layers_a_list.append(A)\r\n return layers_a_list[-1]\r\n \r\n \r\n ","sub_path":"lin_BP.py","file_name":"lin_BP.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"479647671","text":"import socket, sys\n\nIP = \"52.49.91.111\"\nPORT = 2003\nBUF_SIZ = 1024\n\ndir_x = [+1, +2, +2, +1, -1, -2, -2, -1]\ndir_y = [-2, -1, +1, +2, +2, +1, -1, -2]\n\ndef dir_to_str(dx, dy):\n res = \"\"\n if dy < 0:\n res += str(-dy) + \"u\"\n else:\n res += str(dy) + \"d\"\n if dx < 0:\n res += str(-dx) + \"l\"\n else:\n res += str(dx) + \"r\"\n return res\n\ndef recv(s):\n lines = s.recv(BUF_SIZ).decode().split('\\n')\n grid = []\n for line in lines:\n if len(line) == 0 or line[0] == '-':\n break\n grid.append(line)\n return grid\n\ndef send(s, msg):\n s.send(msg.encode())\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((IP, PORT))\n\nSIZE = 400 # Just make it big and start at center\nvisited = [[False for _ in range(SIZE)] for _ in range(SIZE)]\n\ndef dfs(px, py):\n visited[py][px] = True\n\n grid = recv(s)\n\n h = len(grid)\n w = len(grid[0])\n\n kx, ky = -1, -1\n for y in range(h):\n for x in range(w):\n if grid[y][x] == 'K':\n kx, ky = x, y\n\n for i in range(8):\n dx = dir_x[i]\n dy = dir_y[i]\n if grid[ky+dy][kx+dx] == 'P': # solved :)\n send(s, dir_to_str(dx, dy))\n print(s.recv(BUF_SIZ)) # Print key\n sys.exit(0)\n elif grid[ky+dy][kx+dx] == '.':\n px2 = px+dx\n py2 = py+dy\n if not visited[py2][px2]:\n send(s, dir_to_str(dx, dy))\n dfs(px2, py2)\n send(s, dir_to_str(-dx, -dy))\n recv(s)\n\ndfs(SIZE//2, SIZE//2)\n\ns.close()","sub_path":"06/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"385851260","text":"# -*- coding: utf-8 -*-\n\n# Redistribution and use in source and binary forms of this file,\n# with or without modification, are permitted. See the Creative\n# Commons Zero (CC0 1.0) License for more details.\n\n# Ambient Light Bricklet 2.0 communication config\n\nfrom commonconstants import THRESHOLD_OPTION_CONSTANTS\n\ncom = {\n 'author': 'Olaf Lüke ',\n 'api_version': [2, 0, 0],\n 'category': 'Bricklet',\n 'device_identifier': 259,\n 'name': ('AmbientLightV2', 'ambient_light_v2', 'Ambient Light 2.0', 'Ambient Light Bricklet 2.0'),\n 'manufacturer': 'Tinkerforge',\n 'description': {\n 'en': 'Measures ambient light up to 64000lux',\n 'de': 'Misst Umgebungslicht bis zu 64000Lux'\n },\n 'released': True,\n 'packets': [],\n 'examples': []\n}\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetIlluminance', 'get_illuminance'), \n'elements': [('illuminance', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['bf', {\n'en':\n\"\"\"\nReturns the illuminance of the ambient light sensor. The measurement range goes\nup to about 100000lux, but above 64000lux the precision starts to drop.\nThe illuminance is given in lux/100, i.e. a value of 450000 means that an\nilluminance of 4500lux is measured.\n\nIf you want to get the illuminance periodically, it is recommended to use the\ncallback :func:`Illuminance` and set the period with \n:func:`SetIlluminanceCallbackPeriod`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Beleuchtungsstärke des Umgebungslichtsensors zurück. Der Messbereich\nerstreckt sich bis über 100000Lux, aber ab 64000Lux nimmt die Messgenauigkeit\nab. Die Beleuchtungsstärke ist in Lux/100 angegeben, d.h. bei einem Wert von\n450000 wurde eine Beleuchtungsstärke von 4500Lux gemessen.\n\nWenn die Beleuchtungsstärke periodisch abgefragt werden soll, wird empfohlen\nden Callback :func:`Illuminance` zu nutzen und die Periode mit \n:func:`SetIlluminanceCallbackPeriod` vorzugeben.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetIlluminanceCallbackPeriod', 'set_illuminance_callback_period'), \n'elements': [('period', 'uint32', 1, 'in')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nSets the period in ms with which the :func:`Illuminance` callback is triggered\nperiodically. A value of 0 turns the callback off.\n\n:func:`Illuminance` is only triggered if the illuminance has changed since the\nlast triggering.\n\nThe default value is 0.\n\"\"\",\n'de':\n\"\"\"\nSetzt die Periode in ms mit welcher der :func:`Illuminance` Callback ausgelöst wird.\nEin Wert von 0 deaktiviert den Callback.\n\n:func:`Illuminance` wird nur ausgelöst wenn sich die Beleuchtungsstärke seit der\nletzten Auslösung geändert hat.\n\nDer Standardwert ist 0.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetIlluminanceCallbackPeriod', 'get_illuminance_callback_period'), \n'elements': [('period', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nReturns the period as set by :func:`SetIlluminanceCallbackPeriod`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Periode zurück, wie von :func:`SetIlluminanceCallbackPeriod`\ngesetzt.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetIlluminanceCallbackThreshold', 'set_illuminance_callback_threshold'), \n'elements': [('option', 'char', 1, 'in', THRESHOLD_OPTION_CONSTANTS),\n ('min', 'uint32', 1, 'in'),\n ('max', 'uint32', 1, 'in')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nSets the thresholds for the :func:`IlluminanceReached` callback. \n\nThe following options are possible:\n\n.. csv-table::\n :header: \"Option\", \"Description\"\n :widths: 10, 100\n\n \"'x'\", \"Callback is turned off\"\n \"'o'\", \"Callback is triggered when the illuminance is *outside* the min and max values\"\n \"'i'\", \"Callback is triggered when the illuminance is *inside* the min and max values\"\n \"'<'\", \"Callback is triggered when the illuminance is smaller than the min value (max is ignored)\"\n \"'>'\", \"Callback is triggered when the illuminance is greater than the min value (max is ignored)\"\n\nThe default value is ('x', 0, 0).\n\"\"\",\n'de':\n\"\"\"\nSetzt den Schwellwert für den :func:`IlluminanceReached` Callback.\n\nDie folgenden Optionen sind möglich:\n\n.. csv-table::\n :header: \"Option\", \"Beschreibung\"\n :widths: 10, 100\n \n \"'x'\", \"Callback ist inaktiv\"\n \"'o'\", \"Callback wird ausgelöst wenn die Beleuchtungsstärke *außerhalb* des min und max Wertes ist\"\n \"'i'\", \"Callback wird ausgelöst wenn die Beleuchtungsstärke *innerhalb* des min und max Wertes ist\"\n \"'<'\", \"Callback wird ausgelöst wenn die Beleuchtungsstärke kleiner als der min Wert ist (max wird ignoriert)\"\n \"'>'\", \"Callback wird ausgelöst wenn die Beleuchtungsstärke größer als der min Wert ist (max wird ignoriert)\"\n \nDer Standardwert ist ('x', 0, 0).\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetIlluminanceCallbackThreshold', 'get_illuminance_callback_threshold'), \n'elements': [('option', 'char', 1, 'out', THRESHOLD_OPTION_CONSTANTS),\n ('min', 'uint32', 1, 'out'),\n ('max', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nReturns the threshold as set by :func:`SetIlluminanceCallbackThreshold`.\n\"\"\",\n'de':\n\"\"\"\nGibt den Schwellwert zurück, wie von :func:`SetIlluminanceCallbackThreshold`\ngesetzt.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetDebouncePeriod', 'set_debounce_period'), \n'elements': [('debounce', 'uint32', 1, 'in')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nSets the period in ms with which the threshold callbacks\n\n* :func:`IlluminanceReached`,\n\nare triggered, if the thresholds\n\n* :func:`SetIlluminanceCallbackThreshold`,\n\nkeep being reached.\n\nThe default value is 100.\n\"\"\",\n'de':\n\"\"\"\nSetzt die Periode in ms mit welcher die Schwellwert Callbacks\n\n* :func:`IlluminanceReached`,\n \nausgelöst werden, wenn die Schwellwerte \n\n* :func:`SetIlluminanceCallbackThreshold`,\n \nweiterhin erreicht bleiben.\n\nDer Standardwert ist 100.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetDebouncePeriod', 'get_debounce_period'), \n'elements': [('debounce', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['ccf', {\n'en':\n\"\"\"\nReturns the debounce period as set by :func:`SetDebouncePeriod`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Entprellperiode zurück, wie von :func:`SetDebouncePeriod`\ngesetzt.\n\"\"\"\n}]\n})\n\n\ncom['packets'].append({\n'type': 'function',\n'name': ('SetConfiguration', 'set_configuration'), \n'elements': [('illuminance_range', 'uint8', 1, 'in', ('IlluminanceRange', 'illuminance_range', [('64000Lux', '64000lux', 0),\n ('32000Lux', '32000lux', 1),\n ('16000Lux', '16000lux', 2),\n ('8000Lux', '8000lux', 3),\n ('1300Lux', '1300lux', 4),\n ('600Lux', '600lux', 5)])),\n ('integration_time', 'uint8', 1, 'in', ('IntegrationTime', 'integration_time', [('50ms', '50ms', 0),\n ('100ms', '100ms', 1),\n ('150ms', '150ms', 2),\n ('200ms', '200ms', 3),\n ('250ms', '250ms', 4),\n ('300ms', '300ms', 5),\n ('350ms', '350ms', 6),\n ('400ms', '400ms', 7)]))],\n'since_firmware': [1, 0, 0],\n'doc': ['af', {\n'en':\n\"\"\"\nSets the configuration. It is possible to configure an illuminance range\nbetween 0-600lux and 0-64000lux and an integration time between 50ms and 400ms.\nThe upper bound of the illuminance range is not a hard limit. Typically the\nsensor will measure up to 150% of the configured illuminance range. But after\nthe 100% mark the precision starts to drop.\n\nA smaller illuminance range increases the resolution of the data. An\nincrease in integration time will result in less noise on the data.\n\nWith a long integration time the sensor might not be able to measure up to the\nhigh end of the selected illuminance range. Start with a big illuminance range\nand a short integration time then narrow it down to find a good balance between\nresolution and noise for your setup.\n\nThe default values are 0-8000lux illuminance range and 200ms integration time.\n\"\"\",\n'de':\n\"\"\"\nSetzt die Konfiguration. Es ist möglich den Helligkeitswertebereich zwischen\n0-600Lux und 0-64000Lux sowie eine Integrationszeit zwischen 50ms und 400ms\nzu konfigurieren. Die obere Grenze des Helligkeitswertebereich ist keine harte\nSchranke. Typischer Weise misst der Sensor bis zu 150% des eingestellten\nHelligkeitswertebereichs. Allerdings nimmt ab der 100% Marke die Messgenauigkeit\nab.\n\nEin kleinerer Helligkeitswertebereich erhöht die Auflösung der Daten. Eine\nErhöhung der Integrationszeit verringert das Rauschen auf den Daten.\n\nMit einer langen Integrationszeit kann es sein, dass der Sensor nicht bis zum\nMaximum der ausgewählten Helligkeitswertebereich messen kann. Am besten beginnt\nman mit einem großen Helligkeitswertebereich und einer kurzen Integrationszeit\nund tastet sich dann an eine gute Balance zwischen Auflösung und Rauschen der\nDaten heran.\n\nDie Standardwerte sind 0-8000Lux Helligkeitsbereich und 200ms Integrationszeit.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'function',\n'name': ('GetConfiguration', 'get_configuration'), \n'elements': [('illuminance_range', 'uint8', 1, 'out', ('IlluminanceRange', 'illuminance_range', [('64000Lux', '64000lux', 0),\n ('32000Lux', '32000lux', 1),\n ('16000Lux', '16000lux', 2),\n ('8000Lux', '8000lux', 3),\n ('1300Lux', '1300lux', 4),\n ('600Lux', '600lux', 5)])),\n ('integration_time', 'uint8', 1, 'out', ('IntegrationTime', 'integration_time', [('50ms', '50ms', 0),\n ('100ms', '100ms', 1),\n ('150ms', '150ms', 2),\n ('200ms', '200ms', 3),\n ('250ms', '250ms', 4),\n ('300ms', '300ms', 5),\n ('350ms', '350ms', 6),\n ('400ms', '400ms', 7)]))],\n'since_firmware': [1, 0, 0],\n'doc': ['af', {\n'en':\n\"\"\"\nReturns the configuration as set by :func:`SetConfiguration`.\n\"\"\",\n'de':\n\"\"\"\nGibt die Konfiguration zurück, wie von :func:`SetConfiguration`\ngesetzt.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'callback',\n'name': ('Illuminance', 'illuminance'), \n'elements': [('illuminance', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['c', {\n'en':\n\"\"\"\nThis callback is triggered periodically with the period that is set by\n:func:`SetIlluminanceCallbackPeriod`. The :word:`parameter` is the illuminance of the\nambient light sensor.\n\n:func:`Illuminance` is only triggered if the illuminance has changed since the\nlast triggering.\n\"\"\",\n'de':\n\"\"\"\nDieser Callback wird mit der Periode, wie gesetzt mit :func:`SetIlluminanceCallbackPeriod`,\nausgelöst. Der :word:`parameter` ist die Beleuchtungsstärke des Umgebungslichtsensors.\n\n:func:`Illuminance` wird nur ausgelöst wenn sich die Beleuchtungsstärke seit der\nletzten Auslösung geändert hat.\n\"\"\"\n}]\n})\n\ncom['packets'].append({\n'type': 'callback',\n'name': ('IlluminanceReached', 'illuminance_reached'), \n'elements': [('illuminance', 'uint32', 1, 'out')],\n'since_firmware': [1, 0, 0],\n'doc': ['c', {\n'en':\n\"\"\"\nThis callback is triggered when the threshold as set by\n:func:`SetIlluminanceCallbackThreshold` is reached.\nThe :word:`parameter` is the illuminance of the ambient light sensor.\n\nIf the threshold keeps being reached, the callback is triggered periodically\nwith the period as set by :func:`SetDebouncePeriod`.\n\"\"\",\n'de':\n\"\"\"\nDieser Callback wird ausgelöst wenn der Schwellwert, wie von \n:func:`SetIlluminanceCallbackThreshold` gesetzt, erreicht wird.\nDer :word:`parameter` ist die Beleuchtungsstärke des Umgebungslichtsensors.\n\nWenn der Schwellwert erreicht bleibt, wird der Callback mit der Periode, wie\nmit :func:`SetDebouncePeriod` gesetzt, ausgelöst.\n\"\"\"\n}]\n})\n\ncom['examples'].append({\n'type': 'getter',\n'name': 'Simple',\n'values': [(('Illuminance', 'illuminance', 'Illuminance'), 'uint32', 100.0, 'Lux/100', 'Lux', None, [])]\n})\n\ncom['examples'].append({\n'type': 'callback',\n'name': 'Callback',\n'values': [(('Illuminance', 'illuminance', 'Illuminance'), 'uint32', 100.0, 'Lux/100', 'Lux', None, 1000)]\n})\n\ncom['examples'].append({\n'type': 'threshold',\n'name': 'Threshold',\n'values': [(('Illuminance', 'illuminance', 'Illuminance'), 'uint32', 100.0, 'Lux/100', 'Lux', 10000, '>', 1000, 0, 'Too bright, close the curtains!')]\n})\n","sub_path":"configs/bricklet_ambient_light_v2_config.py","file_name":"bricklet_ambient_light_v2_config.py","file_ext":"py","file_size_in_byte":14263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540112240","text":"\n\nfrom xai.brain.wordbase.nouns._plunger import _PLUNGER\n\n#calss header\nclass _PLUNGERS(_PLUNGER, ):\n\tdef __init__(self,): \n\t\t_PLUNGER.__init__(self)\n\t\tself.name = \"PLUNGERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"plunger\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_plungers.py","file_name":"_plungers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"247970193","text":"import discord\nfrom discord.ext import commands\nfrom cogs.utils.dataIO import fileIO\nfrom cogs.utils.chat_formatting import box\nfrom cogs.utils import checks\nfrom __main__ import send_cmd_help\nimport os\nimport re\ntry:\n\timport tabulate\nexcept:\n\ttabulate = None\nimport time\n\n#TODO: Add chess clock\n\nclass Uttt:\n\t\"\"\"Play a match of Ultimate Tic Tac Toe\"\"\"\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.matches = fileIO(\"data/uttt/matches.json\", \"load\")\n\t\tself.scores = fileIO(\"data/uttt/scores.json\", \"load\")\n\t\tself.messages = {}\n\t\tself.threshold = 30\n\t\n\tdef _check(self, values):\n\t\tsquare = [ 1, 2, -3, -4, 0, 4, 3, -2, -1 ]\n\t\tfor i in range(len(values) - 2):\n\t\t\tfor j in range(i + 1, len(values) - 1):\n\t\t\t\tfor k in range(j + 1, len(values)):\n\t\t\t\t\tif abs(values[i] + values[j] + values[k]) == 3 and square[i] + square[j] + square[k] == 0:\n\t\t\t\t\t\treturn values[i]\n\t\treturn 0\n\t\n\tdef _get_match_num(self, server, user):\n\t\tmatch_num = -1\n\t\tif server.id in self.matches:\n\t\t\tfor i in range(len(self.matches[server.id])):\n\t\t\t\tif self.matches[server.id][i][\"user1\"] == user.id or self.matches[server.id][i][\"user2\"] == user.id:\n\t\t\t\t\tmatch_num = i\n\t\treturn match_num\n\t\n\tdef _create_match(self, server, user1, user2):\n\t\tbig_board = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]\n\t\tsmall_boards = []\n\t\tfor i in range(9):\n\t\t\tsmall_boards.append([])\n\t\t\tfor j in range(9):\n\t\t\t\tsmall_boards[i].append(0)\n\t\t\n\t\tif server.id not in self.matches:\n\t\t\tself.matches[server.id] = []\n\t\tself.matches[server.id].append({ \"user1\": user1.id, \"user1-name\": user1.name, \"user1-afk\": False, \"user2\": user2.id, \"user2-name\": user2.name, \"user2-afk\": False, \"big_board\": big_board, \"small_boards\": small_boards, \"turn\": 1, \"last_move\": -1, \"turn_count\": 0 })\n\t\tfileIO(\"data/uttt/matches.json\", \"save\", self.matches)\n\t\n\tdef _delete_match(self, server, match_num):\n\t\tif server.id in self.matches and len(self.matches[server.id]) > match_num:\n\t\t\tself.matches[server.id].pop(match_num)\n\t\t\tfileIO(\"data/uttt/matches.json\", \"save\", self.matches)\n\t\n\tdef _add_score(self, server, user, result):\n\t\tif server.id not in self.scores:\n\t\t\tself.scores[server.id] = {}\n\t\tif user not in self.scores[server.id]:\n\t\t\tself.scores[server.id][user] = { \"w\": 0, \"l\": 0, \"t\": 0 }\n\t\t\n\t\tif result == 1:\n\t\t\tself.scores[server.id][user][\"w\"] += 1\n\t\telif result == -1:\n\t\t\tself.scores[server.id][user][\"l\"] += 1\n\t\telse:\n\t\t\tself.scores[server.id][user][\"t\"] += 1\n\t\t\n\t\tfileIO(\"data/uttt/scores.json\", \"save\", self.scores)\n\t\t\n\tdef _char(self, val):\n\t\tfor j in range(3):\n\t\t\t\tif val == 1:\n\t\t\t\t\treturn \":x:\"\n\t\t\t\telif val == -1:\n\t\t\t\t\treturn \":o:\"\n\t\t\t\telse:\n\t\t\t\t\treturn u\"\\u2B1B\" #:black_large_square:\n\t\n\tdef _build_string(self, match):\n\t\tbig = match[\"big_board\"]\n\t\tsmall = match[\"small_boards\"]\n\t\t\n\t\tboard = \"**\" + match[\"user1-name\"] + \"** *vs* **\" + match[\"user2-name\"] + \"**\\n\" + (match[\"user1-name\"] if match[\"turn\"] == 1 else match[\"user2-name\"]) + \"'s turn\\n\" + (\"Next must be in square #\" + str(match[\"last_move\"] + 1) if match[\"last_move\"] != -1 and match[\"big_board\"][match[\"last_move\"]] == 0 else \"\") + \"\\n\"\n\t\tfor i in range(3):\n\t\t\tfor j in range(3):\n\t\t\t\tfor k in range(3):\n\t\t\t\t\tfor l in range(3):\n\t\t\t\t\t\tif big[3 * i + k] == 0:\n\t\t\t\t\t\t\tboard += self._char(small[3 * i + k][3 * j + l])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tboard += self._char(big[3 * i + k])\n\t\t\t\t\tboard += u\"\\u2B1C\" if k != 2 else \"\"\n\t\t\t\tboard += \"\\n\"\n\t\t\tboard += u\"\\u2B1C\" * 11 + \"\\n\" if i != 2 else \"\" #:white_large_square:\n\t\treturn board\n\t\n\tasync def _print(self, server, channel, match_num):\n\t\tif server.id not in self.messages:\n\t\t\tself.messages[server.id] = {}\n\t\tif match_num in self.messages[server.id]:\n\t\t\tawait self.bot.delete_message(self.messages[server.id][match_num])\n\t\tself.messages[server.id][match_num] = await self.bot.send_message(channel, self._build_string(self.matches[server.id][match_num]))\n\t\n\tasync def _handle_input(self, message):\n\t\tserver = message.server\n\t\tchannel = message.channel\n\t\tuser = message.author\n\t\tinput = re.search(r'^([1-9]) *([1-9])', message.content)\n\t\t\n\t\tif message.author.id != self.bot.user.id and input is not None:\n\t\t\tmatch_num = self._get_match_num(server, message.author)\n\t\t\t\n\t\t\tif match_num != -1:\n\t\t\t\tmatch = self.matches[server.id][match_num]\n\t\t\t\t\n\t\t\t\tif (user.id == match[\"user1\"] and match[\"user1-afk\"]) or (user.id == match[\"user2\"] and match[\"user2-afk\"]):\n\t\t\t\t\treturn\n\t\t\t\t\n\t\t\t\tA = int(input.group(1)) - 1\n\t\t\t\tB = int(input.group(2)) - 1\n\t\t\t\t\n\t\t\t\tif (match[\"last_move\"] == -1 or A == match[\"last_move\"] or match[\"big_board\"][match[\"last_move\"]] != 0) and match[\"small_boards\"][A][B] == 0:\n\t\t\t\t\tif (match[\"turn\"] == 1 and user.id == match[\"user1\"]) or (match[\"turn\"] == -1 and user.id == match[\"user2\"]):\n\t\t\t\t\t\tmatch[\"small_boards\"][A][B] = match[\"turn\"]\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor i in range(9):\n\t\t\t\t\t\t\tmatch[\"big_board\"][i] = self._check(match[\"small_boards\"][i])\n\t\t\t\t\t\t\n\t\t\t\t\t\twinner = self._check(match[\"big_board\"]) \n\t\t\t\t\t\tif winner != 0:\n\t\t\t\t\t\t\tif winner == 1:\n\t\t\t\t\t\t\t\tawait self.bot.send_message(channel, \"<@\" + match[\"user1\"] + \"> wins!\")\n\t\t\t\t\t\t\telif winner == -1:\n\t\t\t\t\t\t\t\tawait self.bot.send_message(channel, \"<@\" + match[\"user2\"] + \"> wins!\")\n\t\t\t\t\t\t\tself._add_score(server, match[\"user1\"], winner)\n\t\t\t\t\t\t\tself._add_score(server, match[\"user2\"], -winner)\n\t\t\t\t\t\t\tself._delete_match(server, match_num)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tempty = 0\n\t\t\t\t\t\t\tfor i in range(9):\n\t\t\t\t\t\t\t\tfor j in range(9):\n\t\t\t\t\t\t\t\t\tif match[\"small_boards\"][i][j] == 0:\n\t\t\t\t\t\t\t\t\t\tempty += 1\n\t\t\t\t\t\t\tif empty == 0:\n\t\t\t\t\t\t\t\tawait self.bot.send_message(channel, \"It's a tie!\")\n\t\t\t\t\t\t\t\tself._add_score(server, match[\"user1\"], 0)\n\t\t\t\t\t\t\t\tself._add_score(server, match[\"user2\"], 0)\n\t\t\t\t\t\t\t\tself._delete_match(server, match_num)\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t\t\t\t\t\tmatch[\"turn\"] *= -1\n\t\t\t\t\t\tmatch[\"turn_count\"] += 1\n\t\t\t\t\t\tmatch[\"last_move\"] = B\n\t\t\t\t\t\tfileIO(\"data/uttt/matches.json\", \"save\", self.matches)\n\t\t\t\t\t\tawait self._print(server, channel, match_num)\n\t\t\t\telse:\n\t\t\t\t\tawait self.bot.send_message(channel, \"Invalid move, you must select an empty slot\" + (\" from big square #\" + str(match[\"last_move\"] + 1)) if match[\"big_board\"][match[\"last_move\"]] == 0 else \"\")\n\t\n\t@commands.group(pass_context=True)\n\tasync def uttt(self, ctx):\n\t\t\"\"\"Challenge someone to a match of Ultimate Tic Tac Toe\"\"\"\n\t\tif ctx.invoked_subcommand is None:\n\t\t\tawait send_cmd_help(ctx)\n\t\n\t@uttt.command(pass_context=True)\n\tasync def play(self, ctx, player2 : discord.Member):\n\t\tserver = ctx.message.server\n\t\tchannel = ctx.message.channel\n\t\tplayer1 = ctx.message.author\n\t\t\n\t\tif player2.id == self.bot.user.id:\n\t\t\tawait self.bot.send_message(channel, \"Sorry, Peppermint is too fucking lazy to make an AI for me\")\n\t\t\treturn\n\t\telif player2.bot:\n\t\t\tawait self.bot.send_message(channel, \"I don't think that bot is smart enough to play...\")\n\t\t\treturn\n\t\telif player1.id == player2.id:\n\t\t\tawait self.bot.send_message(channel, \"https://youtu.be/Lr7CKWxqhtw\")\n\t\t\treturn\n\n\t\tmatch_num = self._get_match_num(server, player1)\n\t\tif match_num == -1:\n\t\t\tself._create_match(server, player1, player2)\n\t\t\tawait self._print(server, channel, match_num)\n\t\telse:\n\t\t\tawait self.bot.send_message(channel, \"You are already in a match against \" + self.matches[server.id][match_num][\"user2-name\"])\n\t\n\t@uttt.command(pass_context=True)\n\tasync def pause(self, ctx):\n\t\tserver = ctx.message.server\n\t\tchannel = ctx.message.channel\n\t\tplayer1 = ctx.message.author\n\t\t\n\t\tif match_num != -1:\n\t\t\tmatch = self.matches[server.id][match_num]\n\t\t\tif match[\"user1\"] == player1.id:\n\t\t\t\tmatch[\"user1-afk\"] == True\n\t\t\telse:\n\t\t\t\tmatch[\"user2-afk\"] == True\n\t\telse:\n\t\t\tawait self.bot.send_message(channel, \"Nothing to pause\")\n\t\n\t@uttt.command(pass_context=True)\n\tasync def resume(self, ctx):\n\t\tif match_num != -1:\n\t\t\tmatch = self.matches[server.id][match_num]\n\t\t\tif match[\"user1\"] == player1.id:\n\t\t\t\tmatch[\"user1-afk\"] == False\n\t\t\telse:\n\t\t\t\tmatch[\"user2-afk\"] == False\n\t\telse:\n\t\t\tawait self.bot.send_message(channel, \"Nothing to resume\")\n\t\n\t@uttt.command(pass_context=True)\n\tasync def board(self, ctx):\n\t\tserver = ctx.message.server\n\t\tchannel = ctx.message.channel\n\t\tuser = ctx.message.author\n\t\tmatch_num = self._get_match_num(server, user)\n\t\t\n\t\tif match_num != -1:\n\t\t\tawait self._print(server, channel, match_num)\n\t\telse:\n\t\t\tawait self.bot.send_message(channel, \"You are not currently in a match\")\n\t\n\t@uttt.command(pass_context=True)\n\tasync def rules(self, ctx):\n\t\tawait self.bot.send_message(ctx.message.channel, \"Like the original Tic-Tac-Toe, Player 1 is represented by X and Player 2 is represented by O. To start the game, Player 1 places an X on any one of the 81 empty squares, and then players alternate turns. However, after the initial move, players must play the board that mirrors the square from the previous player. If the next move is to a board that has already been won, then that player may choose an open square on any board for that turn. You win boards as usual, but you win the game when you win three boards together (across rows, columns or diagnols).\\n\\nFor instance, if the first move by X is the first image, player O is forced to play in the top-right corner as shown in the right image.\\nhttp://i.imgur.com/Jwo80U8.png\")\n\t\n\t@uttt.command(pass_context=True)\n\tasync def format(self, ctx):\n\t\tawait self.bot.send_message(ctx.message.channel, \"The command to select a slot is simply two numbers between 1 and 9 together, each representing the big square and the small square you want to select, respectively. Each number represents a slot as shown below:\\n1 2 3\\n4 5 6\\n7 8 9\\n\\nFor instance, \\\"57\\\" would select the bottom left corner of the center square\")\n\t\n\t@uttt.command(pass_context=True)\n\t@checks.admin_or_permissions()\n\tasync def delete(self, ctx, match_num):\n\t\tserver = ctx.message.server\n\t\tmatch_num = int(match_num)\n\t\t\n\t\tself._delete_match(server, match_num)\n\t\n\t@commands.command(pass_context=True)\n\tasync def forfeit(self, ctx):\n\t\tserver = ctx.message.server\n\t\tchannel = ctx.message.channel\n\t\tuser = ctx.message.author\n\t\tmatch_num = self._get_match_num(server, user)\n\t\t\n\t\tif match_num != -1:\n\t\t\tawait self.bot.send_message(channel, user.mention + \" decided to forfeit\")\n\t\t\tmatch = self.matches[server.id][match_num]\n\t\t\t\n\t\t\tself._add_score(server, user.id, -1)\n\t\t\tif match[\"turn_count\"] >= self.threshold:\n\t\t\t\tif match[\"user1\"] == user.id:\n\t\t\t\t\tself._add_score(server, match[\"user2\"], 1)\n\t\t\t\telse:\n\t\t\t\t\tself._add_score(server, match[\"user1\"], 1)\n\t\t\t\n\t\t\tself._delete_match(server, match_num)\n\t\telse:\n\t\t\tawait self.bot.send_message(channel, \"You can't forfeit if you are not in a match\")\n\t\n\t@commands.command(pass_context=True)\n\tasync def score(self, ctx, user : discord.Member = None):\n\t\tserver = ctx.message.server\n\t\tif user == None:\n\t\t\tuser = ctx.message.author\n\t\t\n\t\tif server.id not in self.scores or user.id not in self.scores[server.id]:\n\t\t\tawait self.bot.send_message(ctx.message.channel, user.name + \" has no scores\")\n\t\telse:\n\t\t\tscores = self.scores[server.id][user.id]\n\t\t\tawait self.bot.send_message(ctx.message.channel, user.name + \" has \" + str(scores[\"w\"]) + \" win\" + (\"s\" if scores[\"w\"] != 1 else \"\") + \", \" + str(scores[\"l\"]) + \" los\" + (\"es\" if scores[\"l\"] != 1 else \"s\") + \" and \" + str(scores[\"t\"]) + \" tie\" + (\"s\" if scores[\"t\"] != 1 else \"\"))\n\t\n\t@commands.command(pass_context=True)\n\tasync def scoreboard(self, ctx):\n\t\tserver = ctx.message.server\n\t\tchannel = ctx.message.channel\n\t\t\n\t\tmember_ids = [ m.id for m in server.members ]\n\t\tuttt_server_members = [ key for key in self.scores[server.id].keys() if key in member_ids ]\n\t\tnames = list(map(lambda mid: discord.utils.get(server.members, id=mid), uttt_server_members))\n\t\twins = list(map(lambda mid: self.scores[server.id][mid][\"w\"], uttt_server_members))\n\t\tloses = list(map(lambda mid: self.scores[server.id][mid][\"l\"], uttt_server_members))\n\t\tties = list(map(lambda mid: self.scores[server.id][mid][\"t\"], uttt_server_members))\n\t\t\n\t\theaders = [ \"User\", \"Wins\", \"Loses\", \"Ties\" ]\n\t\tbody = sorted(zip(names, wins, loses, ties), key = lambda tup: tup[1], reverse=True)[:10]\n\t\ttable = tabulate.tabulate(body, headers, tablefmt=\"psql\")\n\t\tawait self.bot.send_message(channel, box(table))\n\t\ndef check_folder():\n\tif not os.path.exists(\"data/uttt\"):\n\t\tos.makedirs(\"data/uttt\")\n\ndef check_file():\n\tmatches = {}\n\tscores = {}\n\t\n\tf = \"data/uttt/matches.json\"\n\tif not fileIO(f, \"check\"):\n\t\tfileIO(f, \"save\", matches)\n\t\n\tf = \"data/uttt/scores.json\"\n\tif not fileIO(f, \"check\"):\n\t\tfileIO(f, \"save\", scores)\n\ndef setup(bot):\n\tif tabulate is None:\n\t\traise RuntimeError(\"Run `pip install tabulate` to use Karma.\")\n\tcheck_folder()\n\tcheck_file()\n\tn = Uttt(bot) \n\tbot.add_listener(n._handle_input, \"on_message\")\n\tbot.add_cog(n)\n","sub_path":"uttt/uttt.py","file_name":"uttt.py","file_ext":"py","file_size_in_byte":12524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"119894542","text":"# Imports the monkeyrunner modules used by this program\nfrom com.android.monkeyrunner import MonkeyRunner, MonkeyDevice\n\n# Connects to the current device, returning a MonkeyDevice object\ndevice = MonkeyRunner.waitForConnection()\n\nMonkeyRunner.sleep(1)\n\n# Installs the Android package. Notice that this method returns a boolean, so you can test\n# to see if the installation worked.\ndevice.installPackage('C:/muphicforAndroid/muphic-for-Android/muphic-for-Android/bin/muphic-for-Android.apk')\n\nMonkeyRunner.sleep(1)\n\n# sets a variable with the package's internal name\npackage = 'project.muphic.Rikitakelab'\n\n# sets a variable with the name of an Activity in the package\nactivity = 'project.muphic.Rikitakelab.Muphic'\n\n# sets the name of the component to start\nrunComponent = package + '/' + activity\n\n# Runs the component\ndevice.startActivity(component=runComponent)\n\n\n\ndispWidth=int(device.getProperty('display.width'))\ndispHeight=int(device.getProperty('display.height'))\n\nMonkeyRunner.sleep(0.5)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# TitleWindow\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/Title.png','png')\n\n\n\ndevice.touch(787,363,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(787,363,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# Story Create Window\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/StoryCreateWindow.png','png')\n\n\n\ndevice.touch(dispWidth-10,290,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-10,290,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# Music Create Window\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/MusicCreateWindow.png','png')\n\n\n\ndevice.touch(1000,50,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(1000,50,MonkeyDevice.UP)\n\ndevice.touch(dispWidth-10,385,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-10,385,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# BackGround Select\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/BackGroundSelect.png','png')\n\n\n\ndevice.touch(dispWidth-16,35,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-16,35,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# BacktoStory\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/BacktoStory.png','png')\n\n\n\ndevice.touch(dispWidth-10,385,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-10,385,MonkeyDevice.UP)\n\ndevice.touch(191,35,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(191,35,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# Character Select\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/CharacterSelect.png','png')\n\n\n\ndevice.touch(21,75,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(21,75,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# Push BoyButton\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/PushBoyButton.png','png')\n\n\n\ndevice.touch(16,35,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(16,35,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\n# Takes a screenshot\nresult = device.takeSnapshot()\n\n# Back Back Ground Select\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/BackBackGroundSelect.png','png')\n\n\n\ndevice.touch(dispWidth-16,35,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-16,35,MonkeyDevice.UP)\n\ndevice.touch(dispWidth-10,100,MonkeyDevice.DOWN)\nMonkeyRunner.sleep(0.1)\ndevice.touch(dispWidth-10,100,MonkeyDevice.UP)\n\nMonkeyRunner.sleep(0.1)\n\nresult=device.takeSnapshot()\n\n#Back to Title from Story Create Window\nresult.writeToFile('C:/muphicforAndroid/muphic-for-Android/Screenshot/BackTitle.png','png')\n\n\n\ndevice.press('KEYCODE_BACK',MonkeyDevice.DOWN_AND_UP)","sub_path":"muphictest.py","file_name":"muphictest.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631520716","text":"import socket\n\nLOCALHOST = '127.0.0.1'\nPORT = 65432\nBUFFER_SIZE = 1024\n\nquery = input('Enter the request code - ')\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n \n s.connect((LOCALHOST, PORT))\n s.send(bytes(query,'utf-8'))\n data = s.recv(BUFFER_SIZE)\n\n print (\"Received data :\", data.decode('utf-8'))\n s.close()\n","sub_path":"Sem 4/CN_Lab/PS_4/1/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"11586176","text":"import demistomock as demisto # noqa: F401\nfrom CommonServerPython import * # noqa: F401\n\n\nimport re\n\n\ndef get_plain_text(html_regex):\n data = ''\n if html_regex and html_regex.group(0):\n data = re.sub(r'<.*?>', '', html_regex.group(0))\n entities = {'quot': '\"', 'amp': '&', 'apos': \"'\", 'lt': '<', 'gt': '>', 'nbsp': ' ',\n 'copy': '(C)', 'reg': '(R)', 'tilde': '~', 'ldquo': '\"', 'rdquo': '\"', 'hellip': '...'}\n for e in entities:\n data = data.replace(f'&{e};', entities[e])\n return data\n\n\ndef text_from_html(args):\n html = args['html']\n html_tag = args.get('html_tag', 'body')\n\n body = re.search(fr'<{html_tag}.*/{html_tag}>', html, re.M + re.S + re.I + re.U)\n data = get_plain_text(body)\n return data if data != '' else 'Could not extract text'\n\n\nif __name__ in [\"__builtin__\", \"builtins\"]:\n result = text_from_html(demisto.args())\n demisto.results(result)\n","sub_path":"Packs/CommonScripts/Scripts/TextFromHTML/TextFromHTML.py","file_name":"TextFromHTML.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"330060391","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2021-04-17 10:33\n@Auth : LuoLu\n@Email : argluolu@gmail.com\n@File :batch_img_aud_txt2video.py\n@IDE :PyCharm\n@Motto:simple is everything\n\"\"\"\nimport math\nimport os\n\nfrom PIL import Image\nfrom gtts import gTTS\nimport glob\nimport cv2\nimport moviepy.editor as mpe\nimport numpy as np\nimport time\nimport operator\nfrom itertools import repeat\nfrom moviepy.video.VideoClip import TextClip, ImageClip\nfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip\nfrom moviepy.video.compositing.concatenate import concatenate_videoclips\nfrom moviepy.video.io.ImageSequenceClip import ImageSequenceClip\nfrom moviepy.video.tools.subtitles import SubtitlesClip\nfrom natsort import natsorted\n\n\ndef pad_images_to_same_size(img2pad):\n \"\"\"\n :param images: sequence of images\n :return: list of images padded so that all images have same width and height (max width and height are used)\n \"\"\"\n # for img in images:\n h, w = img2pad.shape[:2]\n desired_size = max(h, w)\n\n delta_w = desired_size - w\n delta_h = desired_size - h\n top, bottom = (int)(delta_h / 2), (int)(delta_h - (delta_h / 2))\n left, right = (int)(delta_w / 2), (int)(delta_w - (delta_w / 2))\n\n color = [0, 0, 0]\n img_padded = cv2.copyMakeBorder(img2pad, top, bottom, left, right, cv2.BORDER_CONSTANT,\n value=color)\n return img_padded\n\n\ndef img_size_odd2even(image):\n # pad odd 2 even\n # new image H, W\n height, width, layers = image.shape\n # print(\"crop dst size: \", dst.shape[:2])\n if (height % 2) == 0:\n new_height = height\n else:\n new_height = math.ceil(height / 2) * 2\n if (width % 2) == 0:\n new_width = width\n else:\n new_width = math.ceil(width / 2) * 2\n # print(new_width, new_height)\n top, bottom = new_height, 0\n left, right = new_width, 0\n color = [0, 0, 0]\n newsize = (new_width, new_height)\n return newsize\n\n\ndef video_to_frames(path_video):\n # Start capturing the feed\n cap = cv2.VideoCapture(path_video, 0)\n # Find the number of frames\n video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1\n print(\"Number of frames: \", video_length)\n\n return video_length\n\n\ndef resize_with_pad(im, target_width, target_height):\n '''\n Resize PIL image keeping ratio and using white background.\n '''\n target_ratio = target_height / target_width\n im_ratio = im.height / im.width\n if target_ratio > im_ratio:\n # It must be fixed by width\n resize_width = target_width\n resize_height = round(resize_width * im_ratio)\n else:\n # Fixed by height\n resize_height = target_height\n resize_width = round(resize_height / im_ratio)\n\n image_resize = im.resize((resize_width, resize_height), Image.ADAPTIVE)\n background = Image.new('RGBA', (target_width, target_height), (255, 255, 255, 255))\n offset = (round((target_width - resize_width) / 2), round((target_height - resize_height) / 2))\n background.paste(image_resize, offset)\n return background.convert(\"RGB\")\n\n\ndirectory = \"C:\\\\Users\\\\Administrator\\\\Desktop\\\\atest\"\npathVideoOut = \"D:\\\\video_sp_amazon\"\nmp3_root_dir = \"/home/luolu/Desktop/mp3Amazon/\"\nbg_music_path = \"D:\\\\pycharmProjects\\\\video-processing\\\\util\\\\bensound-memories.mp3\"\ncounter = 0\nnull_counter = 0\nnull_video_counter = 0\nsize = (1920, 1080)\nblank_image = np.ones((1920, 1080, 3), np.uint8)\n# for filename in os.listdir(directory):\nfor filename in glob.glob(directory + \"\\\\*.txt\"):\n if filename.endswith('.txt'):\n # print(filename)\n asin = filename.split('.txt')[0].split(\"\\\\\")[-1]\n with open(filename, 'r', encoding='UTF-8') as file:\n txt_data = file.read().replace('\\n', '')\n\n # Language in which you want to convert\n language = 'en-US'\n # Passing the text and language to the engine,\n # here we have marked slow=False. Which tells\n # the module that the converted audio should\n # have a high speed\n myobj = gTTS(text=txt_data, lang=language, slow=False, tld=\"cn\")\n\n # Saving the converted audio in a mp3 file named\n # welcome\n print(\"type audio\", type(myobj))\n myobj.save('welcome.mp3')\n time.sleep(1)\n # img_folder_path = directory + \"/\" + filename.split('.txt')[0]\n img_folder_path = filename.split('.txt')[0]\n print(img_folder_path)\n frame_array = []\n frame_array.extend(repeat(blank_image, 50))\n\n list_size = []\n img_count = len(glob.glob(img_folder_path + \"\\\\*.jpg\"))\n img_0_path = img_folder_path + \"\\\\0.jpg\"\n np_img0 = cv2.imread(img_0_path)\n if img_count == 0:\n null_counter += 1\n continue\n else:\n for img_file in glob.glob(img_folder_path + \"\\\\*.jpg\"):\n img = cv2.imread(img_file)\n\n target_width = 1920\n target_height = 1080\n #\n im = Image.open(img_file)\n result = resize_with_pad(im, target_width, target_height)\n pix = np.array(result)\n pix = pix[:, :, ::-1]\n # new_im = resize_pad_cv2(img, target_width)\n frame_array.extend(repeat(pix, 150))\n\n path_mp3_google = mp3_root_dir + asin + '.mp3'\n # audio_background = None\n # if os.path.exists(path_mp3_google):\n # audio_background = mpe.AudioFileClip(path_mp3_google)\n # print(\"duration audio_background\", audio_background.duration)\n # else:\n # audio_background = mpe.AudioFileClip('welcome.mp3')\n audio_background = mpe.AudioFileClip('welcome.mp3')\n bg_music = mpe.AudioFileClip(bg_music_path)\n\n if img_count < 4:\n for i in range(len(frame_array)):\n frame_array.append(frame_array[i])\n for i in range(len(frame_array)):\n frame_array.append(frame_array[i])\n elif 4 <= img_count <= 8:\n for i in range(len(frame_array)):\n frame_array.append(frame_array[i])\n else:\n frame_array = frame_array\n frame_array.append(np_img0 * 60)\n FPS = 30\n # out = cv2.VideoWriter(filename=pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '_v.mp4',\n # fourcc=cv2.VideoWriter_fourcc(*'mp4v'),\n # fps=FPS,\n # isColor=True,\n # frameSize=size)\n # for i in range(len(frame_array)):\n # # writing to a image array\n # out.write(frame_array[i])\n # out.release()\n # file_list = glob.glob(img_folder_path + \"\\\\*.jpg\") # Get all the pngs in the current directory\n # file_list_sorted = natsorted(file_list, reverse=False) # Sort the images\n\n clips = [ImageClip(m).set_duration(1)\n for m in frame_array]\n # clip = ImageSequenceClip(clips, fps=30)\n # clip = ImageSequenceClip(np.array(frame_array), fps=30)\n concat_clip = concatenate_videoclips(clips, method=\"chain\")\n # concat_clip.resize(width=1920, height=1080)\n concat_clip.write_videofile(\n pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '_v.mp4',\n bitrate='50000k',\n fps=FPS, audio_bitrate='3000k',\n threads=4)\n time.sleep(2)\n\n print(pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '.mp4')\n my_clip = mpe.VideoFileClip(\n filename=pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '_v.mp4')\n # audio_background = mpe.AudioFileClip('welcome.mp3')\n # print(\"type audio_background\", type(audio_background))\n final_audio = mpe.CompositeAudioClip([audio_background, bg_music])\n # final_clip = CompositeVideoClip([my_clip, subtitles.set_position(('center', 'bottom'))])\n final_clip = my_clip.set_audio(final_audio)\n path_f_video = pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '.mp4'\n final_clip.write_videofile(path_f_video, bitrate='50000k',\n fps=FPS, audio_bitrate='3000k',\n threads=4)\n time.sleep(1)\n v_len = video_to_frames(path_f_video)\n if v_len == 0:\n null_video_counter += 1\n # delete file forever\n os.system(\"del \" + path_f_video)\n os.system(\"del \" + pathVideoOut + \"\\\\\" + filename.split('.txt')[0].split(\"\\\\\")[-1] + '_v.mp4')\n counter += 1\n print(\"process: \", counter)\n\n else:\n # print(filename)\n pass\n\nprint(\"counter: \", counter)\nprint(\"null file counter: \", null_counter)\nprint(\"null_video_counter: \", null_video_counter)\n","sub_path":"util/movipy_aud_txt2video.py","file_name":"movipy_aud_txt2video.py","file_ext":"py","file_size_in_byte":9102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"453609872","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Gao Xiang\nimport shelve\nimport os\nimport threading\nfrom core.host import Hosts\nfrom conf import settings\n\n\n\nclass Manager(threading.Thread):\n\n def __init__(self):\n super(Manager, self).__init__()\n self.hostfile = os.path.join(settings.base_dir,'data','hosts.conf')\n self.data = shelve.open(self.hostfile)\n\n def list_host(self):\n #data = shelve.open(self.hostfile)\n\n for h in self.data:\n print(h)\n\n def help(self):\n info = '''\n --connect to remote host,input 'exit' to logout\n -- download file from remote host,input 'exit' to exit\n -- upload file to remote host,input 'exit' to exit\n '''\n print(info)\n\n def conn_host(self):\n\n while True:\n self.list_host()\n cmd = input(\">>:\")\n if cmd == 'exit': break\n cmd_list = cmd.split()\n hostname = cmd_list[1]\n\n if hostname not in self.data:continue\n\n host_obj = self.data[hostname]\n connector = Hosts(host_obj)\n if hasattr(connector,cmd_list[0]):\n func = getattr(connector,cmd_list[0])\n func(cmd)\n else:\n self.help()\n\n def put_file(self):\n while True:\n self.list_host()\n cmd = input('>>:')\n if cmd.startswith('put') and cmd != 'exit':\n cmd_list = cmd.split()\n hostname = cmd_list[2].split(':')[0]\n host_obj = self.data[hostname]\n connector =Hosts(host_obj)\n if hasattr(connector,cmd_list[0]):\n func = getattr(connector,cmd_list[0])\n func(cmd)\n else:\n self.help()\n else:\n #print(\"Invalid Option\")\n break\n\n def get_file(self):\n while True:\n self.list_host()\n cmd = input('>>:')\n if cmd.startswith('get') and cmd != 'exit':\n cmd_list = cmd.split()\n hostname = cmd_list[1].split(':')[0]\n host_obj = self.data[hostname]\n connector = Hosts(host_obj)\n if hasattr(connector,cmd_list[0]):\n func = getattr(connector,cmd_list[0])\n func(cmd)\n else:\n break\n\n\n\n\n def add(self):\n hostname = input('hostname:')\n port = input('port:')\n username = input('username:')\n passwd = input('passwd:')\n tag = input('tag:')\n\n hostinfo = {\n 'hostname':hostname,\n 'port':port,\n 'username':username,\n 'passwd':passwd,\n 'tag':tag\n }\n\n data = shelve.open(self.hostfile)\n data[hostname] = hostinfo\n data.close()\n exit('主机添加成功')\n\n\n\n def active(self):\n while True:\n msg = '''\n 1:连接主机\n 2:添加主机\n 3:上传文件\n 4:下载文件\n 5:批量命令\n '''\n print(msg)\n chioce = input(\">>:\")\n if len(chioce) == 0:continue\n if chioce == '1':\n self.conn_host()\n if chioce == '2':\n self.add()\n if chioce == '3':\n self.put_file()\n if chioce == '4':\n self.get_file()\n if chioce == '5':\n self.batch()\n\n def batch(self):\n host_list = []\n host_tag = {}\n for host in self.data:\n host_obj = self.data[host]\n tag = host_obj['tag']\n host_list.append(host_obj)\n host_tag[tag] = tag\n while True:\n for t in host_tag:\n print(t)\n\n choice = input('选择分组:')\n if len(choice) ==0:continue\n if choice == 'exit':break\n if choice in host_tag:\n while True:\n cmd = input(\"批量命令>>:\")\n if len(cmd) ==0:continue\n if cmd == 'exit':break\n for i in host_list:\n if i['tag'] == choice:\n # connector = hosts(i)\n # connector.batch_ssh(cmd)\n connector = Hosts(i)\n connector.run(cmd)\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n test = Manager()\n test.active()","sub_path":"core/conn.py","file_name":"conn.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"444405449","text":"import markdown\nfrom jinja2 import Template\n\nfrom crc import app\nfrom crc.api.common import ApiError\nfrom crc.scripts.script import Script\nfrom crc.services.ldap_service import LdapService\nfrom crc.services.mails import send_mail\n\n\nclass Email(Script):\n \"\"\"This Script allows to be introduced as part of a workflow and called from there, specifying\n recipients and content \"\"\"\n\n def get_description(self):\n return \"\"\"\nCreates an email, using the provided arguments (a list of UIDs)\"\nEach argument will be used to look up personal information needed for\nthe email creation.\n\nExample:\nEmail Subject ApprvlApprvr1 PIComputingID\n\"\"\"\n\n def do_task_validate_only(self, task, *args, **kwargs):\n self.get_subject(task, args)\n self.get_users_info(task, args)\n self.get_content(task)\n\n def do_task(self, task, *args, **kwargs):\n args = [arg for arg in args if type(arg) == str]\n subject = self.get_subject(task, args)\n recipients = self.get_users_info(task, args)\n content, content_html = self.get_content(task)\n if recipients:\n send_mail(\n subject=subject,\n sender=app.config['DEFAULT_SENDER'],\n recipients=recipients,\n content=content,\n content_html=content_html\n )\n\n def get_users_info(self, task, args):\n if len(args) < 1:\n raise ApiError(code=\"missing_argument\",\n message=\"Email script requires at least one argument. The \"\n \"name of the variable in the task data that contains user\"\n \"id to process. Multiple arguments are accepted.\")\n emails = []\n for arg in args:\n try:\n uid = task.workflow.script_engine.evaluate_expression(task, arg)\n except Exception as e:\n app.logger.error(f'Workflow engines could not parse {arg}', exc_info=True)\n continue\n user_info = LdapService.user_info(uid)\n email = user_info.email_address\n emails.append(user_info.email_address)\n if not isinstance(email, str):\n raise ApiError(code=\"invalid_argument\",\n message=\"The Email script requires at least 1 UID argument. The \"\n \"name of the variable in the task data that contains subject and\"\n \" user ids to process. This must point to an array or a string, but \"\n \"it currently points to a %s \" % emails.__class__.__name__)\n\n return emails\n\n def get_subject(self, task, args):\n if len(args) < 1:\n raise ApiError(code=\"missing_argument\",\n message=\"Email script requires at least one subject argument. The \"\n \"name of the variable in the task data that contains subject\"\n \" to process. Multiple arguments are accepted.\")\n subject = args[0]\n if not isinstance(subject, str):\n raise ApiError(code=\"invalid_argument\",\n message=\"The Email script requires 1 argument. The \"\n \"the name of the variable in the task data that contains user\"\n \"ids to process. This must point to an array or a string, but \"\n \"it currently points to a %s \" % subject.__class__.__name__)\n\n return subject\n\n def get_content(self, task):\n content = task.task_spec.documentation\n template = Template(content)\n rendered = template.render(task.data)\n rendered_markdown = markdown.markdown(rendered).replace('\\n', '
')\n return rendered, rendered_markdown\n","sub_path":"crc/scripts/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"480944145","text":"import subprocess\nimport plistlib\nimport sys\nimport os\nimport time\n\nclass Disk:\n\n def __init__(self):\n self.diskutil = self.get_diskutil()\n self.disks = self.get_disks()\n self.apfs = self.get_apfs()\n\n def _update_disks(self):\n self.disks = self.get_disks()\n self.apfs = self.get_apfs()\n\n def _get_output(self, comm):\n try:\n p = subprocess.Popen(comm, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n c = p.communicate()\n # p = subprocess.run(comm, shell=True, check=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n if not p.returncode == 0:\n return c[1].decode(\"utf-8\")\n return c[0].decode(\"utf-8\")\n except:\n return c[1].decode(\"utf-8\")\n\n def get_diskutil(self):\n # Returns the path to the diskutil binary\n return self._get_output([\"which\", \"diskutil\"]).split(\"\\n\")[0].split(\"\\r\")[0]\n\n def get_disks(self):\n # Returns a dictionary object of connected disks\n disk_list = self._get_output([self.diskutil, \"list\", \"-plist\"])\n return plistlib.loads(disk_list.encode(\"utf-8\"))\n\n def get_apfs(self):\n # Returns a dictionary object of apfs disks\n disk_list = self._get_output([self.diskutil, \"apfs\", \"list\", \"-plist\"])\n return plistlib.loads(disk_list.encode(\"utf-8\"))\n\n def is_apfs(self, disk):\n # Takes a disk identifier, and returns whether or not it's apfs\n for d in self.disks[\"AllDisksAndPartitions\"]:\n if not \"APFSVolumes\" in d:\n continue\n if \"DeviceIdentifier\" in d and d[\"DeviceIdentifier\"].lower() == disk.lower():\n return True\n for a in d[\"APFSVolumes\"]:\n if a[\"DeviceIdentifier\"].lower() == disk.lower():\n return True\n return False\n\n def get_identifier(self, disk):\n # Should be able to take a mount point, disk name, or disk identifier,\n # and return the disk's parent\n # Iterate!!\n for d in self.disks[\"AllDisksAndPartitions\"]:\n if \"DeviceIdentifier\" in d and d[\"DeviceIdentifier\"].lower() == disk.lower():\n return d[\"DeviceIdentifier\"]\n if \"APFSVolumes\" in d:\n for a in d[\"APFSVolumes\"]:\n if \"DeviceIdentifier\" in a and a[\"DeviceIdentifier\"].lower() == disk.lower():\n return a[\"DeviceIdentifier\"]\n if \"VolumeName\" in a and a[\"VolumeName\"].lower() == disk.lower():\n return a[\"DeviceIdentifier\"]\n if \"MountPoint\" in a and a[\"MountPoint\"].lower() == disk.lower():\n return a[\"DeviceIdentifier\"]\n if \"Partitions\" in d:\n for p in d[\"Partitions\"]:\n if \"DeviceIdentifier\" in p and p[\"DeviceIdentifier\"].lower() == disk.lower():\n return p[\"DeviceIdentifier\"]\n if \"VolumeName\" in p and p[\"VolumeName\"].lower() == disk.lower():\n return p[\"DeviceIdentifier\"]\n if \"MountPoint\" in p and p[\"MountPoint\"].lower() == disk.lower():\n return p[\"DeviceIdentifier\"]\n # At this point, we didn't find it\n return None\n\n def get_physical_store(self, disk):\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n if self.is_apfs(disk_id):\n # We have apfs - let's get the Physical Store\n for a in self.apfs[\"Containers\"]:\n # Check if it's the whole container\n if \"ContainerReference\" in a and a[\"ContainerReference\"].lower() == disk_id.lower():\n return a[\"DesignatedPhysicalStore\"]\n # Check through each volume and return the parent's physical store\n if \"Volumes\" in a:\n for v in a[\"Volumes\"]:\n if \"DeviceIdentifier\" in v and v[\"DeviceIdentifier\"].lower() == disk_id.lower():\n return a[\"DesignatedPhysicalStore\"]\n return None\n\n\n def get_parent(self, disk):\n # Disk can be a mount point, disk name, or disk identifier\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n if self.is_apfs(disk_id):\n # We have apfs - let's get the container ref\n for a in self.apfs[\"Containers\"]:\n # Check if it's the whole container\n if \"ContainerReference\" in a and a[\"ContainerReference\"].lower() == disk_id.lower():\n return a[\"ContainerReference\"]\n # Check through each volume and return the parent's container ref\n if \"Volumes\" in a:\n for v in a[\"Volumes\"]:\n if \"DeviceIdentifier\" in v and v[\"DeviceIdentifier\"].lower() == disk_id.lower():\n return a[\"ContainerReference\"]\n else:\n # Not apfs - go through all volumes and whole disks\n for d in self.disks[\"AllDisksAndPartitions\"]:\n if \"DeviceIdentifier\" in d and d[\"DeviceIdentifier\"].lower() == disk_id.lower():\n return d[\"DeviceIdentifier\"]\n if \"Partitions\" in d:\n for p in d[\"Partitions\"]:\n if \"DeviceIdentifier\" in p and p[\"DeviceIdentifier\"].lower() == disk_id.lower():\n return d[\"DeviceIdentifier\"]\n # Didn't find anything\n return None\n\n def get_efi(self, disk):\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n if self.is_apfs(disk_id):\n disk_id = self.get_parent(self.get_physical_store(disk_id))\n else:\n disk_id = self.get_parent(disk_id)\n if not disk_id:\n return None\n # At this point - we should have the parent\n for d in self.disks[\"AllDisksAndPartitions\"]:\n if d[\"DeviceIdentifier\"].lower() == disk_id.lower():\n # Found our disk\n if not \"Partitions\" in d:\n return None\n for p in d[\"Partitions\"]:\n if \"Content\" in p and p[\"Content\"].lower() == \"efi\":\n return p[\"DeviceIdentifier\"]\n return None\n\n def mount_partition(self, disk):\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n return self._get_output([self.diskutil, \"mount\", disk_id])\n\n def unmount_partition(self, disk):\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n return self._get_output([self.diskutil, \"unmount\", disk_id])\n\n def get_volumes(self):\n # Returns a list object with all volumes from disks\n return self.disks[\"VolumesFromDisks\"]\n\n def get_volume_name(self, disk):\n # Returns the volume name of the passed ident if one exists\n disk_id = self.get_identifier(disk)\n if not disk_id:\n return None\n for d in self.disks[\"AllDisksAndPartitions\"]:\n if \"DeviceIdentifier\" in d and d[\"DeviceIdentifier\"].lower() == disk_id.lower():\n # Whole disk - no mounts\n return None\n if \"APFSVolumes\" in d:\n for a in d[\"APFSVolumes\"]:\n if \"DeviceIdentifier\" in a and a[\"DeviceIdentifier\"].lower() == disk_id.lower():\n if \"VolumeName\" in a:\n return a[\"VolumeName\"]\n else:\n return None\n if \"Partitions\" in d:\n for p in d[\"Partitions\"]:\n if \"DeviceIdentifier\" in p and p[\"DeviceIdentifier\"].lower() == disk_id.lower():\n if \"VolumeName\" in p:\n return p[\"VolumeName\"]\n else:\n return None\n\n def get_mounted_volumes(self):\n # Returns a list of mounted volumes\n vol_list = self._get_output([\"ls\", \"-1\", \"/Volumes\"]).split(\"\\n\")\n if vol_list[len(vol_list)-1] == \"\":\n vol_list.pop(len(vol_list)-1)\n return vol_list\n\n# Helper methods\ndef grab(prompt):\n if sys.version_info >= (3, 0):\n return input(prompt)\n else:\n return str(raw_input(prompt))\n\n# Header drawing method\ndef head(text = \"CorpTool\", width = 50):\n os.system(\"clear\")\n print(\" {}\".format(\"#\"*width))\n mid_len = int(round(width/2-len(text)/2)-2)\n middle = \" #{}{}{}#\".format(\" \"*mid_len, text, \" \"*((width - mid_len - len(text))-2))\n print(middle)\n print(\"#\"*width)\n\n\n# Main menu\ndef main():\n # Refresh volumes\n d = Disk()\n head(\"MountEFI\")\n print(\" \")\n # List the volumes\n num = 0\n vols = d.get_mounted_volumes()\n for v in vols:\n num += 1\n print(\"{}. {}\".format(num, v))\n print(\" \")\n print(\"Q. Quit\\n\")\n default = d.get_volume_name(\"/\")\n if not default:\n default = \"/\"\n select = grab(\"Please select a volume (default is {}): \".format(default))\n\n if select.lower() == \"q\":\n custom_quit()\n\n head(\"MountEFI\")\n print(\" \")\n\n if select == \"\":\n select = \"/\"\n try:\n select = int(select)\n except:\n pass\n if type(select) is int:\n # Check if we're out of bounds\n if select < 0 or select >= len(vols):\n # OOB\n return\n efi = d.get_efi(vols[select-1])\n if not efi:\n print(\"{} has no EFI partition...\".format(vols[select-1]))\n else:\n print(d.mount_partition(efi))\n time.sleep(3)\n custom_quit()\n else:\n # Maybe it's a volume name/mount point/ident/etc\n disk_ident = d.get_identifier(select)\n if not disk_ident:\n return\n efi = d.get_efi(disk_ident)\n if not efi:\n print(\"{} has no EFI partition...\".format(d.get_parent(disk_ident)))\n else:\n print(d.mount_partition(d.get_efi(disk_ident)))\n time.sleep(3)\n custom_quit()\n\ndef custom_quit():\n head(\"MountEFI\")\n print(\"by CorpNewt\\n\")\n print(\"Thanks for testing it out, for bugs/comments/complaints\")\n print(\"send me a message on Reddit, or check out my GitHub:\\n\")\n print(\"www.reddit.com/u/corpnewt\")\n print(\"www.github.com/corpnewt\\n\")\n print(\"Have a nice day/night!\\n\\n\")\n exit(0)\n\nif len(sys.argv) > 1:\n # We started with args - assume the arg passed is the disk to mount\n d = Disk()\n d.mount_partition(d.get_efi(sys.argv[1]))\n exit(0)\n\n# Start the loop and keep it going\nwhile True:\n main()\n","sub_path":"MountEFI/MountEFI.py","file_name":"MountEFI.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"236422951","text":"# Problem File for Blocks World\nfrom BWD import *\nfrom random import *\nfrom Planner.ExpectationsGenerator import *\nstate = None\npolicy = None\n\ndef run():\n global state, policy\n agent = 'Agent1'\n state = treehop.State('state')\n state.weights = {}\n state.acquired = {agent: (0, 0)}\n state.under = {}\n state.on = {}\n state.top = {}\n state.top_acquired = {}\n state.collected = {agent: 0}\n top_list = Queue()\n goal_set = {} # goals for goal regression\n for i in range(0, 3):\n top_list.put(None)\n n = 500\n collection_weight = 500\n max_weight = 50\n variance = 2\n for i in range(0, n):\n under = top_list.get()\n state.under[i] = None\n state.under[under] = i\n state.on[i] = under\n top_list.put(i)\n temp = round((random() * (max_weight - (2 * variance))) + variance, 2)\n state.weights[i] = (temp - variance, temp + variance)\n state.top[i] = False\n state.top_acquired[i] = False\n while not top_list.empty():\n i = top_list.get()\n state.top[i] = True\n goals = [('achieve_goal', agent, collection_weight)]\n treehop.declare_goals(goals)\n policy = treehop.pyhop_t(state, goals, True)\n treehop.print_policy(policy, state)\n gen_expectations(policy, state, goal_set)\n\nrun()","sub_path":"BWP.py","file_name":"BWP.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"101729306","text":"import pickle\nimport ir\n# import textCleaning\nfrom gensim import models\nfrom gensim import similarities\nimport streamlit as st\nimport tf_IDF\nfrom gensim import corpora\nfrom gensim.parsing import strip_tags, strip_numeric, \\\n strip_multiple_whitespaces, stem_text, strip_punctuation, \\\n remove_stopwords, preprocess_string\nimport QuesAns\n\n# Project Title\nheader= st.beta_container()\nwith header:\n st.title(\"Welcome to Automated Q&A bot\")\n\n# To fetch the query that is the question \nquestion=st.text_input('Ask a question here:') \nif question:\n with open('clean_text.pkl', 'rb') as p:\n new_docs = pickle.load(p)\n text_docs=[] \n for ele in new_docs:\n if len(ele) > 50:\n text_docs.append(ele)\n else:\n pass\n # Loading all pickle files\n #dictionary, pdoc = ir.create_dictionary(raw_corpus)\n with open('dictionary.pkl', 'rb') as p:\n dictionary = pickle.load(p)\n with open('index.pkl', 'rb') as p:\n index = pickle.load(p)\n with open('tfidf.pkl', 'rb') as p:\n tfidf = pickle.load(p)\n \n answer=[]\n for d in tf_IDF.get_closest_n(question,5, dictionary, index, tfidf, text_docs):\n answer.append(d)\n Answer=st.beta_container()\n with Answer:\n st.title(\"The answer\")\n st.write(answer)\n \n ans=QuesAns.QuesAnswer(question,answer)\n\n # To fetch the predicted result of the query\n Answer=st.beta_container()\n with Answer:\n st.title(\"The answer\")\n st.write(ans)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519334038","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing, metrics, svm\nfrom sklearn.metrics import precision_recall_fscore_support, accuracy_score\nfrom sklearn.preprocessing import LabelEncoder, FunctionTransformer\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\nwarnings.filterwarnings(\"error\", message=\".*check_inverse*.\", category=UserWarning, append=False)\n\n\ntraining=pd.read_csv(\"training.csv\",sep=';')\nvalidation=pd.read_csv(\"validation.csv\",sep=';')\ndef clean(data):\n data=data.drop_duplicates()\n data=data.drop('variable18',axis=1) # too many null values\n encoder = LabelEncoder()\n cat=['variable1','variable4','variable5','variable6','variable7','variable9','variable10','variable12',\n 'variable13','classLabel']\n num=['variable2','variable3','variable8','variable11','variable14','variable15','variable17','variable19']\n for i in cat:\n data[i]=data[i].apply(lambda x:str(x))\n encoded = data[cat].apply(encoder.fit_transform)\n data = data[num].join(encoded)\n data.variable2 = data.variable2.apply(lambda x: str(x))\n data.variable2=data.variable2.apply(lambda x: float(x.replace(',','.')))\n data.variable3=data.variable3.apply(lambda x: float(x.replace(',','.')))\n data.variable8=data.variable8.apply(lambda x: float(x.replace(',','.')))\n data=data.fillna(data.mode())\n data=data.dropna()\n return data,encoder\n\n\n\ndef preprocess(data):\n num=['variable2','variable3','variable8','variable11','variable14','variable15','variable17','variable19']\n label=training.classLabel\n train=training.drop('classLabel',axis=1)\n train[num] = preprocessing.scale(train[num])\n transformer = FunctionTransformer(np.log1p, validate=True)\n transformer.transform(train[num])\n train[num] = preprocessing.normalize(train[num], norm='l2')\n return train,label\n\n\ntraining,encoder=clean(training)\nvalidation,_=clean(validation)\n\nTrainX,TrainY=preprocess(training)\nTestX,TestY=preprocess(validation)\n\n\ndef trainSVM(VTrainX,VTrainY, VTestX, VTestY):\n clf = svm.SVC(gamma='auto')\n clf.fit(VTrainX, VTrainY)\n valid_pred = clf.predict(VTestX)\n valid_score = metrics.roc_auc_score(VTestY, valid_pred)\n valid_score3 = precision_recall_fscore_support(VTestY, valid_pred, average='weighted')\n print(f\"Validation precision,recall,f score: \")\n print(valid_score3)\n print(f\"Validation AUC score: {valid_score:.4f}\")\n accuracy = accuracy_score(VTestY, valid_pred)\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n return clf\n\n\nsvmm = trainSVM(TrainX,TrainY, TestX, TestY)\n#Validation precision,recall,f score: (0.987647905340582, 0.9872881355932204, 0.9873068679420286)\n#Validation AUC score: 0.9887\n#Accuracy: 98.73%\n\n\ndef prediction(model, encoder, input):\n input[1] = float(str(input[1]).replace(\",\",\".\"))\n input[2] = float(str(input[2]).replace(\",\", \".\"))\n input[7] = float(str(input[7]).replace(\",\", \".\"))\n input[10] = float(input[10])\n input[13] = float(input[13])\n input[14] = float(input[14])\n input[15] = float(input[15])\n input[17] = float(input[17])\n cat=[0,3,4,5,6,8,9,11,12]\n for i in cat:\n input[i] = encoder.fit_transform([input[i]])\n del input[16]\n prediction = model.predict([input])\n p=''\n if prediction == 0:\n p=\"no\"\n else:\n p='yes'\n print('The predicted lable is: ' + p)\n return prediction\n\ninput = ['b', '32,33', '0,00075', 'u', 'g', 'e', 'bb', '1,585', 't', 'f', '0', 't', 's', '420', '0', '4.2e+06', 'NaN', '1']\nprediction=prediction(svmm, encoder, input)\n","sub_path":"Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"569379225","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2017 Dan Halbert\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\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 FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\n\"\"\"\n:mod:`adafruit_max7219.bcddigits.BCDDigits`\n====================================================\n\"\"\"\nfrom adafruit_max7219 import max7219\n\n_DECODEMODE = const(9)\n_SCANLIMIT = const(11)\n_SHUTDOWN = const(12)\n_DISPLAYTEST = const(15)\n\nclass BCDDigits(max7219.MAX7219):\n \"\"\"\n Basic support for display on a 7-Segment BCD display controlled\n by a Max7219 chip using SPI.\n \"\"\"\n def __init__(self, spi, cs, nDigits=1):\n \"\"\"\n :param object spi: an spi busio or spi bitbangio object\n :param ~digitalio.DigitalInOut cs: digital in/out to use as chip select signal\n :param int nDigits: number of led 7-segment digits; default 1; max 8\n \"\"\"\n self.nD = nDigits\n super().__init__(self.nD, 8 ,spi ,cs)\n\n def init_display(self):\n \n for cmd, data in (\n (_SHUTDOWN, 0),\n (_DISPLAYTEST, 0),\n (_SCANLIMIT, 7),\n (_DECODEMODE, (2**self.nD)-1),\n (_SHUTDOWN, 1),\n ):\n self.write_cmd(cmd, data) \n\n self.clear_all()\n self.show()\n\n def set_digit(self, d, v):\n \"\"\"\n set one digit in the display\n :param int d: the digit position; zero-based \n :param int v: integer ranging from 0->15\n \"\"\"\n d = self.nD - d - 1\n for i in range(4):\n #print('digit {} pixel {} value {}'.format(d,i+4,v & 0x01))\n self.pixel(d,i,v & 0x01)\n v >>= 1\n \n def set_digits(self, s, ds):\n \"\"\"\n set the display from a list\n :param int s: digit to start display zero-based\n :param list ds: list of integer values ranging from 0->15\n \"\"\"\n for d in ds:\n #print('set digit {} start {}'.format(d,start))\n self.set_digit(s,d)\n s += 1\n\n def show_dot(self,d, col=None):\n \"\"\"\n set the decimal point for a digit\n :param int d: the digit to set the decimal point zero-based \n :param int col: value > zero lights the decimal point, else unlights the point\n \"\"\"\n if d < self.nD and d >= 0:\n #print('set dot {} = {}'.format((self.nD - d -1),col))\n self.pixel(self.nD-d-1, 7,col)\n\n def clear_all(self):\n \"\"\"\n clear all digits and decimal points\n \"\"\"\n self.fill(1)\n for i in range(self.nD):\n self.show_dot(i)\n\n def show_str(self,s,str): \n \"\"\"\n displays a numeric str in the display. shows digits 0-9, -, and .\n :param int s: start position to show the numeric string\n :param string str: the numeric string\n \"\"\"\n ci = s\n for i in range (len(str)):\n c = str[i]\n # print('c {}'.format(c))\n v = 0x0f # assume blank \n if c >= '0' and c<='9':\n v = int(c)\n elif c == '-':\n v = 10 # minus sign\n elif c == '.':\n self.show_dot(ci-1,1)\n continue\n self.set_digit(ci,v)\n ci += 1\n \n def show_help(self, s):\n \"\"\"\n display the word HELP in the display\n :param int s: start position to show HELP\n \"\"\"\n digits = [12,11,13,14]\n self.set_digits(s,digits)\n\n","sub_path":"adafruit_max7219/bcddigits.py","file_name":"bcddigits.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264444607","text":"import cv2\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom pyimagesearch import four_point_transform\n# load the image and grab the source coordinates (i.e. the list of\n# of (x, y) points)\n# NOTE: using the 'eval' function is bad form, but for this example\n# let's just roll with it -- in future posts \n# automatically determine the coordinates without pre-supplying them\nimage = cv2.imread('threepots.png') \npts1 = np.array(eval('[(80, 296), (174, 269), (86, 323), (399, 329)]'), dtype = \"float32\")\npts2 = np.array(eval('[(294, 272), (399, 270), (306, 334), (339, 329)]'), dtype = \"float32\")\npts3 = np.array(eval('[(306, 334), (399, 329), (494, 273), (496, 331)]'), dtype = \"float32\")\ndef warpedfoo(image, pts):\n\t# apply the four point tranform to obtain a \"birds eye view\" of\n\t# the image\n\twarped = four_point_transform(image, pts)\n\treturn warped\ndef changecolorandframe(img1):\n\tBLUE = [255,0,0]\n\tconstant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)\n\thsv = cv2.cvtColor(constant,cv2.COLOR_BGR2RGB)\n\t#plt.imshow(constant,'gray'),plt.title('CONSTANT')#1\n\t#plt.show()\n\treturn hsv\ndef colordetection(color_changed,boundaries):\n\t# define the list of boundaries #boundaries = [([0, 0, 240], [10, 10, 255]),([100, 80, 60], [145, 135, 130])]\n\t# loop over the boundaries\n\tfor (lower, upper) in boundaries:\n\t\t# create NumPy arrays from the boundaries\n\t\tlower = np.array(lower, dtype = \"uint8\")\n\t\tupper = np.array(upper, dtype = \"uint8\")\n\t\t# find the colors within the specified boundaries and apply\n\t\t# the mask\n\t\tmask = cv2.inRange(color_changed, lower, upper)\n\t\tcolordet_img = cv2.bitwise_and(color_changed, color_changed, mask = mask)\n\t\t# show the images\n\t\t#cv2.imshow(\"images\", np.hstack([color_changed, colordet_img]))\n\t\t#cv2.waitKey(0)\n\treturn colordet_img\ndef determprocentege(path):\n\tim = Image.open(path)\n\tblack = 0\n\tother_color = 0\n\n\tfor pixel in im.getdata():\n\t\tif pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so\n\t\t\tblack += 1\n\t\telse:\n\t\t\tother_color += 1\n\t#print('black=' + str(black)+', red='+str(other_color))\n\tcovered_proc = 100*(float(other_color)/float((other_color+black)))\n\treturn covered_proc\nplt.imshow(image,'gray'),plt.title('CONSTANT')#1\nplt.show()\nimg1 = warpedfoo(image, pts1)\nimg2 = warpedfoo(image, pts2)\nimg3 = warpedfoo(image, pts3)\ncolor_changed1 = changecolorandframe(img1)\ncolor_changed2 = changecolorandframe(img2)\ncolor_changed3 = changecolorandframe(img3)\ncolordet_red1 = colordetection(color_changed1,[([0, 0, 240], [10, 10, 255])])\ncolordet_red2 = colordetection(color_changed2,[([0, 0, 240], [10, 10, 255])])\ncolordet_red3 = colordetection(color_changed3,[([0, 0, 240], [10, 10, 255])])\ncolordet_flower1 = colordetection(color_changed1,[([100, 80, 60], [145, 135, 130])])\ncolordet_flower2 = colordetection(color_changed2,[([100, 80, 60], [145, 135, 130])])\ncolordet_flower3 = colordetection(color_changed3,[([100, 80, 60], [145, 135, 130])])\ncv2.imwrite('img1.jpg',colordet_flower1)\ncv2.imwrite('img2.jpg',colordet_flower2)\ncv2.imwrite('img3.jpg',colordet_flower3)\npath1 = 'img1.jpg'\npath2 = 'img2.jpg'\npath3 = 'img3.jpg'\nprecentage1 = determprocentege(path1)\nprecentage2 = determprocentege(path2)\nprecentage3 = determprocentege(path3)\nprint(precentage1,precentage2,precentage3)\n#cv2.imshow(\"Flower\", colordet_flower)\ncv2.waitKey(0)","sub_path":"redboarder.py","file_name":"redboarder.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483860592","text":"import requests\nfrom config import readcfg\n\nheader_Gary = {\n 'Appid': \"1f1615ba596299024d73efc6\",\n 'Sign': \"\",\n 'Userid': \"38715a6d7c0608f7.606065919364653057\",\n 'Token': \"5882be9c0054904df30a06b0e79dabdf51e8\",\n 'Lang': \"zh\",\n 'Content-Type': \"multipart/form-data\",\n 'cache-control': \"no-cache\"\n }\nheader_Jenny = readcfg.header_Jenny\nurl = readcfg.url\n\n\ndef app_background_upload():\n url_ = url + \"/app/v1.0/lumi/app/background/upload\"\n file = {\"file\": open(\"C:\\\\AIOT\\\\test.jpg\", \"rb\")}\n print(file)\n upload_data = {\"file\": \"C:\\\\AIOT\\\\test.jpg\"}\n r = requests.post(url_, upload_data, headers=header_Gary, files=file)\n return r\n\n\nif __name__ == '__main__':\n result_main = app_background_upload()\n print(result_main.text)\n","sub_path":"modules/app_additional/app_background/app_background_upload.py","file_name":"app_background_upload.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"248411303","text":"from source import source\n#from DataBase import DataBase\nfrom RW_txt import Read_txt\nclass analyze():\n def __init__(self):\n #self.db=DataBase()\n self.resultlist=[]\n self.scalelist=[]\n self.all_result={\"1.嵌入式软件工程师\":[], \n \"2.JAVA软件工程师\":[], \n \"3.WEB软件工程师\":[] , \n \"4.IOS软件工程师\":[], \n \"5..Net软件工程师\":[], \n \"6.C#软件工程师\":[],\n \"7.PHP软件工程师\":[],\n \"8.Android开发工程师\":[],\n \"9.C++软件工程师\":[]\n }\n self.all_wages={\"1.嵌入式软件工程师\":[], \n \"2.JAVA软件工程师\":[], \n \"3.WEB软件工程师\":[] , \n \"4.IOS软件工程师\":[], \n \"5..Net软件工程师\":[], \n \"6.C#软件工程师\":[],\n \"7.PHP软件工程师\":[],\n \"8.Android开发工程师\":[],\n \"9.C++软件工程师\":[]\n }\n self.all_Ewages={\"1.嵌入式软件工程师\":5000, \n \"2.JAVA软件工程师\":5000, \n \"3.WEB软件工程师\":5000 , \n \"4.IOS软件工程师\":5000, \n \"5..Net软件工程师\":5000, \n \"6.C#软件工程师\":5000,\n \"7.PHP软件工程师\":5000,\n \"8.Android开发工程师\":5000,\n \"9.C++软件工程师\":5000\n }\n self.num=0.000\n def select_all(self, name):\n source.read_txt=Read_txt(source.Edbname[name])\n read_txt=source.read_txt\n rl=[]\n classrl=[]\n classfy=source.Eclassfy[name]\n # self.db.open()\n #result=self.db.select(dbname)\n result=read_txt.readlines()\n if result==\"error\":\n return \"error\"\n for r in result:\n res=r.split(',')\n rl.append(res)\n self.all_result[name]=rl\n k=0\n for c in classfy:\n classrl.append([c[0]])\n for n in range(len(c)):\n classrl[k].append(0)\n k=k+1\n for i in rl:\n for k in range(0, len(i)):\n for j in range(len(classfy)):\n for n in range(1, len(classfy[j])):\n if classfy[j][n]==k+2:\n if i[k]==\"1\":\n classrl[j][n]=classrl[j][n]+1\n #self.db.close()\n read_txt.close()\n return classrl\n def getscale(self, result):\n scalelist=[]\n if len(result)>0:\n sum=0\n #scalelist.append(result[0])\n for l in range(1, len(result)):\n sum=sum+result[l]\n if sum==0:\n return 0\n for l in range(1, len(result)):\n scalelist.append(result[l]/sum)\n return scalelist\n def getbest(self, classrl, name):\n data_name=source.Erealdata[name]\n classfy=source.Eclassfy[name]\n resultlist=[]\n for c in classrl:\n rl=[]\n for i in range(1, len(c)):\n rl.append(c[i])\n resultlist.append(rl)\n bestlist=[]\n biglist=[]\n for r in resultlist:\n biglist.append(r.index(self.compare(r)))\n i=0\n for big in biglist:\n bestlist.append(data_name[classfy[i][big+1]-1])\n i=i+1\n return bestlist\n def compare(self, list):\n big=0\n for s in list:\n if s>big:\n big=s\n return big\n def get_alldata(self):\n rl=[]\n self.num=0\n for n in source.enginename:\n read_txt=Read_txt(source.Edbname[n])\n result=read_txt.readlines()\n if result==\"error\":\n return \"error\"\n self.num=self.num+len(result)-1\n for r in result:\n res=r.split(',')\n res.pop()\n rl.append(res)\n rl.pop()\n self.all_result[n]=rl\n rl=[]\n read_txt.close()\n return self.all_result\n def get_allscale(self, name):\n result=self.all_result[name]\n return len(result)/self.num\n def get_wages(self):\n read_txt=Read_txt(\"wages\")\n result=read_txt.readlines()\n name=\"\"\n wage=0\n if result==\"error\":\n return \"error\"\n for r in result:\n res=r.split('-')\n if len(res)==3:\n name=res[0]\n wage=(int(res[1])+int(res[2]))/2\n self.all_wages[name].append(wage)\n for n in source.enginename:\n wage=0\n for w in self.all_wages[n]:\n wage=wage+w\n if len(self.all_wages[n])>0:\n wage=wage/len(self.all_wages[n])\n self.all_Ewages[n]=int(wage)\n return self.all_Ewages\n","sub_path":"spider-engineer/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"331226789","text":"\"\"\"\n while 循环计数\n 循环以前 创建计数器\n 循环条件 判断计数器是否满足条件\n 循环以内 累加\n exercise:exercise13\n\n\"\"\"\n# 抄5遍\ncount = 1\nwhile count <= 5:# 1 ~ 5\n print(\"抄\" + str(count) + \"遍\")\n count += 1 # 累加1\n\n# 在终端中显示0 1 2 3\n# 在终端中显示2 3 4 5 6\n# 在终端中显示1 3 5 7\n# 在终端中显示8 7 6 5 4\n# 在终端中显示-1 -2 -3 -4 -5\n","sub_path":"day03_all/day03/demo11.py","file_name":"demo11.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"468094807","text":"###Autor: Jose Luis Mata Lomeli\r\n###Calcular Area y Perimetro de dos rectángulos y comparar cual tiene mayor area o si es igual\r\n\r\n##Calcular el Area y Perimetro del 1er Rectangulo:\r\n#Area del 1er Rectángulo\r\ndef rectangulo1Area(rectArea1_1, rectArea2_1):\r\n\r\n area1 = rectArea1_1 * rectArea2_1\r\n return area1\r\n\r\n#Perimetro del 1er Rectángulo\r\ndef rectangulo1Perimetro(rectPeri1_1, rectPeri2_1):\r\n\r\n perimetro1 = 2*(rectPeri1_1 + rectPeri2_1)\r\n return perimetro1\r\n\r\n\r\n##Calcular Area y Perimetro del 2do Rectangulo:\r\n#Area del 2do rectángulo\r\ndef rectangulo2Area(rectArea1_2, rectArea2_2):\r\n\r\n area2 = rectArea1_2 * rectArea2_2\r\n return area2\r\n\r\n#Perimetro del 2do rectángulo\r\ndef rectangulo2Perimetro(rectPeri1_2, rectPeri2_2):\r\n\r\n perimetro2 = 2 *(rectPeri1_2 + rectPeri2_2)\r\n return perimetro2\r\n\r\n##Compara las Areas de ambos rectángulos:\r\ndef compararAreas (a1, a2):\r\n\r\n if a1 > a2:\r\n return (\"el 1er rectangulo; con %d de area\" % (a1))\r\n else:\r\n if a2 > a1:\r\n return (\"el 2do rectangulo; con %d de area\" % (a2))\r\n else:\r\n if a1 == a2:\r\n return (\"ninguna. El 1er y 2do rectangulo tienen la misma area\")\r\n\r\n##Comparar los Perimetros de Ambos rectangulos\r\ndef compararPerimetros(p1, p2):\r\n if p1 > p2:\r\n return (\"el 1er rectangulo; con %d de perimetro\" % (p1))\r\n else:\r\n if p2 > p1:\r\n return (\"el 2do rectangulo; con %d de perimetro\" % (p2))\r\n else:\r\n if p1 == p2:\r\n return (\"ninguno. El 1er y 2do rectangulo tienen el mismo perimetro\")\r\n\r\n\r\n###Función principal\r\ndef main():\r\n\r\n dimension1_1 = int(input(\"Escriba la base del 1er rectangulo: \"))\r\n dimension2_1 = int(input(\"Escriba la altura del 1er rectangulo: \"))\r\n\r\n area1 = rectangulo1Area(dimension1_1, dimension2_1)\r\n perimetro1 = rectangulo1Perimetro(dimension1_1, dimension2_1)\r\n\r\n print(\" \") #Espacio entre lineas\r\n\r\n print (\"El area del 1er rectangulo es de \", area1)\r\n print (\"Mientras que el perimetro es de \", perimetro1)\r\n\r\n#################################################################################\r\n\r\n print(\" \") #Espacio entre lineas\r\n\r\n dimension1_2 = int(input(\"Escribe la base del 2do rectangulo: \"))\r\n dimension2_2 = int(input(\"Escribe la altura del 2do rectangulo: \"))\r\n\r\n area2 = rectangulo2Area(dimension1_2, dimension2_2)\r\n perimetro2 = rectangulo2Perimetro(dimension1_2, dimension2_2)\r\n\r\n print(\" \") #Espacio entre lineas\r\n\r\n print(\"El area del 2do rectangulo es de \", area2)\r\n print(\"Mientras que perimetro es de : \", perimetro2)\r\n\r\n###################################################################################\r\n\r\n print(\" \") #Espacio entre lineas\r\n\r\n mayor_area = compararAreas(area1, area2)\r\n print (\"Si quieres saber cual tuvo una mayor area, fue...\",(mayor_area))\r\n\r\n mayor_perimetro = compararPerimetros(perimetro1, perimetro2)\r\n print (\"Y si quieres saber cual tuvo un mayor perimetro, fue...\",(mayor_perimetro))\r\n\r\nmain()","sub_path":"Rectangulos.py","file_name":"Rectangulos.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"523060029","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(\"\")\n dummy.next = head\n start = head\n length = 0\n while start != None:\n start = start.next\n length += 1\n length = length - n\n start = dummy\n while length>0:\n length-=1\n start = start.next\n start.next = start.next.next\n return dummy.next ","sub_path":"RemoveNthFromEnd/RemoveNthFromEnd.py","file_name":"RemoveNthFromEnd.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"493319355","text":"import matplotlib.pyplot as plt\n\n\nclass Graficador:\n def graficar(self, values):\n plt.title(\"Frecuencia cardiaca\")\n plt.plot(values, color=\"red\", label=\"Frecuencia\")\n\n plt.legend(loc=4, framealpha=0.7)\n plt.show()\n return\n","sub_path":"models/graficar.py","file_name":"graficar.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575610038","text":"import wave\nimport struct\nimport math\nfrom even_or_odd import *\n\n\n\"\"\"\nWave class handles opening new wave files and generating waves.\n\"\"\"\n\n\nclass WaveClass:\n id = 0\n\n def __init__(self, output_filename, length_of_file, channels, sample_width, sample_rate, volume, frequency):\n self.output_filename = output_filename\n self.length_of_file = length_of_file\n self.channels = channels\n self.sample_width = sample_width\n self.sample_rate = sample_rate\n self.sample_length = sample_rate / length_of_file\n self.volume = volume\n self.frequency = frequency\n self.id = WaveClass.id\n WaveClass.id += 1\n\n def open_file(self, output_filename):\n \"\"\"\n This opens a new file with a the desired file name to be worked on\n\n :param output_filename: The name of the file\n :return: The new file to be written to\n \"\"\"\n file_to_write = wave.open(output_filename, \"w\")\n return file_to_write\n\n def close_file(self, file_to_close):\n \"\"\"\n This closes the desired file\n\n :param file_to_close: The file to be closed\n :return: Nothing\n \"\"\"\n file_to_close.close()\n\n def sine_wave(self, frequency, index_position, sample_rate, volume):\n \"\"\"\n Creates a sine wave\n\n :param frequency: The frequency of the wave (how close together the waves are)\n :param index_position: The current position in the index\n :param sample_rate: The rate at which the wave is sampled (typically 44100)\n :param volume: The amplitude of the wave (how high it goes)\n :return: The current sample of the wave\n \"\"\"\n new_wave = 0\n new_wave += (math.sin(2.0 * math.pi * frequency * (index_position / sample_rate)) / math.pi) * volume\n packed_value = struct.pack('h', int(new_wave))\n return packed_value\n\n def square_wave(self, frequency, index_position, sample_rate):\n \"\"\"\n Creates a square wave\n\n :param frequency: Frequency of the wave\n :param index_position: Current position in the index\n :param sample_rate: Rate at which the wave is sampled\n :return: 1 or -1\n \"\"\"\n value = 0\n if (math.sin(2.0 * math.pi * frequency * (index_position / sample_rate)) * self.volume) > 0:\n value += self.volume\n else:\n value += -self.volume\n packed_values = struct.pack('h', value)\n return packed_values\n\n def saw_wave(self, frequency, index_position, sample_rate, volume, max_range):\n \"\"\"\n Creates a saw wave\n :param frequency: The frequency of the wave\n :param index_position: The index position\n :param sample_rate: The rate at which the wave is sampled\n :param volume: The amplitude of the wave\n :param max_range: The maximum range of the wave\n :return: The current sample of the wave\n \"\"\"\n new_wave = 0\n for multiplier in range(1, max_range):\n if is_odd(multiplier):\n multiplier = -multiplier\n print(multiplier)\n new_wave += (math.sin(multiplier * 2.0 * math.pi * frequency * (index_position / sample_rate)) / (multiplier * math.pi))* volume\n packed_values = struct.pack('h', int(new_wave))\n return packed_values\n","sub_path":"wave_class.py","file_name":"wave_class.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"54252978","text":"'''\n bisection search example\n also known as a binary search\n'''\n\n\ndef main():\n cube = int(input(\"Enter in the input: \"))\n epsilon = 0.01\n guessCount = 0\n low = 0\n high = cube\n guess = (high + low) / 2.0\n\n while abs(guess**3 - cube) >= epsilon:\n if guess**3 < cube:\n low = guess\n else:\n high = guess\n guess = (high + low) / 2.0\n guessCount += 1\n\n print('guess count: ', guessCount)\n print(guess, 'is close to the cube root of', cube)\n\nmain()\n","sub_path":"Electrical-Engineering-and-Computer-Science/6.0001/notes/lecture-3/bisection_search.py","file_name":"bisection_search.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"204827086","text":"# Will Harle\r\n\r\n# Professor Johnson\r\n\r\n# Cyber Defense Techniques Homework 3\r\n\r\n# Imports the necessary modules to run the keylogger\r\nfrom pynput.keyboard import Key, Listener\r\nimport logging\r\nimport os\r\n\r\n# An out of the way file path to hide the file\r\nlogPath = r\"C:/Logs/.ssh/\"\r\n\r\n# On the off chance the directory does not exist, it will create one\r\nif not os.path.exists(logPath):\r\n os.makedirs(logPath)\r\n\r\n# Give the file an official looking name and format it to store keys\r\nlogging.basicConfig(filename = (logPath + \"auth.log\"), level=logging.DEBUG, format='%(message)s')\r\n\r\n# Log whenever a key is hit\r\ndef on_press(key):\r\n\tlogging.info(str(key))\r\n\r\n# Create a listening instance to store the keys that are hit\r\nwith Listener(on_press=on_press) as receiver:\r\n\treceiver.join()\r\n","sub_path":"tools/will/WillHarleRedTeamTool.py","file_name":"WillHarleRedTeamTool.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"532597923","text":"import time\nimport pickle\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tqdm import tqdm\nfrom utils import *\n\n\n\nclass GAN():\n\n def __init__(self, sess, batch_size = 100, lr_rate = 0.0002, epochs = 100, keep_prob = 0.3, random_dim = 100):\n\n # training hyperparameters\n self.batch_size = batch_size\n self.lr_rate = lr_rate\n self.epochs = epochs\n self.keep_prob = keep_prob\n self.random_dim = random_dim\n\n # generate fixed inputs form gaussian normal\n self.fixed_z_ = np.random.normal(0, 1, (25, random_dim))\n\n # tensorflow session object \n self.sess = sess\n\n # construct model\n self.__construct_model()\n sess.run(tf.global_variables_initializer())\n\n\n def __generator(self, x):\n \n # initializers\n w_init = tf.truncated_normal_initializer(mean=0, stddev=0.02)\n w_init_xavier = tf.contrib.layers.xavier_initializer()\n b_init = tf.constant_initializer(0.)\n\n # 1st hidden layer\n w0 = tf.get_variable('G_w0', [x.get_shape()[1], 256], initializer=w_init)\n b0 = tf.get_variable('G_b0', [256], initializer=b_init)\n h0 = lrelu(tf.matmul(x, w0) + b0)\n\n # 2nd hidden layer\n w1 = tf.get_variable('G_w1', [h0.get_shape()[1], 512], initializer=w_init_xavier)\n b1 = tf.get_variable('G_b1', [512], initializer=b_init)\n h1 = lrelu(tf.matmul(h0, w1) + b1)\n\n # 3rd hidden layer\n w2 = tf.get_variable('G_w2', [h1.get_shape()[1], 1024], initializer=w_init_xavier)\n b2 = tf.get_variable('G_b2', [1024], initializer=b_init)\n h2 = lrelu(tf.matmul(h1, w2) + b2)\n\n # output hidden layer\n w3 = tf.get_variable('G_w3', [h2.get_shape()[1], 784], initializer=w_init_xavier)\n b3 = tf.get_variable('G_b3', [784], initializer=b_init)\n o = tf.nn.tanh(tf.matmul(h2, w3) + b3)\n\n return o\n \n def __discriminator(self, x, drop_out):\n\n # initializers\n w_init = tf.truncated_normal_initializer(mean=0, stddev=0.02)\n w_init_xavier = tf.contrib.layers.xavier_initializer()\n b_init = tf.constant_initializer(0.)\n\n # 1st hidden layer\n w0 = tf.get_variable('D_w0', [x.get_shape()[1], 1024], initializer=w_init)\n b0 = tf.get_variable('D_b0', [1024], initializer=b_init)\n h0 = lrelu(tf.matmul(x, w0) + b0)\n h0 = tf.nn.dropout(h0, drop_out)\n\n # 2nd hidden layer\n w1 = tf.get_variable('D_w1', [h0.get_shape()[1], 512], initializer=w_init_xavier)\n b1 = tf.get_variable('D_b1', [512], initializer=b_init)\n h1 = lrelu(tf.matmul(h0, w1) + b1)\n h1 = tf.nn.dropout(h1, drop_out)\n\n # 3rd hidden layer\n w2 = tf.get_variable('D_w2', [h1.get_shape()[1], 256], initializer=w_init_xavier)\n b2 = tf.get_variable('D_b2', [256], initializer=b_init)\n h2 = lrelu(tf.matmul(h1, w2) + b2)\n h2 = tf.nn.dropout(h2, drop_out)\n\n # output layer\n w3 = tf.get_variable('D_w3', [h2.get_shape()[1], 1], initializer=w_init_xavier)\n b3 = tf.get_variable('D_b3', [1], initializer=b_init)\n o = tf.matmul(h2, w3) + b3\n\n return o \n\n def __construct_model(self):\n # networks : generator\n with tf.variable_scope('G'):\n self._z = tf.placeholder(tf.float32, shape=(None, self.random_dim))\n self._fake_y = tf.placeholder(tf.float32, shape=(None))\n self._G_z = self.__generator(self._z)\n\n # networks : discriminator\n with tf.variable_scope('D') as scope:\n self._drop_out = tf.placeholder(dtype=tf.float32, name='drop_out')\n self._real_y = tf.placeholder(tf.float32, shape=(None))\n self._x = tf.placeholder(tf.float32, shape=(None, 784))\n D_real = self.__discriminator(self._x, self._drop_out)\n scope.reuse_variables()\n D_fake = self.__discriminator(self._G_z, self._drop_out)\n\n\n # loss for each network\n #eps = 1e-2\n #self._D_loss = tf.reduce_mean(-tf.log(D_real+eps) - tf.log(1 - D_fake+eps))\n #self._G_loss = tf.reduce_mean(-tf.log(D_fake+eps))\n \n # alternative loss function\n D_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real, labels=self._real_y))\n D_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=self._fake_y))\n self._D_loss = D_loss_real + D_loss_fake\n self._G_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake, labels=self._real_y))\n \n\n # trainable variables for each network\n t_vars = tf.trainable_variables()\n D_vars = [var for var in t_vars if 'D_' in var.name]\n G_vars = [var for var in t_vars if 'G_' in var.name]\n\n # optimizer for each network\n self._D_optim = tf.train.AdamOptimizer(self.lr_rate, beta1 = 0.5).minimize(self._D_loss, var_list=D_vars)\n self._G_optim = tf.train.AdamOptimizer(self.lr_rate, beta1 = 0.5).minimize(self._G_loss, var_list=G_vars)\n\n\n def fit(self, train_set):\n\n train_var = [self._z, self._G_z, self._drop_out]\n tf.add_to_collection('train_var', train_var[0])\n tf.add_to_collection('train_var', train_var[1])\n tf.add_to_collection('train_var', train_var[2])\n \n saver = tf.train.Saver(max_to_keep=25)\n saver.export_meta_graph('models/gan_model_ckpt.meta', collection_list=['train_var'])\n \n\n train_hist = {}\n train_hist['D_losses'] = []\n train_hist['G_losses'] = []\n train_hist['per_epoch_ptimes'] = []\n train_hist['total_ptime'] = []\n \n # training-loop\n print('training start!')\n start_time = time.time()\n for epoch in range(self.epochs):\n G_losses = []\n D_losses = []\n epoch_start_time = time.time()\n idx = np.arange(train_set.shape[0])\n np.random.shuffle(idx)\n for iter in tqdm(range(train_set.shape[0] // self.batch_size)):\n # update discriminator\n x_ = train_set[idx[iter*self.batch_size:(iter+1)*self.batch_size]]\n #x_ = train_set[np.random.randint(0, train_set.shape[0], size=self.batch_size)]\n z_ = np.random.normal(0, 1, (x_.shape[0], self.random_dim))\n \n # soft labels\n y_real_ = np.ones(x_.shape[0])*0.9\n y_fake_ = np.zeros(x_.shape[0])\n loss_d_, _ = self.sess.run([self._D_loss, self._D_optim], {self._x: x_, self._z: z_, self._real_y: y_real_, self._fake_y: y_fake_, self._drop_out: self.keep_prob})\n\n D_losses.append(loss_d_)\n\n # update generator\n z_ = np.random.normal(0, 1, (x_.shape[0], self.random_dim))\n y_real_ = np.ones(x_.shape[0])\n loss_g_, _ = self.sess.run([self._G_loss, self._G_optim], {self._z: z_, self._real_y: y_real_, self._drop_out: self.keep_prob})\n G_losses.append(loss_g_)\n\n if (epoch+1) % 20 == 0:\n saver.save(self.sess, 'models/gan_model_ckpt', global_step=epoch+1)\n\n epoch_end_time = time.time()\n per_epoch_ptime = epoch_end_time - epoch_start_time\n print('[%d/%d] - ptime: %.2f loss_d: %.3f, loss_g: %.3f' % ((epoch + 1), self.epochs, per_epoch_ptime, np.mean(D_losses), np.mean(G_losses)))\n p = 'results/gan_random_results/generated_image_epoch_' + str(epoch + 1) + '.png'\n fixed_p = 'results/gan_fixed_results/generated_image_epoch_' + str(epoch + 1) + '.png'\n save_results(self, (epoch + 1), path=p, isFix=False)\n save_results(self, (epoch + 1), path=fixed_p, isFix=True)\n train_hist['D_losses'].append(np.mean(D_losses))\n train_hist['G_losses'].append(np.mean(G_losses))\n train_hist['per_epoch_ptimes'].append(per_epoch_ptime)\n\n end_time = time.time()\n total_ptime = end_time - start_time\n train_hist['total_ptime'].append(total_ptime)\n\n print('Avg per epoch ptime: %.2f, total %d epochs ptime: %.2f' % (np.mean(train_hist['per_epoch_ptimes']), self.epochs, total_ptime))\n print(\"Training finish!... save training results\")\n with open('results/gan_train_history.pkl', 'wb') as f:\n pickle.dump(train_hist, f)\n save_train_history(train_hist, path='results/gan_train_history.png')\n save_animation(self.epochs, 'results/gan_animation.gif', 'results/gan_fixed_results/')\n\n def generate(self, isFix = False, number = 1):\n if isFix:\n return self.sess.run(self._G_z, {self._z: self.fixed_z_, self._drop_out: 0.0})\n z = np.random.normal(0, 1, (number, self.random_dim))\n return self.sess.run(self._G_z, {self._z: z, self._drop_out: 0.0})\n\n\n def load(self, epoch):\n saver = tf.train.Saver()\n saver.restore(self.sess, 'models/gan_model_ckpt-' + str(epoch))\n\n","sub_path":"gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":9059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"418116729","text":"import numpy as np\nimport scipy\nfrom scipy import misc\nfrom scipy.ndimage.interpolation import map_coordinates\nfrom scipy.ndimage.filters import gaussian_filter\nimport nibabel as nib\nimport glob\nimport skimage.exposure\n\ndef wl_normalization(img):\n img = skimage.exposure.rescale_intensity(img, out_range=(0, 255))\n return img.astype(np.uint8)\n\n\ndef elastic_transform(image, alpha, sigma, random_state=None):\n \"\"\"Elastic deformation of images as described in [Simard2003]_.\n .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\n Convolutional Neural Networks applied to Visual Document Analysis\", in\n Proc. of the International Conference on Document Analysis and\n Recognition, 2003.\n \"\"\"\n assert len(image.shape)==2\n\n if random_state is None:\n random_state = np.random.RandomState(None)\n\n shape = image.shape\n\n dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=\"constant\", cval=0) * alpha\n\n x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')\n # indices = np.reshape(x*0.8, (-1, 1)), np.reshape(y*0.8, (-1, 1))\n indices = np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1))\n # print(indices[0].shape)\n return indices\n # return map_coordinates(image, indices, order=1).reshape(shape)\n\n\nq = 0\nimg_path = []\nHGG_path = sorted(glob.glob(\"/media/zzx/data/2-MICCAI_BraTS_2018/MICCAI_BraTS_2018_Data_Training/HGG/*\"))\nLGG_path = sorted(glob.glob(\"/media/zzx/data/2-MICCAI_BraTS_2018/MICCAI_BraTS_2018_Data_Training/LGG/*\"))\nimg_path=HGG_path+LGG_path\nidx = np.random.choice(285, 285, replace=False)\nfor i in img_path:\n t1path = i+\"/\"+i.split('/')[-1]+\"_t1.nii.gz\"\n t2path = i+\"/\"+i.split('/')[-1]+\"_t2.nii.gz\"\n segpath = i+\"/\"+i.split('/')[-1]+\"_seg.nii.gz\"\n imgt1=nib.load(t1path).get_data()\n imgt2=nib.load(t2path).get_data()\n seg=nib.load(segpath).get_data()\n imgt1 = imgt1[20:220,20:220,:]\n imgt2 = imgt2[20:220,20:220,:]\n seg = seg[20:220,20:220,:]\n seg[seg>0]=1\n orit1 = scipy.ndimage.zoom(imgt1, np.array((128,128,96)) / np.array(imgt1.shape), order = 1)\n oriseg = scipy.ndimage.zoom(seg, np.array((128,128,96)) / np.array(imgt2.shape), order = 0)\n orit1 = wl_normalization(orit1) /255.0\n orit1 = orit1[8:120,:,:]\n oriseg = oriseg[8:120,:,:]\n # print(img)\n # x = np.zeros((112,128))\n # y = np.zeros((112,128))\n # x = np.zeros((220,220))\n # y = np.zeros((220,220))\n # z = np.zeros((220,220))\n x = np.zeros((200,200))\n y = np.zeros((200,200))\n z = np.zeros((200,200))\n\n indice = elastic_transform(x,x.shape[1]*2,x.shape[1]*0.08)\n\n for i in range(imgt1.shape[2]):\n x[:,:] = imgt1[:,:,i]\n y[:,:] = imgt2[:,:,i]\n z[:,:] = seg[:,:,i]\n elastic_imgt1 = map_coordinates(x, indice, order=1).reshape(x.shape)\n elastic_imgt2 = map_coordinates(y, indice, order=1).reshape(y.shape)\n elastic_seg = map_coordinates(z, indice, order=0).reshape(z.shape)\n imgt1[:,:,i] = elastic_imgt1\n imgt2[:,:,i] = elastic_imgt2\n seg[:,:,i] = elastic_seg\n\n imgt1 = scipy.ndimage.zoom(imgt1, np.array((128,128,96)) / np.array(imgt1.shape), order = 1)\n imgt2 = scipy.ndimage.zoom(imgt2, np.array((128,128,96)) / np.array(imgt2.shape), order = 1)\n seg = scipy.ndimage.zoom(seg, np.array((128,128,96)) / np.array(seg.shape), order = 0)\n imgt1 = wl_normalization(imgt1) / 255.0\n imgt2 = wl_normalization(imgt2) / 255.0\n imgt1 = imgt1[8:120,:,:]\n imgt2 = imgt2[8:120,:,:]\n seg = seg[8:120,:,:]\n\n # imgt1 = np.transpose(imgt1, (2, 1, 0))\n # imgt2 = np.transpose(imgt2, (2, 1, 0))\n # q+=1\n\n if q<236:\n path = \"train\"\n else:\n path = \"test\"\n # q = 1\n\n movvol = nib.Nifti1Image(imgt1,affine = None)\n nib.save(movvol, '/media/zzx/data/rebrats18/%s/t1/%03dt1.nii.gz' % (path,idx[q]))\n fixvol = nib.Nifti1Image(imgt2,affine = None)\n nib.save(fixvol, '/media/zzx/data/rebrats18/%s/t2/%03dt2.nii.gz' % (path,idx[q]))\n ori = nib.Nifti1Image(orit1,affine = None)\n nib.save(ori, '/media/zzx/data/rebrats18/%s/orit1/%03dorit1.nii.gz' % (path,idx[q])) \n segori = nib.Nifti1Image(oriseg,affine = None)\n nib.save(segori, '/media/zzx/data/rebrats18/%s/oriseg/%03doriseg.nii.gz' % (path,idx[q])) \n segvol = nib.Nifti1Image(seg,affine = None)\n nib.save(segvol, '/media/zzx/data/rebrats18/%s/seg/%03dseg.nii.gz' % (path,idx[q])) \n q+=1 \n print(q)\n# scipy.misc.imsave('/media/zzx/elastic.jpg',elastic_img)","sub_path":"deform-gan-beta1/pre.py","file_name":"pre.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622187824","text":"import os\r\nfor s in range(1, 16): #[ 1, 2, 4, 8 ]: global size\r\n\t#print \"NUMT = %d\" % t\r\n\tfor t in [ 8, 64, 128, 256, 512 ]: #[ 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 ]:local size\r\n\t\t#print \"NUMNODES = %d\" % s\r\n\t\t#cmd = \"g++ -DNUMNODES=%d -DNUMT=%d P1.cpp -o prog -lm -fopenmp\" % ( s, t )\r\n\t\tcmd = \"g++ -DNMB=%d -DLOCAL_SIZE=%d first.cpp -o first /scratch/cuda-7.0/lib64/libOpenCL.so -lm -fopenmp\" % ( s, t )\r\n\t\tos.system( cmd )\r\n\t\tcmd = \"./first\"\r\n\t\tos.system( cmd )","sub_path":"p6/submit/first_vg.py","file_name":"first_vg.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"274332603","text":"import re\nfrom dataclasses import dataclass, field\n\nfrom packaging import version\n\nfrom exporter.metadata.exceptions import MetadataParseException\n\n# These are the versions which started using https://schema.humancellatlas.org/system/1.1.0/provenance\n# which introduced the schema_major_version and schema_minor_version\n# The versions are sourced from metadata-schema changelog\n# https://github.com/HumanCellAtlas/metadata-schema/blob/master/changelog.md#systemprovenancejson---v110---2019-07-25\nSCHEMA_VERSIONS_WITHOUT_SCHEMA_FIELDS = {\n 'cell_suspension': '13.2.0',\n 'protocol': '7.1.0',\n 'differentiation_protocol': '2.2.0',\n 'cell_suspension': '13.2.0',\n 'dissociation_protocol': '6.2.0',\n 'reference_file': '3.2.0',\n 'organoid': '11.2.0',\n 'process': '9.2.0',\n 'analysis_file': '6.2.0',\n 'ipsc_induction_protocol': '3.2.0',\n 'analysis_protocol': '9.1.0',\n 'sequence_file': '9.2.0',\n 'aggregate_generation_protocol': '2.1.0',\n 'enrichment_protocol': '3.1.0',\n 'collection_protocol': '9.2.0',\n 'sequencing_protocol': '10.1.0',\n 'supplementary_file': '2.2.0',\n 'imaged_specimen': '3.2.0',\n 'donor_organism': '15.4.0',\n 'imaging_preparation_protocol': '2.2.0',\n 'image_file': '2.2.0',\n 'project': '14.1.0',\n 'analysis_process': '11.1.0',\n 'cell_line': '14.4.0',\n 'library_preparation_protocol': '6.2.0',\n 'imaging_protocol': '11.2.0',\n 'specimen_from_organism': '10.3.0'\n}\n\n\n@dataclass\nclass MetadataProvenance:\n document_id: str\n submission_date: str\n update_date: str\n schema_major_version: int = field(default=None)\n schema_minor_version: int = field(default=None)\n\n @staticmethod\n def from_dict(data: dict):\n try:\n uuid = data['uuid']['uuid']\n submission_date = data['submissionDate']\n update_date = data['updateDate']\n\n # Populate the major and minor schema versions from the URL in the describedBy field\n schema_semver = re.findall(r'\\d+\\.\\d+\\.\\d+', data[\"content\"][\"describedBy\"])[0]\n concrete_type = data['content']['describedBy'].rsplit('/', 1)[-1]\n version_with_schema_fields = SCHEMA_VERSIONS_WITHOUT_SCHEMA_FIELDS.get(concrete_type)\n if MetadataProvenance.version_has_schema_fields(schema_semver, version_with_schema_fields):\n schema_major_version, schema_minor_version = [int(x) for x in schema_semver.split(\".\")][:2]\n return MetadataProvenance(uuid, submission_date, update_date, schema_major_version,\n schema_minor_version)\n else:\n return MetadataProvenance(uuid, submission_date, update_date)\n except (KeyError, TypeError) as e:\n raise MetadataParseException(e)\n\n @staticmethod\n def version_has_schema_fields(schema_semver, version_with_schema_fields):\n return not version_with_schema_fields or version.parse(schema_semver) >= version.parse(\n version_with_schema_fields)\n","sub_path":"exporter/metadata/provenance.py","file_name":"provenance.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"262146375","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render, redirect\nfrom django import forms\nfrom django.http import HttpResponse\nfrom website.models import Campus_Ambassdors\nfrom website.forms import Campus_Ambassdor_Form\nfrom django.conf import settings\nfrom django.core.mail import send_mail,EmailMessage\n\n# Create your views here.\ndef index(request):\n context_dict = {}\n return render(request, 'website/index.html', context_dict)\n\n\ndef success(request,context_dict):\n return render(request, 'website/Success.html', context_dict)\n\n\ndef contact(request):\n return render(request, 'website/contact.html')\n\ndef sponsor(request):\n return render(request, 'website/sponsors.html')\n\ndef campusambassador(request):\n form = Campus_Ambassdor_Form()\n context_dict={}\n if request.method == 'POST':\n form = Campus_Ambassdor_Form(request.POST)\n if form.is_valid():\n page = form.save(commit=False)\n email = request.POST['email']\n phone = request.POST['phone']\n subject = \"Greetings from 67th Milestone'18\"\n body1 = u\"Hi,\\n\\n\"+\\\n u\"Greetings from Team 67th Milestone'18 and welcome to our family. \\n\\n\" +\\\n u\"Thank you for applying to Campus Ambassador Internship. We are looking forward to\" \\\n u\" work with you and will get back to you soon regarding the onset of\" \\\n u\" the program once final applications are shortlisted.\\n\\n\"\n body2= u\"All the best!\"\n body3=u\"\\n\\nFor more updates, stay tuned on - \\n\\n\"+\\\n u\"Website - www.67thmilestone.com \\n\"+\\\n u\"Facebook - www.facebook.com/67milestone\\n\"+\\\n u\"Instagram - www.instagram.com/67thmilestone\\n\"+\\\n u\"Twitter - www.twitter.com/67th_milestone\\n\"\n body=body1+body2+body3\n emailsend = EmailMessage(subject,body,to=[email])\n emailsend.send()\n page.save()\n print(phone,email)\n context_dict={}\n context_dict['email']=email\n context_dict['phone']=phone\n return render(request, 'website/Success.html', context_dict)\n else:\n if 'email' in form.errors:\n context_dict['error'] = 'User with this Email already exits'\n print(context_dict)\n if 'phone' in form.errors:\n context_dict['error'] = 'User with this Whatsapp Number already exits'\n print(context_dict)\n return render(request, 'website/error.html', context_dict)\n context_dict['form']=form\n print(context_dict)\n return render(request, 'website/campusamb.html', context_dict)\n\ndef error(request):\n context_dict = {}\n return render(request, 'website/error.html', context_dict)\n","sub_path":"2018/festWebsite/website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104480227","text":"# Mad Lib By Alex Day\n\n\n#Import the OS lib to be used later\nimport os\n#Get users name\nosname = os.getlogin()\n#Welcome the user\nprint(\"Welcome to the program, this is a statement that informs the user that this is a Mad Lib program\")\n#Define a function called Mad_Lib that takes no arguments\ndef mad_lib():\n print()\n #Get input for use in the mad lib\n food = input(\"Enter a food: \")\n drink = input(\"Enter a drink: \")\n thing_you_can_do = input(\"Enter a common activity (no -ed or -ing): \")\n name = input(\"Enter a name: \")\n body_part = input(\"Enter a body part: \")\n name2 = input(\"Enter a different name: \")\n #If nothing was entered then print nothing was entered\n if food == \"\" or drink == \"\" or thing_you_can_do == \"\" or name == \"\" or body_part == \"\" or name2 == \"\":\n print(\"It seems like you didn't enter anything\")\n mad_lib()\n else:\n #Convert the sentences to strings for cleaner code while printing and logging to file\n first = name + \" used a/n \" + body_part + \" to kill \" + name2\n second = \"if you eat \" + food + \" you have to drink more \" + drink + \".\"\n third = \"If you don't drink more \" + drink + \" you will die just like \" + name2\n forth = \"sometimes \" + name2 + \" liked to \" + thing_you_can_do + \" while eating \" + food\n\n #Print the sentences\n print()\n print(first)\n print(second)\n print(third)\n print(forth)\n print()\n\n #Ask the user if they would like to print the Mad Lib to a file\n yorn = input(\"Do you want to output to a file?(y/n)\")\n print()\n yorn = yorn.lower()\n if yorn == \"y\":\n #If they do open the file and write the sentences on different lines while telling the user what is happening\n file = open(osname+\"MadLib.txt\", \"w+\")\n print(\"File created and opened\")\n file.write(first + '\\n')\n file.write(second + '\\n')\n file.write(third + '\\n')\n file.write(forth + '\\n')\n file.write('\\n')\n file.write(\"This Mad Lib was made by \" + osname)\n print(\"File writing completed\")\n file.close()\n print(\"File closed\")\n print()\n #Ask the user if they would like to open the file in their default text editor (normally notepad)\n yorn = input(\"Do you want to open the file?(y/n)\")\n yorn = yorn.lower()\n if yorn == \"y\":\n os.startfile(osname+\"MadLib.txt\")\n\n#Set the play_again variable to true to start the program again\nplay_again = True\n#While the user wants to paly again run the program\nwhile play_again == True:\n mad_lib()\n print()\n #Ask the user if they would like to play again\n yorn = input(\"Do you want to play again? (y/n)\")\n yorn = yorn.lower()\n if yorn == \"y\":\n play_again = True\n else:\n play_again = False\n","sub_path":"Alex Day Mad Lib.py","file_name":"Alex Day Mad Lib.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"354001557","text":"import sys\nsys.path.append(\"../hs\")\nfrom hs import HS\n\nclass SWProcess (object):\n '''Типы процессов: работа (расширения или сжатия), нагрев - охдаждение\n дросселирование, переход в состояние кипящей воды, \n переход в состояние сухого насыщенного пара'''\n proctypes = ('work','heating','throttling', 'boiling_water', \n 'dry_saturated_steam')\n def __init__(self):\n '''Список словарей процессов: \"type\", \"start_point\", \"end_point\",\n \"end_point0\" - конечная точка идельного процесса'''\n self.processes =[]\n self.hs = HS ()\n self.start_point = {}\n '''Начальная точка для процесса. Для первого процесса это \n self.start_point, для последующих процессов - это end_point \n предыдущего процесса'''\n self.cur_start_point = {}\n self.end_point = {}\n \n def startpoint_pT (self, p, T):\n self.__set_start_point (self.hs.prop_pT (p, T))\n\n \n def startpoint_px (self, p, x):\n self.__set_start_point (self.hs.prop_px (p, x))\n\n \n def startpoint_ph (self, p, h):\n self.__set_start_point (self.hs.prop_ph (p, h))\n\n def startpoint_ps (self, p, s):\n self.__set_start_point (self.hs.prop_ps (p, s))\n\n def __set_start_point(self, prop):\n self.start_point = prop\n self.end_point = {}\n self.processes =[]\n self.cur_start_point = self.start_point\n \n def work (p, efficiency):\n check_start_point()\n '''Если '''\n \n \n \n \n\nif __name__ == \"__main__\":\n swp = SWProcess()\n T = 293\n p = 101325\n prop = swp.startpoint_pT(p, T)\n \n print (prop['h'], prop['u'] + prop['p']*prop['v'])\n\n \n print (swp.startpoint_ph(p, prop['h'])['T'] - T)\n print (swp.startpoint_ps(p, prop['s'])['T'] - T) \n #print(prop)\n \n x = 0\n print (swp.startpoint_px(p, x))\n \n x = 1\n print (swp.startpoint_px(p, x))\n\n prop = swp.startpoint_px(p, x)\n print (prop['h'], prop['u'] + prop['p']*prop['v'])\n","sub_path":"proc/swprocesses.py","file_name":"swprocesses.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"21844743","text":"from django.core import validators\nfrom django.db import models\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import (\n AbstractBaseUser, BaseUserManager, PermissionsMixin\n)\nimport ulid\n\nfrom utils.customfield import ULIDField\n\n\nclass UserManager(BaseUserManager):\n\n def create_user(self, email, password=None, **extra_fields):\n if not email:\n raise ValueError('Emailは必須です')\n\n user = self.model(email=self.normalize_email(email), **extra_fields)\n user.set_password(password)\n user.save(using=self._db)\n\n return user\n\n def create_superuser(self, email, password):\n user = self.create_user(email, password)\n user.is_staff = True\n user.is_superuser = True\n user.save(using=self._db)\n\n return user\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n id = ULIDField(default=ulid.new, primary_key=True, editable=False)\n email = models.EmailField(max_length=255, unique=True)\n is_active = models.BooleanField(default=True)\n is_staff = models.BooleanField(default=False)\n\n objects = UserManager()\n\n USERNAME_FIELD = 'email'\n\n def __str__(self):\n return self.email\n\n\nclass Profile(models.Model):\n id = ULIDField(default=ulid.new, primary_key=True, editable=False)\n nickname = models.CharField(\n max_length=20,\n null=True,\n blank=False,\n default='名無し'\n )\n user = models.OneToOneField(\n get_user_model(),\n on_delete=models.CASCADE\n )\n exercise_flag = models.BooleanField(default=False)\n created_on = models.DateTimeField(auto_now_add=True)\n updated_on = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.nickname\n\n\nclass Exercise(models.Model):\n\n EXERCISE_TYPE_CHOICES = (\n ('A', 'SetA'),\n ('B', 'SetB'),\n ('AB', 'Always')\n )\n\n DEFAULT_REP_CHOICES = (\n ('1', '1rep / 1set'),\n ('5', '5rep / 1set')\n )\n\n name = models.CharField(max_length=50)\n exercise_type = models.CharField(\n max_length=2,\n choices=EXERCISE_TYPE_CHOICES\n )\n default_rep = models.CharField(\n max_length=2,\n choices=DEFAULT_REP_CHOICES\n )\n created_on = models.DateTimeField(auto_now_add=True)\n updated_on = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.name\n\n\nclass ExerciseLog(models.Model):\n id = ULIDField(default=ulid.new, primary_key=True, editable=False)\n user = models.ForeignKey(\n get_user_model(),\n on_delete=models.CASCADE\n )\n exercise = models.ForeignKey(\n Exercise,\n on_delete=models.CASCADE\n )\n exercise_date = models.DateField()\n set_weight = models.DecimalField(default=0, max_digits=4, decimal_places=1)\n one_set = models.PositiveSmallIntegerField(default=0)\n two_set = models.PositiveSmallIntegerField(default=0)\n three_set = models.PositiveSmallIntegerField(default=0)\n four_set = models.PositiveSmallIntegerField(default=0)\n five_set = models.PositiveSmallIntegerField(default=0)\n created_on = models.DateTimeField(auto_now_add=True)\n updated_on = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return f'{self.user}: {self.set_weight}'\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"391563151","text":"\n\n#calss header\nclass _CLUE():\n\tdef __init__(self,): \n\t\tself.name = \"CLUE\"\n\t\tself.definitions = [u'a sign or some information that helps you to find the answer to a problem, question, or mystery: ']\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/_clue.py","file_name":"_clue.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127158083","text":"from flask import Flask, render_template, url_for, jsonify, request, redirect\nimport os\nimport math\nimport numpy as np\nimport json\nimport random\n\napp = Flask(__name__);\napp._static_folder_ = os.path.abspath('templates/static');\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\nGRID_SIZE = 8;\nNUM_TRAIN = 5;\nNUM_TRIAL = 5;\n\ndistance_fraction = 0.5;\ncurrent_max_uncertainty_idx = \"0,0\";\ngridpoints = []\nclicked_buttons = [];\nenabled_buttons = [];\ninput_enabled_buttons = [];\n\nfor i in range(GRID_SIZE):\n\tfor j in range(GRID_SIZE):\n\t\tgridpoints.append((i,j));\ndef get_rand_gridpoints_list(size=3):\n\tres = [];\n\tidx = np.random.randint(0, GRID_SIZE ** 2,size);\n\tfor id_ in idx:\n\t\tres.append(gridpoints[id_]);\n\n\treturn res;\n\ndef dir_last_updated(folder):\n return str(max(os.path.getmtime(os.path.join(root_path, f))\n for root_path, dirs, files in os.walk(folder)\n for f in files))\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\tpid = random.randint(0, 1000);\n\tprint('/%d/train/1'%(pid));\n\tinstructions = '';\n\twith open(url_for('static', filename='txt/maininstructions.txt')[1:], 'r') as f:\n\t\tfor line in f:\n\t\t\tinstructions += line;\n\n\treturn render_template('layouts/index.html',\n\t\tpage_title = 'I haven\\'t yet thought of an experiment name, but it would go here.',\n\t\tbody_text = instructions,\n\t\tbutton_dest = '/%d/train/1'%(pid),\n\t\tbutton_text = 'Begin Training'\n\t\t);\n\n@app.route('//end')\ndef render_end(pid):\n\tinstructions = 'thank you for participating owo';\n\treturn render_template('layouts/index.html',\n\t\tpage_title = 'End',\n\t\tbody_text = instructions,\n\t\tbutton_dest = '/',\n\t\tbutton_text = 'Restart'\n\t\t);\n\n@app.route('//trial/')\ndef render_trial(trial_num, pid):\n\tif int(trial_num) > NUM_TRIAL:\n\t\treturn redirect('/%d/end'%(pid));\n\tinstructions = 'Enter your predictions for the values in the empty locations. \\n\\nClick \\'Continue\\' to continue.';\n\tnext_instructions = 'Select one of your predictions to waive. \\n\\n Click \\'Next\\' to continue.';\n\tgridvals, enabled_buttons, clicked_buttons = get_trial();\n\tprint(gridvals);\n\tprint(enabled_buttons);\n\tprint(clicked_buttons);\n\treturn render_template('layouts/grid.html',\n\t\ttrial_num = int(trial_num), \n\t\tstatic_scripts = [\n\t\t\t{'src': url_for('static', filename='js/jpalette.min.js')}, \n\t\t\t{'src': url_for('static', filename='js/colors.js')},\n\t\t\t{'src': url_for('static', filename='js/grid.js')},\n\t\t\t{'src': 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js'} ],\n\t\ttemplate_scripts = [\n\t\t\t{'src': \"js/main.js\"} ],\n\t\tgrid_values = gridvals,\n\t\tenabled_buttons = enabled_buttons,\n\t\tclicked_buttons = clicked_buttons,\n\t\ttitle_text = 'Test: Terrain',\n\t\ttrial_type = 'trial', \n\t\tpid = pid,\n\t\tinstructions = instructions,\n\t\tnext_instructions = next_instructions);\n\n@app.route('//trialbegin')\ndef render_trialbegin(pid):\n\tinstructions = '';\n\twith open(url_for('static', filename='txt/traininstructions.txt')[1:], 'r') as f:\n\t\tfor line in f:\n\t\t\tinstructions += line;\n\treturn render_template('layouts/index.html',\n\t\tpage_title = 'Training Phase Complete',\n\t\tbody_text = instructions,\n\t\tbutton_dest = '/%d/trial/1'%(pid),\n\t\tbutton_text = 'Begin Trials'\n\t\t);\n\n@app.route('//train/')\ndef render_train(trial_num, pid):\n\tif int(trial_num) > NUM_TRAIN:\n\t\treturn redirect('/%d/trialbegin'%(pid));\n\n\tinstructions = 'Enter your predictions for the values in the empty locations. \\n\\nClick \\'Check\\' to continue.';\n\tnext_instructions = 'Here are the actual values of the boxes you filled in. \\n\\nClick \\'Next\\' to continue.';\n\tgridvals, enabled_buttons, clicked_buttons = get_trial();\n\tprint(type(gridvals[\"0,3\"]));\n\tprint(type(enabled_buttons[0][0]));\n\tprint(type(clicked_buttons[0]));\n\n\treturn render_template('layouts/grid.html',\n\t\ttrial_num = int(trial_num), \n\t\tstatic_scripts = [\n\t\t\t{'src': url_for('static', filename='js/jpalette.min.js')}, \n\t\t\t{'src': url_for('static', filename='js/colors.js')},\n\t\t\t{'src': url_for('static', filename='js/grid.js')},\n\t\t\t{'src': 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js'} ],\n\t\ttemplate_scripts = [\n\t\t\t{'src': \"js/main.js\"} ],\n\t\tgrid_values = gridvals,\n\t\tenabled_buttons = enabled_buttons,\n\t\tclicked_buttons = clicked_buttons,\n\t\ttitle_text = 'Training: Terrain',\n\t\ttrial_type = 'train',\n\t\tpid = pid,\n\t\tinstructions = instructions,\n\t\tnext_instructions = next_instructions);\n\"\"\"\n@app.route('/postmethod', methods = ['POST'])\ndef get_post_javascript_data():\n jsdata = request.form['javascript_data'];\n\n id_ = json.loads(jsdata);\n targets = id_['target'];\n print(targets);\n\n return jsonify(get_val_dict(id_['numCells'], targets));\n\"\"\"\n@app.route('/postmethod', methods = ['POST'])\ndef get_post_javascript_data():\n jsdata = request.form['javascript_data'];\n\n click_data = json.loads(jsdata);\n \n print(\"\\n{}\\n\".format(click_data));\n\n return \"0\";\n\ndef get_cell_val(idx, idy):\n\tval = abs(float('%.1f'%(np.sin(idx * idy))));\n\tval = idx*idy;\n\n\tgrid = np.linspace(-5, 5, 10000);\n\tx = vec_to_buck(grid, 8, idx);\n\ty = vec_to_buck(grid, 8, idy);\n\txx, yy = np.meshgrid(x, y);\n\n\tz = griewank(xx,yy);\n\tval = abs(int(55*np.mean(z)));\n\t#val = abs(float('%.1f'%(np.mean(z))))\n\treturn val;\n\ndef listidx_to_stringidx(listidx):\n\treturn str(listidx[0] + \",\" + listidx[1]);\n\n\ndef gridvals_to_dict(gridvals):\n\tvaldict = {};\n\tfor i in range(len(gridvals)):\n\t\tfor j in range(len(gridvals[0])):\n\t\t\tvaldict[str(i) + \",\" + str(j)] = gridvals[i][j];\n\n\treturn valdict;\n\ndef scalar_to_2dindex(idx, n):\n\tidx1 = int(idx / n);\n\tidx2 = (idx % n).item();\n\treturn (idx1, idx2);\n\ndef assemble_trial(filename):\n\tjson_dict = {};\n\tprint(filename);\n\tif os.path.isfile(filename):\n\t\twith open(filename, 'r') as f_in:\n\t\t\tjson_dict = json.load(f_in);\n\n\trevealed_idx = json_dict['revealed_idx'];\n\tjson_dict['revealed_idx'] = revealed_idx;\n\tuncertainty_variance = json_dict['uncertainty_variance'];\n\tgridvals = gridvals_to_dict(json_dict['gridvals']);\n\tvariances = np.array(json_dict['variances']);\n\n\tclicked_buttons = [(idx[0],idx[1]) for idx in revealed_idx];\n\t\n\tfor idx in clicked_buttons:\n\t\tvariances[idx] = np.inf;\n\n\tprint(variances);\n\tenabled_buttons = [];\n\n\t# picking lowest variance point at random\n\tmin_var = np.min(variances);\n\tmin_idx, min_idy = np.where(variances == min_var);\n\trandi = np.random.randint(len(min_idx));\n\t# print(min_var);\n\t# print(min_idx[randi], min_idy[randi]);\n\tenabled_buttons.append((int(min_idx[randi]), int(min_idy[randi])));\n\n\t# picking highest variance point at random\n\tvariances = np.where(variances == np.inf, np.NINF, variances)\n\tmax_var = np.max(variances);\n\tmax_idx, max_idy = np.where(variances == max_var);\n\trandi = np.random.randint(len(max_idx));\n\tenabled_buttons.append((int(max_idx[randi]), int(max_idy[randi])));\n\n\t# picking intermediate variance point at random\n\tint_var = distance_fraction * (max_var - min_var);\n\tvariances = np.where(variances == np.NINF, np.inf, variances)\n\tprint(int_var)\n\tdistance = np.abs(variances - min_var - int_var);\n\tprint(distance);\n\tint_idx, int_idy = np.where(distance == np.min(distance));\n\trandi = np.random.randint(len(int_idx));\n\tenabled_buttons.append((int(int_idx[randi]), int(int_idy[randi])));\n\n\treturn gridvals, enabled_buttons, clicked_buttons;\n\n\ndef get_trial():\n\tfile_num = np.random.randint(1,6);\n\tfilename = 'valdicts/sample{}.json'.format(file_num);\n\tgridvals, enabled_buttons, clicked_buttons = assemble_trial(filename);\n\treturn gridvals, enabled_buttons, clicked_buttons;\n\ndef get_val_dict(num_cells):\n\tval_dict = np.random.randint(1,6);\n\tfilename = \"valdicts/valdict{}.json\".format(val_dict);\n\tif os.path.isfile(filename):\n\t\twith open(filename, 'r') as f_in:\n\t\t\treturn json.load(f_in);\n\n\tval_dict = {}\n\tfor i in range(num_cells):\n\t\tfor j in range(num_cells):\n\t\t\tidx = str(i)+','+str(j);\n\t\t\tval_dict[idx] = get_cell_val(i, j);\n\n\twith open('valdict.json', 'w') as f_out:\n\t\tf_out.write(json.dumps(val_dict));\n\n\tprint(max(val_dict.values()));\n\tprint(min(val_dict.values()));\n\tprint('\\n');\n\treturn val_dict;\n\ndef vec_to_buck(vec, nbucks, buckid):\n\tvec_size = len(vec);\n\tnum_per_buck = math.ceil(vec_size/nbucks);\n\t\n\tfor i in range(nbucks):\n\t\tstart = i * num_per_buck;\n\n\t\tidx = np.arange(start, start+num_per_buck-1, 1).astype(int);\n\t\tif idx[-1] > vec_size-1:\n\t\t\tidx = np.arange(start, vec_size, 1).astype(int)\n\t\tif i == buckid:\n\t\t\treturn vec[idx];\n\ndef griewank(x,y):\n\tt1 = (x**2)/4000 + (y**2)/4000;\n\tt2 = np.cos(x) * np.cos(y / np.sqrt(2));\n\treturn t1 - t2 + 1;\n\nif __name__ == '__main__':\n\ttest = np.arange(0, 100, 1);\n\tfor i in range(8):\n\t\tprint(vec_to_buck(test, 8, i));\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"435733438","text":"## validate_mastervisa.py\n## Algorithm to validate a user input MasterCard or VISA credit card number\n\nimport re\n \ndef master_or_visa(number):\n if number.isdigit() == True:\n if len(number) == 16:\n if number[0] == '4':\n return validate_visa(number)\n elif number[0] == '5':\n return validate_mc(number)\n elif len(number) == 13:\n if number[0] == '4':\n return validate_visa(number)\n else:\n return \"This does not belong to MasterCard or VISA.\"\n\n\n\ndef validate_visa(visa):\n if re.match('^4[0-9]{12}(?:[0-9]{3})?$', visa):\n return \"VISA card number is valid.\"\n else:\n return \"Invalid VISA card number.\"\n \n \n\ndef validate_mc(mc):\n if re.match('^5[1-5][0-9]{14}$', mc):\n return \"MasterCard card number is valid.\"\n else:\n return \"Invalid MasterCard number.\"\n\nccnum = input(\"Enter credit card number: \")\n\nccnum = ccnum.replace(\" \",\"\")\n\nprint(master_or_visa(ccnum))\n","sub_path":"validate_mastervisa.py","file_name":"validate_mastervisa.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"276290439","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\npoints = 200\nx = np.linspace(-2.2,2.2,points)\n\nprint('#! FIELDS time d1.x d1.y')\ntime = 0.0\nfor p1 in range(points):\n for p2 in range(points):\n print(time,x[p1],x[p2])\n time = time + 1.0\n\nnp.savetxt('bins_x.dat',x)\nnp.savetxt('bins_y.dat',x)\n","sub_path":"exercises/reweight-zeta-potential-mono/reference/construct_grid.py","file_name":"construct_grid.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"150986953","text":"#1/usr/bin/evn python3\n\n'''\nThis program for pasrsing data from hh.ru\n'''\n\ndef hh_parser(vacancy):\n #import modules\n import requests\n from bs4 import BeautifulSoup as bs\n \n \n headers = {\"accept\": \"*/*\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.132\"}\n url = \"https://perm.hh.ru/search/vacancy?area=72&clusters=true&enable_snippets=true&text={}&page=0\".format(vacancy) #page=0 is the first page. (How parse all?)\n jobs = []\n urls = []\n urls.append(url)\n #make first request\n session = requests.Session()\n request = session.get(url, headers=headers)\n \n #chek answer\n if request.status_code == 200:\n print(\"{}: OK\".format(vacancy))\n else:\n return request.status_code\n \n #Found count of pages with our vacancy.\n soup = bs(request.content, \"lxml\")\n try:\n pagination = soup.find_all('a', attrs={\"data-qa\":\"pager-page\"}) #try to find all page_switch elements.\n count = int(pagination[-1].text)\n for i in range (count+1):\n url = \"https://perm.hh.ru/search/vacancy?area=72&clusters=true&enable_snippets=true&text={0}&page={1}\".format(vacancy,i)\n urls.append(url)\n except IndexError:\n pass\n \n #make soup again for all pages\n for url in urls:\n session = requests.Session()\n request = session.get(url, headers=headers)\n soup = bs(request.content, \"lxml\")\n divs = soup.find_all(\"div\", attrs={\"data-qa\":\"vacancy-serp__vacancy\"})\n #grab information\n for div in divs:\n title = div.find('a', attrs={\"data-qa\":\"vacancy-serp__vacancy-title\"}).text\n href = div.find('a', attrs={\"data-qa\":\"vacancy-serp__vacancy-title\"})[\"href\"]\n company = div.find('a', attrs={\"data-qa\":\"vacancy-serp__vacancy-employer\"}).text\n text1 = div.find('div', attrs={\"data-qa\":\"vacancy-serp__vacancy_snippet_responsibility\"}).text\n text2 = div.find('div', attrs={\"data-qa\":\"vacancy-serp__vacancy_snippet_requirement\"}).text\n disctription = \"{0}\\n{1}\".format(text1, text2)\n try:\n compensation = div.find('div', attrs={\"data-qa\":\"vacancy-serp__vacancy-compensation\"}).text\n except AttributeError:\n compensation = \"0\" \n jobs.append({\n \"title\":title,\n \"compensation\":compensation,\n \"href\":href,\n \"company\":company,\n \"content\":disctription\n })\n return jobs\n \ndef files_writer(jobs):\n '''\n write our vacancies in file.\n '''\n import csv\n with open (\"hh_ru_parsed_jobs.csv\",\"w\") as file:\n a_pen=csv.writer(file)\n a_pen.writerow((\"Название вакансии\",\"Компания\",\"Ссылка\",\"Оплата труда\",\"Описание вакансии\"))\n for job in jobs:\n a_pen.writerow((job[\"title\"],job[\"company\"],job[\"href\"],job[\"compensation\"],job[\"content\"]))\n\n\ndef test():\n '''\n Simple non-unit tests.\n '''\n \n #Test case 1: parsing difference vacancies.\n print (\"__TEST CASE: FIND VECANCIES__\")\n vacancyes = ['python', 'javascript','юрист','sql','адвокат']\n for vacancy in vacancyes:\n print(len(hh_parser(vacancy)))\n \n #Test case 2: write information about vacancies in file.\n print(\"__TEST CASE: WRITE INFO IN FILE__\")\n files_writer(hh_parser(\"python\"))\n \n\ndef main():\n test()\n\nif __name__ == \"__main__\":\n main()","sub_path":"parsers/hh_ru_parser.py","file_name":"hh_ru_parser.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39875238","text":"\"\"\"\n문제\n상근이는 퀴즈쇼의 PD이다. 이 퀴즈쇼의 참가자는 총 8개 문제를 푼다. 참가자는 각 문제를 풀고, 그 문제를 풀었을 때 얻는 점수는 문제를 풀기 시작한 시간부터 경과한 시간과 난이도로 결정한다. 문제를 풀지 못한 경우에는 0점을 받는다. 참가자의 총 점수는 가장 높은 점수 5개의 합이다. \n\n상근이는 잠시 여자친구와 전화 통화를 하느라 참가자의 점수를 계산하지 않고 있었다. 참가자의 8개 문제 점수가 주어졌을 때, 총 점수를 구하는 프로그램을 작성하시오.\n\n입력\n8개 줄에 걸쳐서 각 문제에 대한 참가자의 점수가 주어진다. 점수는 0보다 크거나 같고, 150보다 작거나 같다. 모든 문제에 대한 점수는 서로 다르다. 입력으로 주어지는 순서대로 1번 문제, 2번 문제, ... 8번 문제이다.\n\n출력\n첫째 줄에 참가자의 총점을 출력한다. 둘째 줄에는 어떤 문제가 최종 점수에 포함되는지를 공백으로 구분하여 출력한다. 출력은 문제 번호가 증가하는 순서이어야 한다.\n\"\"\"\n\nimport sys\ninput = sys.stdin.readline\n\nscore = []\nsort_score = []\n\n\nfor i in range(8):\n score.append(int(input()))\n\nfor i in range(8):\n sort_score.append(score[i])\n\nsort_score.sort()\nresult = []\nfor j in range(8):\n if sort_score[2] < score[j]:\n result.append(j+1)\n\nsum = 0\nfor i in range(5):\n sum = sum + score[result[i]-1]\n\nprint(sum)\nfor i in range(5):\n print(result[i],end=' ')","sub_path":"2822_점수 계산.py","file_name":"2822_점수 계산.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"131410779","text":"from django.contrib import admin\nfrom django.conf.urls import url\n\nfrom .views import CustomersView, OrdersView, PingView, ProductView\n\nurlpatterns = [\n url('admin/', admin.site.urls),\n\n url('ping/', PingView.as_view()),\n\n # Endpoints for customers URL.\n url('customer/', CustomersView.as_view(), name='customers'),\n url('customer//', CustomersView.as_view(), name='customers'),\n\n # Endpoints for customers URL.\n url('product/', ProductView.as_view(), name='product'),\n url('product//', ProductView.as_view(), name='product'),\n\n url('order/', OrdersView.as_view(), name='order'),\n]\n","sub_path":"_includes/v19.2/app/insecure/django-basic-sample/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"582331168","text":"\"\"\"extractor\n\"\"\"\nfrom wrdbm.client import DBMClient\nimport random\nfrom pathlib import Path\nimport ijson\nimport voluptuous as vp\n\n\nclass DBMExtractor(DBMClient):\n def _download_lineitems(self, outpath, filter_type, filter_ids=None):\n payload = {\n \"filterType\": filter_type,\n }\n if filter_ids:\n payload[\"filterIds\"] = filter_ids\n\n with open(outpath, 'wb') as out:\n for chunk in self.post_stream(\"/lineitems/downloadlineitems\", json=payload):\n out.write(chunk)\n return outpath\n\n @staticmethod\n def _clean_lineitems_response_via_ijson(inpath, outpath):\n with open(inpath) as f:\n # conntains just 1 lineitem but we still need to iterate\n for item in ijson.items(f, 'lineItems'):\n with open(outpath, 'w') as fout:\n fout.write(item)\n\n @staticmethod\n def _clean_lineitems_response(inpath, outpath):\n \"\"\"the input json looks like this\n '{\"lineItems\": \"actual,csv\\ncontents,yes\"}'\n so this function skips the first and last json string\n\n DOESN'T WORK AT THE MOMENT as the csv is JSON escaped and we would need\n to unescape \\n and \"\n\n \"\"\"\n raise NotImplementedError(\"Dont use this\")\n offset_beginning = 17\n offset_tail = -4\n\n chunksize = 1024\n with open(inpath, 'r') as inf, open(outpath, 'w') as outf:\n # skip the first '{\"lineItems\": \"' characters\n inf.seek(offset_beginning)\n while True:\n chunk = inf.read(chunksize)\n if len(chunk) < chunksize:\n # we are at the end and need to strip the \"} characters\n outf.write(chunk[:offset_tail])\n break\n else:\n outf.write(chunk)\n return outpath\n\n def download_and_clean_lineitems(self, outpath, filter_type, filter_ids=None):\n tmp_outpath = '/tmp/temp_{}_raw_lineitems.json'.format(random.randint(0,999999))\n self._download_lineitems(tmp_outpath, filter_type, filter_ids)\n real_outpath = self._clean_lineitems_response_via_ijson(tmp_outpath, outpath)\n return real_outpath\n\n\ndef validate_extractor_params(params):\n schema = vp.Schema(\n {\n \"extract\": {\n \"lineItems\": {\n \"filterType\": vp.Any(\"ADVERTISER_ID\", \"INSERTION_ORDER_ID\", \"LINE_ITEM_ID\"),\n vp.Optional(\"filterIds\"): [vp.Coerce(int)]\n }\n }\n }\n )\n return schema(params)\n\n\ndef main(datadir, credentials, params):\n params_cleaned = validate_extractor_params(params)\n ex = DBMExtractor(**credentials)\n outpath = Path(datadir) / 'out/tables/lineitems_export.csv'\n config_lineitems = params_cleaned['lineItems']\n ex.download_and_clean_lineitems(outpath,\n config_lineitems['filterType'],\n config_lineitems.get('filterIds'))\n\n\n","sub_path":"wrdbm/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"97125268","text":"#\n# This script will determine the optimal cat costume sticker\n# and quantify its effectiveness for different sizes\n#\n\nimport os\nimport sys\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\" # disable GPU\nimport random\nimport matplotlib.pyplot as plt\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.models import load_model\nfrom keras.datasets import cifar10\nimport numpy as np\n\nrandom.seed(1)\n\n\nclass_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nnum_classes = len(class_names)\ncat_idx = class_names.index('cat')\n\n\n# plotting helper function\ndef plot(img,label) :\n plt.imshow(img)\n plt.title(label)\n plt.show()\n\n# extracts a rectangle from the essence of cat\ndef make_sticker (sticker_stats) :\n [ulx,uly,h,w] = sticker_stats\n x = np.copy(cat_img[uly:uly+h, ulx:ulx+w, :])\n return x\n\n# applies sticker to the center of an image\ndef sticker_image (input_img, sticker) :\n sticker_shape = sticker.shape\n img_shape = input_img.shape\n ulx = (img_shape[1] - sticker_shape[1]) // 2 # centering \n uly = (img_shape[0] - sticker_shape[0]) // 2 # centering\n input_img[uly:uly+sticker_shape[0],ulx:ulx+sticker_shape[1],:] = sticker\n return input_img\n\n\n\n############################################################################################################################################################\n############################################################################################################################################################\n############################################################################################################################################################\n\n\n# load saved model from memory\nmodel = load_model('trained_models/cifar10_detector_model.h5')\n\n\n# load GAN model to generate essensce of cat\ngmodel = load_model('trained_models/cat_generator.hd5')\nnoise = np.random.normal(0, 1, (1, 100))\n\n\n# generate cat image\ncat_img = gmodel.predict(noise)[0]\nif (1) : # make it look more washed out like the dataset images\n cat_img = cat_img * 0.5 # reduce contrast\n cat_img += 0.5 # increase brightness\nplot(cat_img,'essence of cat to be used as a cat costume')\n\n\n# Load the CIFAR10 data.\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nx_test = x_test.astype('float32') / 255 # convert to float\nimages = len(x_test)\nx = np.copy(x_test[0:images])\ny = y_test[0:images]\n\n# pare down test images to only things the detector thought were non-cats, and therefore in need of a costume\ny_pred = model.predict(x, verbose=1)\nnon_cat_idx = []\nfor i in range(images) :\n c = np.argmax(y_pred[i,:])\n if (not c==cat_idx) :\n non_cat_idx.append(i)\n\nx_non_cat_test = x_test[non_cat_idx]\ny_non_cat_test = y_test[non_cat_idx]\ny = y_non_cat_test\nimages = len(x_non_cat_test)\n\n\n# this has already been swept over the entire range\n# for quicker repetition, the sweep is constrained to a region \n# alread demonstrated to be more effective\nulx_range = range(21,29)\nuly_range = range(3,8)\nwh_range = range(3,11)\n\nfor wh in wh_range :\n best_cat_count = 0\n for ulx in ulx_range :\n for uly in uly_range :\n x = np.copy(x_non_cat_test)\n # create stickered images\n sticker = make_sticker([ulx,uly,wh,wh])\n for i in range(images) :\n x[i] = sticker_image(x[i],sticker)\n \n # run classifier with \n y_pred = model.predict(x, verbose=1)\n\n cat_count = 0\n for i in range(images) :\n c = np.argmax(y_pred[i,:])\n if (c==cat_idx) : \n cat_count = cat_count + 1\n #if ((not [i][0] == c) and (y_pred[i,c]>0.95)): plot(x[i],\"image {:d} {:s} wears the cat costume with probability {:0.3f})\".format(i, class_names[y[i][0]], y_pred[i,c], ))\n #else : plot(x[i],\"image {:d} still not a cat, instead {:s} with probability {:0.3f} (supposed to be {:s})\".format(i, class_names[c], y_pred[i,c], class_names[y[i][0]]))\n \n if (cat_count > best_cat_count) : \n best_cat_count = cat_count\n best_sticker = [ulx,uly,wh,wh]\n\n print(\"{:0.3f} cat factor for sticker {:d}x{:d} from [{:d},{:d}]\".format(cat_count/images,wh,wh,uly,ulx))\n\n print(\"\\n\\nbest cat factor was {:0.3f} for sticker\".format(best_cat_count/images),best_sticker)\n plot(make_sticker(best_sticker),\"best {:d}x{:d} cat costume ({:0.3f} effective)\".format(wh,wh,best_cat_count/images))\n\n # debug printout to see how well it worked\n if (0) :\n # re-run best sticker to see where it worked the \n x = np.copy(x_non_cat_test)\n # create stickered images\n sticker = make_sticker(best_sticker)\n for i in range(images) :\n x[i] = sticker_image(x[i],sticker)\n \n # run classifier with \n y_pred = model.predict(x, verbose=1)\n\n for i in range(images) :\n c = np.argmax(y_pred[i,:])\n if (c==cat_idx and y_pred[i,c]>0.8 and (y[i][0]<2 or y[i][0]>7)) : \n plot(x[i],\"image {:d} {:s} wears the cat costume with probability {:0.3f})\".format(i, class_names[y[i][0]], y_pred[i,c] ))\n #else : plot(x[i],\"image {:d} still not a cat, instead {:s} with probability {:0.3f} (supposed to be {:s})\".format(i, class_names[c], y_pred[i,c], class_names[y[i][0]]))\n\n\n\n","sub_path":"cat_costume_demo.py","file_name":"cat_costume_demo.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"231271704","text":"from flask import Blueprint, Flask, jsonify, request\nimport json\nimport pymongo\nimport os\nfrom pprint import pprint\n\napp = Flask(__name__)\n\nconnection = pymongo.MongoClient(\"localhost\", 27017)\nconnection.drop_database('medi')\n\ndb = connection[\"medi\"]\n\nambulance_main_column = db[\"ambulance_main\"]\ndiagnosis_main_column = db[\"diagnosis_main\"]\nhospital_main_column = db[\"hospital_main\"]\ndoctors_main_column = db[\"doctors_main\"]\n\nambulance_detail_column = db[\"ambulance_detail\"]\ndiagnosis_detail_column = db[\"diagnosis_detail\"]\nhospital_detail_column = db[\"hospital_detail\"]\ndoctors_detail_column = db[\"doctors_detail\"]\n\ndir = os.path.dirname(os.path.realpath(__file__)).replace('\\\\', '/') + '/'\n\n# main\nwith open(dir + './main_data/ambul_medic.json') as file:\n json_string = file.read() \n ambulance_main = json.loads(json_string)\n ambulance_main_data = ambulance_main_column.insert_many(ambulance_main)\nwith open(dir + './main_data/diagnosis.json') as file:\n json_string = file.read() \n diagnosis_main = json.loads(json_string)\n diagnosis_main_data = diagnosis_main_column.insert_many(diagnosis_main)\nwith open(dir + './main_data/hospital.json') as file:\n json_string = file.read() \n hospital_main = json.loads(json_string)\n hospital_main_data = hospital_main_column.insert_many(hospital_main)\nwith open(dir + './main_data/doctor.json') as file:\n json_string = file.read() \n doctors_main = json.loads(json_string)\n doctors_main_data = doctors_main_column.insert_many(doctors_main)\n\n# detail\nwith open(dir + './detail_data/ambul_medic_detail.json') as file:\n json_string = file.read() \n ambulance_detail = json.loads(json_string)\n ambulance_detail_data = ambulance_detail_column.insert_many(ambulance_detail)\nwith open(dir + './detail_data/diagnosis_detail.json') as file:\n json_string = file.read() \n diagnosis_detail = json.loads(json_string)\n diagnosis_detail_data = diagnosis_detail_column.insert_many(diagnosis_detail)\nwith open(dir + './detail_data/hospital.json') as file:\n json_string = file.read() \n hospital_detail = json.loads(json_string)\n hospital_detail_data = hospital_detail_column.insert_many(hospital_detail)\nwith open(dir + './detail_data/num_of_doctors_for_detail_page.json') as file:\n json_string = file.read() \n doctors_detail = json.loads(json_string)\n doctors_detail_data = doctors_detail_column.insert_many(doctors_detail)\n\n\n@app.route('/', methods = ['GET', 'POST'])\ndef main():\n return \"main\"\n\n# 의사 메인\n@app.route('/doctor', methods = ['GET', 'POST'])\ndef doctor_info():\n temp = []\n for doc in doctors_main_column.find({}, {'_id': False}):\n temp.append(doc)\n return jsonify(temp)\n\n# 병원 메인\n@app.route('/hospital', methods = ['GET', 'POST'])\ndef hospital_info():\n temp = []\n for doc in hospital_main_column.find({}, {'_id': False}):\n temp.append(doc)\n return jsonify(temp)\n\n# 응급차 메인\n@app.route('/ambul-medic', methods = ['GET', 'POST'])\ndef ambulance_info():\n temp = []\n for doc in ambulance_main_column.find({}, {'_id': False}):\n temp.append(doc)\n return jsonify(temp)\n\n# 진료 메인\n@app.route('/diagnosis', methods = ['GET', 'POST'])\ndef diagnosis_info():\n temp = []\n for doc in diagnosis_main_column.find({}, {'_id': False}):\n temp.append(doc)\n return jsonify(temp)\n\n# 상세 페이지 전체\n@app.route('/detail', methods = ['GET', 'POST'])\ndef doctor_detail():\n detail, doctor_list, hospital_list, ambulance_list, diagnosis_list = [], [], [], [], []\n for doc in doctors_detail_column.find({}, {'_id': False}):\n doctor_list.append(doc)\n for doc in hospital_detail_column.find({}, {'_id': False}):\n hospital_list.append(doc)\n for doc in ambulance_detail_column.find({}, {'_id': False}):\n ambulance_list.append(doc)\n for doc in diagnosis_detail_column.find({}, {'_id': False}):\n diagnosis_list.append(doc)\n detail.append(doctor_list)\n detail.append(hospital_list)\n detail.append(ambulance_list)\n detail.append(diagnosis_list)\n # print(detail)\n return jsonify(detail)\n\nif __name__ == \"__main__\":\n app.run(\"0.0.0.0\", port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"559300023","text":"from __main__ import *\n\nfor port,db in config.run_server.items():\n\n root = resource.QueryParser(db)\n\n root.putChild('static', static.File(config.static_dir))\n\n #\n # favicon.ico\n #\n favicon = static.File(os.path.join(config.static_dir, 'images/favicon.ico'),\n defaultType='image/vnd.microsoft.icon')\n root.putChild('favicon.ico', favicon)\n\n site = server.Site(root)\n\n site.displayTracebacks = config.display_tracebacks\n\n application = service.Application('dbwfserver')\n\n sc = service.IServiceCollection(application)\n\n sc.addService(internet.TCPServer(int(port), site))\n","sub_path":"bin/export/dbwfserver/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389473430","text":"# -*- coding: utf-8 -*-\n# @Author: Puffrora\n# @Date: 2019-10-13 11:18:12\n# @Last Modified by: Puffrora\n# @Last Modified time: 2019-10-13 11:25:42\n\n\nclass Solution:\n\tdef hasGroupsSizeX(self, deck):\n\n\t\t# 最大公约数\n\t\tdef gcd(x, y):\n\t\t\tif x == 0:\n\t\t\t\treturn y\n\t\t\telse:\n\t\t\t\treturn gcd(y%x, x)\n\n\t\tdic = {}\n\t\tfor i in deck:\n\t\t\tdic[i] = dic.get(i, 0) + 1\n\n\t\tres = -1\n\t\tfor key,val in dic.items():\n\t\t\tif res < 0:\n\t\t\t\tres = val\n\t\t\telse:\n\t\t\t\tres = gcd(res, val)\n\t\tif res >= 2:\n\t\t\treturn True\n\t\treturn False\n","sub_path":"Leetcode/leetcode914 卡牌分组.py","file_name":"leetcode914 卡牌分组.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73591487","text":"#\n# Open-BLDC pysim - Open BrushLess DC Motor Controller python simulator\n# Copyright (C) 2011 by Antoine Drouin \n# Copyright (C) 2011 by Piotr Esden-Tempski \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\nimport numpy as np\nimport dyn_model as dm\nimport misc_utils as mu\n\ndef read_csv(filename):\n my_records = np.recfromcsv(filename)\n Y = np.zeros((my_records.time.size, dm.ov_size))\n Y[:,dm.ov_iu] = my_records.ia\n Y[:,dm.ov_iv] = my_records.ib\n Y[:,dm.ov_iw] = my_records.ic\n Y[:,dm.ov_vu] = my_records.vag\n Y[:,dm.ov_vv] = my_records.vbg\n Y[:,dm.ov_vw] = my_records.vcg\n Y[:,dm.ov_omega] = mu.radps_of_rpm(my_records.nm)\n# import code; code.interact(local=locals())\n return my_records.time, Y\n","sub_path":"my_io.py","file_name":"my_io.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6274401","text":"\nimport cv2\nimport os\nimport sys\nimport time\nimport numpy as np\nimport skimage\n\n\n_GRAY = (218, 227, 218)\n\ndef vis_bbox(img, bbox, color=(0,255,0), thick=2):\n \"\"\"Visualizes a bounding box.\"\"\"\n img = skimage.img_as_ubyte(img)\n (x0, y0, x1, y1) = bbox\n x1, y1 = int(x1), int(y1)\n x0, y0 = int(x0), int(y0)\n cv2.rectangle(img, (x0, y0), (x1, y1), color, thickness=thick)\n return img\n\ndef vis_class(img, pos, class_str, color=(0, 255, 0), font_scale=1, thickness=2):\n \"\"\"Visualizes the class.\"\"\"\n img = skimage.img_as_ubyte(img)\n x0, y0 = int(pos[0]), int(pos[1])\n # Compute text size.\n txt = class_str\n font = cv2.FONT_HERSHEY_SIMPLEX\n ((txt_w, txt_h), _) = cv2.getTextSize(txt, font, font_scale, 5)\n # Place text background.\n back_tl = x0, y0 - int(1.3 * txt_h)\n back_br = x0 + txt_w, y0\n\n cv2.rectangle(img, back_tl, back_br, color, thickness)\n # Show text.\n txt_tl = x0, y0 - int(0.3 * txt_h)\n cv2.putText(img, txt, txt_tl, font, font_scale,\n color, lineType=cv2.LINE_AA, thickness=thickness)\n return img\n\ndef vis_box_class(img, bbox, class_str, color=(0, 255, 0), thick=0.5):\n img = vis_bbox(img, bbox, color, thick=thick)\n img = vis_class(img, bbox, class_str, color, thickness=thick)\n\n return img","sub_path":"demo/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"181005177","text":"import tensorflow\nimport numpy\nfrom __Base.BaseClass import NeuralNetwork_Base\nfrom __Base.Shuffle import Shuffle_Two\nfrom tensorflow.contrib import rnn\nfrom tensorflow.contrib import seq2seq\nfrom tensorflow.python.layers.core import Dense\n\n\nclass AutoEncoder(NeuralNetwork_Base):\n def __init__(self, data, seq, weight=10, attention=None, attentionName=None, attentionScope=None, batchSize=32,\n maxLen=1000, rnnLayers=2, hiddenNodules=128, learningRate=1E-3, startFlag=True, graphRevealFlag=True,\n graphPath='logs/', occupyRate=-1):\n self.treatData = data\n self.treatSeq = seq\n self.weight = weight\n\n self.attention = attention\n self.attentionName = attentionName\n self.attentionScope = attentionScope\n\n self.maxLen = maxLen\n self.rnnLayers = rnnLayers\n self.hiddenNodules = hiddenNodules\n self.featureShape = numpy.shape(data[0])[1]\n # print(self.featureShape)\n\n super(AutoEncoder, self).__init__(trainData=None, trainLabel=None, batchSize=batchSize,\n learningRate=learningRate, startFlag=startFlag,\n graphRevealFlag=graphRevealFlag, graphPath=graphPath, occupyRate=occupyRate)\n\n def BuildNetwork(self, learningRate):\n self.dataInput = tensorflow.placeholder(dtype=tensorflow.float32, shape=[None, None, self.featureShape],\n name='DataInput')\n self.seqInput = tensorflow.placeholder(dtype=tensorflow.int32, shape=[None], name='SeqInput')\n\n #############################################################################\n # Batch Parameters\n #############################################################################\n\n self.parameters['BatchSize'], self.parameters['TimeStep'], _ = tensorflow.unstack(\n tensorflow.shape(input=self.dataInput, name='DataShape'))\n\n ###################################################################################################\n # Encoder\n ###################################################################################################\n\n with tensorflow.variable_scope('Encoder_AE'):\n self.parameters['Encoder_Cell_Forward_AE'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules) for _ in range(self.rnnLayers)], state_is_tuple=True)\n self.parameters['Encoder_Cell_Backward_AE'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules) for _ in range(self.rnnLayers)], state_is_tuple=True)\n\n self.parameters['Encoder_Output_AE'], self.parameters['Encoder_FinalState_AE'] = \\\n tensorflow.nn.bidirectional_dynamic_rnn(\n cell_fw=self.parameters['Encoder_Cell_Forward_AE'],\n cell_bw=self.parameters['Encoder_Cell_Backward_AE'],\n inputs=self.dataInput, sequence_length=self.seqInput, dtype=tensorflow.float32)\n\n if self.attention is None:\n self.parameters['Decoder_InitalState_AE'] = []\n for index in range(self.rnnLayers):\n self.parameters['Encoder_Cell_Layer%d_AE' % index] = rnn.LSTMStateTuple(\n c=tensorflow.concat([self.parameters['Encoder_FinalState_AE'][index][0].c,\n self.parameters['Encoder_FinalState_AE'][index][1].c], axis=1),\n h=tensorflow.concat([self.parameters['Encoder_FinalState_AE'][index][0].h,\n self.parameters['Encoder_FinalState_AE'][index][1].h], axis=1))\n self.parameters['Decoder_InitalState_AE'].append(self.parameters['Encoder_Cell_Layer%d_AE' % index])\n self.parameters['Decoder_InitalState_AE'] = tuple(self.parameters['Decoder_InitalState_AE'])\n else:\n self.attentionList = self.attention(dataInput=self.parameters['Encoder_Output_AE'],\n scopeName=self.attentionName, hiddenNoduleNumber=2 * self.hiddenNodules,\n attentionScope=self.attentionScope, blstmFlag=True)\n self.parameters['Decoder_InitalState_AE'] = []\n for index in range(self.rnnLayers):\n self.parameters['Encoder_Cell_Layer%d_AE' % index] = rnn.LSTMStateTuple(\n c=self.attentionList['FinalResult'],\n h=tensorflow.concat(\n [self.parameters['Encoder_FinalState_AE'][index][0].h,\n self.parameters['Encoder_FinalState_AE'][index][1].h],\n axis=1))\n self.parameters['Decoder_InitalState_AE'].append(self.parameters['Encoder_Cell_Layer%d_AE' % index])\n self.parameters['Decoder_InitalState_AE'] = tuple(self.parameters['Decoder_InitalState_AE'])\n\n #############################################################################\n # Decoder Label Pretreatment\n #############################################################################\n\n self.parameters['Decoder_Helper_AE'] = seq2seq.TrainingHelper(\n inputs=self.dataInput, sequence_length=self.seqInput, name='Decoder_Helper_AE')\n with tensorflow.variable_scope('Decoder_AE'):\n self.parameters['Decoder_FC_AE'] = Dense(self.featureShape)\n self.parameters['Decoder_Cell_AE'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules * 2) for _ in range(self.rnnLayers)],\n state_is_tuple=True)\n\n self.parameters['Decoder_AE'] = seq2seq.BasicDecoder(\n cell=self.parameters['Decoder_Cell_AE'], helper=self.parameters['Decoder_Helper_AE'],\n initial_state=self.parameters['Decoder_InitalState_AE'], output_layer=self.parameters['Decoder_FC_AE'])\n\n self.parameters['Decoder_Logits_AE'], self.parameters['Decoder_FinalState_AE'], self.parameters[\n 'Decoder_FinalSeq_AE'] = seq2seq.dynamic_decode(decoder=self.parameters['Decoder_AE'])\n\n #############################################################################\n # Losses\n #############################################################################\n\n self.parameters['Loss_AE'] = tensorflow.losses.absolute_difference(\n labels=self.dataInput, predictions=self.parameters['Decoder_Logits_AE'][0], weights=self.weight)\n self.train = tensorflow.train.AdamOptimizer(learning_rate=learningRate).minimize(self.parameters['Loss_AE'])\n\n def Train(self, logname):\n data, seq = Shuffle_Two(data=self.treatData, label=self.treatSeq)\n # data, seq = self.treatData, self.treatSeq\n\n # for index in range(len(data)):\n # print(numpy.shape(data[index]), seq[index])\n\n with open(logname, 'w') as file:\n startPosition = 0\n totalLoss = 0.0\n while startPosition < numpy.shape(data)[0]:\n batchData, batchSeq = [], []\n\n maxSeq = min(numpy.max(seq[startPosition:startPosition + self.batchSize]), self.maxLen)\n for index in range(startPosition, min(startPosition + self.batchSize, numpy.shape(data)[0])):\n batchSeq.append(min(seq[index], self.maxLen))\n\n for index in range(startPosition, min(startPosition + self.batchSize, numpy.shape(data)[0])):\n if numpy.shape(data[index])[0] >= self.maxLen:\n currentData = data[index][0:self.maxLen]\n else:\n currentData = numpy.concatenate(\n [data[index],\n numpy.zeros([maxSeq - numpy.shape(data[index])[0], numpy.shape(data[index])[1]])],\n axis=0)\n # print(numpy.shape(currentData))\n batchData.append(currentData)\n\n # print(startPosition, numpy.shape(batchData), numpy.shape(batchSeq), maxSeq)\n # print(batchSeq, '\\n')\n\n loss, _ = self.session.run(fetches=[self.parameters['Loss_AE'], self.train],\n feed_dict={self.dataInput: batchData, self.seqInput: batchSeq})\n file.write(str(loss) + '\\n')\n totalLoss += loss\n print('\\rBatch %d/%d Loss = %f' % (startPosition, len(data), loss), end='')\n\n # exit()\n\n startPosition += self.batchSize\n return totalLoss\n","sub_path":"DepressionRecognition/Model/AutoEncoder.py","file_name":"AutoEncoder.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"33097583","text":"import unittest\nfrom Wangyunfei.shopping.test.test_homework.shopping import memberHelp\n\n\nclass TestmemberHelp(unittest.TestCase):\n def test_add_mem01(self):\n print('test_add_mem01')\n tel = '18812345665'\n act_disc = memberHelp.add_member_by_tel(tel)\n exp_disc = 1\n self.assertEqual(exp_disc, act_disc)\n def test_add_mem02(self):\n print('test_add_mem02')\n tel = '18812345671'\n act_disc = memberHelp.add_member_by_tel(tel)\n exp_disc = False\n self.assertEqual(exp_disc, act_disc)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"old/study/home/Wangyunfei/shopping/test/test_homework/test_add_member.py","file_name":"test_add_member.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"399077325","text":"# Test capabilities of the idea_chain.py file\nimport sys\nimport os\nsys.path.insert(0, os.getcwd() + \"/..\")\nfrom brain.idea_chain import IdeaChain\nfrom brain.idea import Idea\n\n# Create dummy ideas to add\ni1 = Idea(\"idea1\", temp=True)\ni2 = Idea(\"idea2\", temp=True)\ni3 = Idea(\"idea3\", temp=True)\ni4 = Idea(\"idea4\", temp=True)\n\n############# TEST ADDING ################\n# Add Ideas to the head of the list\nic = IdeaChain()\nic.add_to_head(i1)\nic.add_to_head(i2)\nic.add_to_head(i3)\nic.add_to_head(i4)\n# i4 - i3 - i2 - i1\nprint(ic)\n''':-\nName: idea4 | ID: idea4temp - Head\nName: idea3 | ID: idea3temp\nName: idea2 | ID: idea2temp\nName: idea1 | ID: idea1temp - Tail\n'''\n\n# Add ideas to the tail of the list\nic = IdeaChain()\nic.add_to_tail(i1)\nic.add_to_tail(i2)\nic.add_to_tail(i3)\nic.add_to_tail(i4)\n# i1 - i2 - i3 - i4\nprint(ic)\n''':-\nName: idea1 | ID: idea1temp - Head\nName: idea2 | ID: idea2temp\nName: idea3 | ID: idea3temp\nName: idea4 | ID: idea4temp - Tail\n'''\n\n# Add Ideas to the head and tail of the list\nic = IdeaChain()\nic.add_to_head(i1)\nic.add_to_tail(i2)\nic.add_to_head(i3)\nic.add_to_tail(i4)\n# i3 - i1 - i2 - i4\nprint(ic)\n''':-\nName: idea3 | ID: idea3temp - Head\nName: idea1 | ID: idea1temp\nName: idea2 | ID: idea2temp\nName: idea4 | ID: idea4temp - Tail\n'''","sub_path":"tests/idea_chain_add.py","file_name":"idea_chain_add.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"273334911","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0002_auto_20160107_2041'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RestKey',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('key', models.CharField(unique=True, max_length=4)),\n ('value', models.CharField(default=b'\\xd0\\x9d\\xd0\\xb5 \\xd0\\xb2\\xd1\\x8b\\xd0\\xb4\\xd0\\xb0\\xd0\\xbd', max_length=10)),\n ],\n ),\n ]\n","sub_path":"myblog/blog/migrations/0003_restkey.py","file_name":"0003_restkey.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"117674589","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom types import MethodType\n\n__author__ = 'zwk'\n\"\"\"\n@time: 2016/5/22 21:42\n@content:\n__slots__ :限定实例动态绑定的属性,但对继承的子类不起作用\n@property装饰器:可以将方法变成属性调用\n\"\"\"\n\n\nclass Animal(object):\n __slots__ = ('name', 'age')\n\n\nclass Screen(object):\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n if isinstance(value, int):\n self._width = value\n else:\n raise ValueError('width must be an integer!')\n\n @property\n def height(self):\n return self._height\n\n @height.setter\n def height(self, value):\n if isinstance(value, int):\n self._height = value\n else:\n raise ValueError('height must be an integer!')\n\n @property\n def resolution(self):\n return self._height * self._width\n\nif __name__ == '__main__':\n aa = Animal()\n aa.name = 'dog'\n aa.age = 11\n\n s = Screen()\n s.width = 1024\n s.height = 768\n print(s.resolution)","sub_path":"study_case/class_3.py","file_name":"class_3.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"468058220","text":"# Copyright 2017 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport inspect\nimport time\nimport unittest\n\nimport rclpy\nfrom rclpy.logging import LoggingSeverity\n\n\nclass TestLogging(unittest.TestCase):\n\n def test_severity_threshold(self):\n original_severity = rclpy.logging.get_severity_threshold()\n for severity in LoggingSeverity:\n rclpy.logging.set_severity_threshold(severity)\n self.assertEqual(severity, rclpy.logging.get_severity_threshold())\n rclpy.logging.set_severity_threshold(original_severity)\n\n def test_log_threshold(self):\n rclpy.logging.set_severity_threshold(LoggingSeverity.INFO)\n\n # Logging below threshold not expected to be logged\n self.assertFalse(rclpy.logging.logdebug('message_debug'))\n\n # Logging at or above threshold expected to be logged\n self.assertTrue(rclpy.logging.loginfo('message_info'))\n self.assertTrue(rclpy.logging.logwarn('message_warn'))\n self.assertTrue(rclpy.logging.logerr('message_err'))\n self.assertTrue(rclpy.logging.logfatal('message_fatal'))\n\n def test_log_once(self):\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n once=True,\n ))\n self.assertEqual(message_was_logged, [True] + [False] * 4)\n\n # If the argument is specified as false it shouldn't impact the logging.\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message2_' + inspect.stack()[0][3] + '_false_' + str(i),\n LoggingSeverity.INFO,\n once=False,\n ))\n self.assertEqual(message_was_logged, [True] * 5)\n\n def test_log_throttle(self):\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n throttle_duration_sec=1,\n throttle_time_source_type='RCUTILS_STEADY_TIME',\n ))\n time.sleep(0.3)\n self.assertEqual(message_was_logged, [True] + [False] * 3 + [True])\n\n def test_log_skip_first(self):\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n skip_first=True,\n ))\n self.assertEqual(message_was_logged, [False] + [True] * 4)\n\n def test_log_skip_first_throttle(self):\n # Because of the ordering of supported_filters, first the throttle condition will be\n # evaluated/updated, then the skip_first condition\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n skip_first=True,\n throttle_duration_sec=1,\n throttle_time_source_type='RCUTILS_STEADY_TIME',\n ))\n time.sleep(0.3)\n self.assertEqual(message_was_logged, [False] * 4 + [True])\n\n def test_log_skip_first_once(self):\n # Because of the ordering of supported_filters, first the skip_first condition will be\n # evaluated/updated, then the once condition\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n once=True,\n skip_first=True,\n ))\n time.sleep(0.3)\n self.assertEqual(message_was_logged, [False, True] + [False] * 3)\n\n def test_log_arguments(self):\n # Check half-specified filter not allowed if a required parameter is missing\n with self.assertRaisesRegex(TypeError, 'required parameter .* not specified'):\n rclpy.logging.log(\n 'message',\n LoggingSeverity.INFO,\n throttle_time_source_type='RCUTILS_STEADY_TIME',\n )\n\n # Check half-specified filter is allowed if an optional parameter is missing\n rclpy.logging.log(\n 'message',\n LoggingSeverity.INFO,\n throttle_duration_sec=0.1,\n )\n\n # Check unused kwarg is not allowed\n with self.assertRaisesRegex(TypeError, 'parameter .* is not one of the recognized'):\n rclpy.logging.log(\n 'message',\n LoggingSeverity.INFO,\n name='my_name',\n skip_first=True,\n unused_kwarg='unused_kwarg',\n )\n\n def test_log_parameters_changing(self):\n # Check changing log call parameters is not allowed\n with self.assertRaisesRegex(ValueError, 'parameters cannot be changed between'):\n # Start at 1 because a throttle_duration_sec of 0 causes the filter to be ignored.\n for i in range(1, 3):\n rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n throttle_duration_sec=i,\n )\n\n with self.assertRaisesRegex(ValueError, 'name cannot be changed between'):\n for i in range(2):\n rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n name='name_' + str(i),\n )\n\n with self.assertRaisesRegex(ValueError, 'severity cannot be changed between'):\n for severity in LoggingSeverity:\n rclpy.logging.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(severity),\n severity,\n )\n\n def test_named_logger(self):\n my_logger = rclpy.logging.get_named_logger('my_logger')\n\n rclpy.logging.set_severity_threshold(LoggingSeverity.INFO)\n # Test convenience functions\n\n # Logging below threshold not expected to be logged\n self.assertFalse(my_logger.debug('message_debug'))\n\n # Logging at or above threshold expected to be logged\n self.assertTrue(my_logger.warn('message_warn'))\n self.assertTrue(my_logger.error('message_err'))\n self.assertTrue(my_logger.fatal('message_fatal'))\n\n # Check that specifying a different severity isn't allowed\n with self.assertRaisesRegex(TypeError, \"got multiple values for argument 'severity'\"):\n my_logger.fatal(\n 'message_fatal',\n severity=LoggingSeverity.DEBUG)\n\n # Check that this logger's context is independent of the root logger's context\n loggers = [my_logger, rclpy.logging.root_logger]\n for logger in loggers:\n message_was_logged = []\n for i in range(5):\n message_was_logged.append(logger.log(\n 'message_' + inspect.stack()[0][3] + '_' + str(i),\n LoggingSeverity.INFO,\n once=True,\n ))\n self.assertEqual(message_was_logged, [True] + [False] * 4)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"rclpy/test/test_logging.py","file_name":"test_logging.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"221459593","text":"import csv\nimport json\n\nimport helper\n\ndef read_airlines(filename='airlines.dat'):\n airlines = {} # Map from code -> name\n with open(filename) as f:\n reader = csv.reader(f)\n for line in reader:\n airlines[line[4]] = line[1]\n return airlines\n\ndef read_airports(filename='airports.dat'):\n airports = {} # Map from code -> name\n with open(filename) as f:\n reader = csv.reader(f)\n for line in reader:\n airports[line[4]] = line[1]\n return airports\n\ndef read_routes(filename='routes.dat'):\n # Note: This could be a collections.defaultdict(list) instead, for elegance.\n routes = {} # Map from source -> list of dests\n with open(filename) as f:\n reader = csv.reader(f)\n for line in reader:\n source, dest = line[2], line[4]\n if source not in routes:\n routes[source] = []\n routes[source].append(dest)\n return routes\n\ndef find_paths(routes, source, dest, max_segments):\n # Run the BFS search\n frontier = {source}\n seen = {source: {(source, )}}\n for steps in range(max_segments):\n next_frontier = set()\n for airport in frontier:\n for target in routes.get(airport, ()):\n if target not in seen:\n next_frontier.add(target)\n seen[target] = set()\n for path in seen[airport]:\n if len(path) != steps + 1:\n continue\n seen[target].add(path + (target, ))\n frontier = next_frontier\n return seen[dest]\n\ndef rename_path(path, airports):\n return tuple(map(airports.get, path))\n\n\ndef main(source, dest, max_segments):\n airlines = read_airlines()\n airports = read_airports()\n routes = read_routes()\n\n paths = find_paths(routes, source, dest, max_segments)\n output = {} # Again, could use a collections.defaultdict(list) here.\n for path in paths:\n segments = len(path) - 1\n if segments not in output:\n output[segments] = []\n output[segments].append(rename_path(path, airports))\n\n with open(f\"{source}->{dest} (max {max_segments}).json\", 'w') as f:\n json.dump(output, f, indent=2, sort_keys=True)\n\n\nif __name__ == '__main__':\n parser = helper.build_parser()\n args = parser.parse_args()\n main(args.source, args.dest, args.max_segments)","sub_path":"exercise_csv_finding_routes/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"423487480","text":"import requests\nfrom bs4 import BeautifulSoup as bs\n\nfrom Utility import Minutes, Money, Files, Date\n\n\ndef main():\n # Making a GET request to wikipedia disney films movies\n r = requests.get(\n 'https://en.wikipedia.org/wiki/List_of_Walt_Disney_Pictures_films')\n soup = bs(r.content)\n movies = soup.select('.wikitable.sortable i a')\n\n print(\"Scraping is Done.\")\n\n mins = Minutes()\n money = Money()\n files = Files()\n d = Date()\n\n movie_info_list = scrap_wiki_disney(movies)\n\n files.save_data_json('DisneyMovies.json', movie_info_list)\n\n print(\"Cleaning Data....\")\n\n movie_info = files.load_data_json('DisneyMovies.json')\n\n for movie in movie_info:\n movie['Running time'] = mins.minutes_to_integer(\n movie.get('Running time', 'N/A'))\n\n for movie in movie_info:\n movie['Budget'] = money.money_conversion(movie.get('Budget', 'N/A'))\n movie['Box office'] = money.money_conversion(\n movie.get('Box office', 'N/A'))\n\n for movie in movie_info:\n movie['Release date'] = d.date_conversion(\n movie.get('Release date', 'N/A'))\n\n files.save_data_csv('DisneyMovies_cleaned_data.csv', movie_info)\n\n print(\"Cleaning Data is Done.\")\n print(\"The data has been convertd to CSV file.\")\n\n\ndef scrap_wiki_disney(movies):\n\n base_path = 'https://en.wikipedia.org/'\n movie_info_list = []\n\n for index, movie in enumerate(movies):\n try:\n relative_path = movie['href']\n full_path = base_path + relative_path\n title = movie['title']\n\n movie_info_list.append(get_info_box(full_path))\n\n except Exception as e:\n print(movie.get_text())\n print(e)\n\n return movie_info_list\n\n\ndef get_info_box(url):\n r = requests.get(url)\n soup = bs(r.content)\n info_box = soup.find(class_=\"infobox vevent\")\n info_rows = info_box.find_all(\"tr\")\n\n clean_tags(soup)\n\n movie_info = {}\n for index, row in enumerate(info_rows):\n if index == 0:\n movie_info['title'] = row.find(\"th\").get_text(\" \", strip=True)\n else:\n header = row.find('th')\n if header:\n content_key = row.find(\"th\").get_text(\" \", strip=True)\n content_value = get_content_value(row.find(\"td\"))\n movie_info[content_key] = content_value\n\n return movie_info\n\n\ndef clean_tags(soup):\n for tag in soup.find_all([\"sup\", \"span\"]):\n tag.decompose()\n\n\ndef get_content_value(row_data):\n if row_data.find('li'):\n return [i.get_text(\" \", strip=True).replace('\\xa0', ' ') for i in row_data.find_all('li')]\n elif row_data.find('br'):\n return [text for text in row_data.stripped_strings]\n else:\n return row_data.get_text(\" \", strip=True).replace('\\xa0', ' ')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ScrapingDisneyFilms.py","file_name":"ScrapingDisneyFilms.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"522041119","text":"import msprime\nimport time\nimport math\n\n#####################################################################\n# -- Simple simulation, no mutations --\n#####################################################################\n\n# Simulate 5 individuals with Ne = 1000\ntree_sequence = msprime.simulate(sample_size=6, Ne=1000)\ntree = tree_sequence.first()\nprint(tree.draw(format=\"unicode\"))\n\n#####################################################################\n# -- Add mutations --\n#####################################################################\n\n# Simulate\n# With recombination --> multiple trees, time it\nstartR = time.time()\ntree_sequenceR = msprime.simulate(sample_size=10, Ne=1000, length=10e8, mutation_rate=1e-8,\n recombination_rate=1e-8, random_seed = 65)\nendR = time.time()\nprint(endR - startR)\ntree_sequenceR.num_trees\n\n# Without recombination --> one tree, time it\nstart = time.time()\ntree_sequence = msprime.simulate(sample_size=10, Ne=1000, length=10e8, mutation_rate=1e-8,\n random_seed = 65)\nend = time.time()\nprint(end - start)\ntree_sequence.num_trees\ntype(tree_sequence)\n\n# Obtain the first tree\ntree = tree_sequenceR.first()\nhelp(tree)\n# Draw the tree\nprint(tree.draw(format=\"unicode\"))\n# print(tree.__doc__) = help(tree)\ntype(tree)\n\ntree = tree_sequence.first()\n# Obtain number of variants\nhelp(site)\nlen([x.site.id for x in tree_sequence.variants()])\n# Obtain number of sites\ntree_sequence.num_sites\n# Obtain number of mutations\ntree_sequence.num_mutations\n# Mutations at the first site\n[x.mutations for x in tree.sites()][0]\n[x.position for x in tree.sites()][0]\n[x.mutations for x in tree.sites()][26]\n[x.mutations for x in tree.sites()][50000]\n# Obtain number of individuals\ntree_sequence.num_individuals\n\n# TABLES (TableCollection)\nprint(tree_sequence.tables.nodes)\nprint(tree_sequence.tables.sites)\nprint(tree_sequence.tables.mutations)\nprint(tree_sequence.tables.individuals)\nprint(tree_sequence.tables.edges)\nprint(tree_sequence.tables.populations)\nprint(tree_sequence.tables.provenances)\n\n# Get variants\n# See the first variant\n[(variant.site.id, variant.alleles, variant.genotypes) for variant in tree_sequence.variants()][0]\n#\ntree = tree_sequence.first()\nsite = tree.sites()\nfor site in tree.sites():\n for mutation in site.mutations:\n print(\"Site: {}, mutation: {}.\".format(site.position, mutation.node))\n\n# Get genotypes\ngeno = tree_sequence.genotype_matrix()\ngeno.shape\n\n\n#####################################################################\n# -- Add demographic event --\n#####################################################################\nbottle_neck1 = 1000\nbottle_neck2 = 2000\ngeneration_time = 25\ngTime = bottle_neck1 / generation_time\ngTime1 = bottle_neck2 / generation_time\n\n############# Population configuration - NO GROWTH RATE ###################\n# This is optional when you have only one population\npopulation_configuration = [msprime.PopulationConfiguration(sample_size = 1000,\n initial_size = 20000)]\n\n#Population expansion\n# First a \"smaller\" time!!!\ndemographic_events = [\n msprime.PopulationParametersChange(time = gTime, initial_size = 1000),\n msprime.PopulationParametersChange(time = gTime1, initial_size = 100)\n]\n\nhistory = msprime.DemographyDebugger(population_configurations = population_configuration,\n demographic_events = demographic_events, model = \"dtwf\")\nhistory.print_history()\nhistory.coalescence_rate_trajectory()\nhistory.epoch_times\nhistory.population_size_history\nhistory.population_size_trajectory(steps = [0, 1, 10, 40, 41, 42, 43, 44, 100, 200, 1000, 10000])\n\n\n############# Population configuration - GROWTH RATE ###################\n# current size = 1,000;\n# bottle neck 100 years ago, size = 100\n# before bottle neck size = 10,000 (constant)\nsample_size = 10e6\ninitial_size = 1000\nback100_size = 100\nhistorical_size = 10000\ngrowth_rate = math.log( initial_size / back100_size) /100\n#back100 = math.exp(growth_rate * 100) / initial_size\nbottle_neck = 2500\ngeneration_time = 25\ngTime = bottle_neck / generation_time\n\npopulation_configuration = [msprime.PopulationConfiguration(sample_size = sample_size,\n initial_size = initial_size,\n growth_rate = growth_rate)]\ndemographic_events = [\n msprime.PopulationParametersChange(time = gTime, initial_size = historical_size, growth_rate = 0)\n]\n\nhistory = msprime.DemographyDebugger(population_configurations = population_configuration,\n demographic_events = demographic_events, model = \"dtwf\")\nhistory.print_history() ###???\nhistory.coalescence_rate_trajectory()\nhistory.epoch_times\nhistory.population_size_history\nhistory.population_size_trajectory(steps = [0, 1, 10, 40, 41, 42, 43, 44, 100, 200, 1000, 10000])\n\n\n############## Run simulation ##########################3\npop = msprime.simulate(length = 10e08, mutation_rate=1e-8, recombination_rate=1e-8, random_seed = 8465, Ne = 200,\n population_configurations = population_configuration, demographic_events = demographic_events)\npop.num_trees\npop.num_samples\npop.num_sites\npop.num_mutations","sub_path":"test_msprime_simulation.py","file_name":"test_msprime_simulation.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382101848","text":"#Counter - Dictionary subclass\r\nfrom collections import Counter\r\n\r\nl - [1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5]\r\n\r\nCounter(l)\r\n\r\ns = \"asdasdasdasdasdfg\"\r\nCounter(s)\r\n\r\ns = \"How many times does each word show up in this sentence word word show up up show\"\r\nwords = s.split()\r\n\r\nCounter(words)\r\n\r\nc = Counter(words)\r\nc.most_commmon(2)\r\n\r\n\r\nsum(c.values()) #total of all counts\r\nc.clear() #reset all counts\r\nlist(c) # list of unique elements\r\nset(c) # Convert to a set\r\ndict(c) # convert to a regular dictionary\r\nc.items() #convert to a list of (elem, cnt) pairs\r\nCounter(dict(list_of_pairs)) #convert from a list of (elem, cnt) pairs \r\nc.most_common()[:-n-1:-1] #n least common elements\r\nc += Counter() #remove zero and negative counts\r\n\r\nsum(c.values()) # total words in string\r\n","sub_path":"collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"474749282","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\nfrom mpl_toolkits.axes_grid1 import host_subplot\nimport mpl_toolkits.axisartist as AA\n\nabundance_list = [3.54e-3, 1.04e-3, 8.59e-3, 1.88e-3, 1.06e-3, 1.94e-3]\n\n\ndef enclosed_mass(dr, beta, rc, r_lim):\n n = dr/(rc**(3 * beta))\n\n def d_mass(r):\n return r**2 * (1 + (r / rc)**2)**(-3 * beta / 2)\n\n def d_mass_powerlaw(r):\n return r**2 * (r / rc)**(-3 * beta)\n\n mass, err = integrate.quad(d_mass, 0, r_lim)\n return mass * 4 * np.pi * n * 1e-2 * 3.086**3 * 1.67 / 1.989 * 1e6 * (1 + 0.386 + 0.3 * sum(abundance_list))\n\n\ndef disk_mass(n_disk, ZH, r_lim):\n RH = 3\n def density(r, mu):\n return np.exp(-r / RH) * np.exp(-abs(r * mu) / ZH)\n\n mass, err = integrate.dblquad(lambda r, mu: density(r, mu) * r**2, -1, 1, lambda r: 0, lambda r: r_lim)\n return mass * 2 * np.pi * n_disk * 1e-2 * 3.086**3 * 1.67 / 1.989 * 1e6 * (1 + 0.386 + 0.3 * sum(abundance_list))\n\n\ndef enclosed_mass_analytic(dr, beta, r_lim):\n abundance_list = [0.382, 3.54e-3, 1.04e-3, 8.59e-3, 1.88e-3, 1.06e-3, 1.94e-3]\n return dr * r_lim**(3 - 3 * beta) / (3 - 3 * beta) * 4 * np.pi * 1e-2 * 3.086**3 * 1.67 / 1.989 * 1e6 * (1 + 0.3 * sum(abundance_list))\n\n\ndef plot():\n matplotlib.pyplot.figure(figsize=(9, 5))\n ax = host_subplot(111, axes_class=AA.Axes)\n r_list = np.linspace(30, 300, 1000)\n\n m_7_s_list = [enclosed_mass(3.48, 0.50, 2.39, _) for _ in r_list]\n m_8_s_list = [enclosed_mass(3.55, 0.51, 2.38, _) for _ in r_list]\n m_7_r_list = [enclosed_mass(3.38, 0.50, 2.45, _) for _ in r_list]\n m_8_r_list = [enclosed_mass(3.39, 0.51, 2.43, _) for _ in r_list]\n\n\n ax.semilogy(r_list, m_7_s_list, lw=2, color=(42. / 255, 72. / 255, 121. / 255),\n label=r'$\\mathrm{O_{VII}}$ Stationary')\n ax.semilogy(r_list, m_8_s_list, lw=2, color=(234./255, 51./255, 35./255),\n label=r'$\\mathrm{O_{VIII}}$ Stationary')\n ax.semilogy(r_list, m_7_r_list, lw=2, linestyle='--', color=(42. / 255, 72. / 255, 121. / 255),\n label=r'$\\mathrm{O_{VII}}$ Rotating')\n ax.semilogy(r_list, m_8_r_list, lw=2, linestyle='--', color=(234./255, 51./255, 35./255),\n label=r'$\\mathrm{O_{VIII}}$ Rotating')\n\n axins = zoomed_inset_axes(ax, 6, loc=7)\n axins.semilogy(r_list, m_7_s_list, lw=2, color=(42. / 255, 72. / 255, 121. / 255))\n axins.semilogy(r_list, m_8_s_list, lw=2, color=(234./255, 51./255, 35./255))\n axins.semilogy(r_list, m_7_r_list, lw=2, linestyle='--', color=(42. / 255, 72. / 255, 121. / 255))\n axins.semilogy(r_list, m_8_r_list, lw=2, linestyle='--', color=(234./255, 51./255, 35./255))\n\n\n axins.set_xticks([])\n\n axins.set_yticks([3.3e10, 3.8e10])\n mark_inset(ax, axins, loc1=3, loc2=1, aa=True, fc=\"none\", ec=\"0.5\")\n\n\n legend = ax.legend(loc=2, fontsize=12)\n frame = legend.get_frame()\n frame.set_facecolor('none')\n\n ax.set_xlim(30, 300)\n ax.set_ylim(9e8, 8e10)\n axins.set_xlim(246, 254)\n axins.set_ylim(3.2e10, 3.99e10)\n ax.set_ylabel('Enclosed Mass' + r'$(M_{\\odot})$')\n ax.set_xlabel('Radius' + r'$(\\mathrm{kpc})$')\n\n ax2 = ax.twin()\n ax2.set_xticks([])\n ax2.set_ylim(9e8, 8e10)\n ax2.set_yticks([1e9, 7e9, 8e9, 9e9, 1e10, 2e10, 3e10, 4e10, 5e10, 6e10])\n ax2.set_yticklabels([])\n # matplotlib.pyplot.savefig('../publication/mass_distribution.eps', transparent=True)\n matplotlib.pyplot.show()\n\nif __name__ == '__main__':\n '''\n print(enclosed_mass(3.55, 0.51, 2.38, 250) * 1e-10)\n print(enclosed_mass(3.39, 0.51, 2.43, 250) * 1e-10)\n print(enclosed_mass(2.86, 0.51, 2.44, 250) * 1e-10)\n\n print(enclosed_mass(3.48, 0.50, 2.39, 250) * 1e-10)\n print(enclosed_mass(3.48, 0.50, 2.09, 250) * 1e-10)\n print(enclosed_mass(3.38, 0.50, 2.45, 250) * 1e-10)\n print(enclosed_mass(3.60, 0.51, 2.30, 250) * 1e-10)\n print(enclosed_mass(2.99, 0.52, 2.67, 250) * 1e-10)\n print(enclosed_mass(2.82, 0.51, 2.53, 250) * 1e-10)\n\n\n print(disk_mass(3.62, 0.97, 50) * 1e-8)\n print(disk_mass(3.99, 1.25, 50) * 1e-8)\n print(disk_mass(3.82, 1.34, 50) * 1e-8)\n '''\n\n # print enclosed_mass_analytic(3.0, 0.5, 250)\n # plot()\n\n","sub_path":"Visualization/enclose_mass.py","file_name":"enclose_mass.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"162681599","text":"# Приветствие с переключателем\nfrom tkinter import *\n\n# Константы текста\nAnswer = [\"Супер\", \"Хорошо\", \"Так себе\", \"Плохо\", \"Ужасно\", \"Не скажу\"]\nState = [\"Духовно\", \"Морально\", \"Физически\"]\nDiagnose = [\"Это здорово!\", \"Это радует!\", \"Все возможно.\", \\\n \"Это огорчает!\", \"Это плохо!\", \"Раз ты так думаешь ...\"]\n\n# Функция для события\ndef buttonClick() :\n Display.config(text=Diagnose[OptNum.get()])\ndef checkClick() :\n Text = \"Привет! \"\n for Nr in range (0,3) :\n if ChkNum[Nr].get() == 1 :\n Text = Text + State[Nr] + \" \";\n Window.title(Text)\n\n# Основная программа\nWindow = Tk()\nWindow.title(\"Привет!\")\nWindow.minsize(width=420, height=300)\nDisplay = Label(Window, text=\"Как это сделать?\")\nDisplay.place(x=50, y=10)\nLinks = Frame(Window, borderwidth=2, relief=\"sunken\")\nLinks.place(x=20, y=50, width=180, height=220)\nRechts = Frame(Window, borderwidth=2, relief=\"raised\")\nRechts.place(x=220, y=50, width=180, height=110)\n\n# Вспомогательные переменные\nChkNum = [0,0,0]\nOptNum = IntVar()\nOptNum.set(-1)\n\n# Опции\nOption = []\nfor Nr in range(0,6) :\n Option.append(Radiobutton(Links, variable=OptNum, value=Nr, text=Answer[Nr]))\n Option[Nr].config(command=buttonClick)\n Option[Nr].grid(row=Nr+1, column=0, sticky=\"w\")\n\n# Управление\nChoice = []\nfor Nr in range(0,3) :\n ChkNum[Nr] = IntVar()\n Choice.append(Checkbutton(Rechts, variable=ChkNum[Nr], text= State [Nr]))\n Choice[Nr].config(command=checkClick)\n Choice[Nr].grid(row=Nr+1, column=2, sticky=\"w\")\n\n# Цикл событий\nWindow.mainloop()\n\n","sub_path":"python_for_kids/book/Projects/hallo8.py","file_name":"hallo8.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"551543430","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass OrderExtInfo(object):\n\n def __init__(self):\n self._ext_key = None\n self._ext_value = None\n\n @property\n def ext_key(self):\n return self._ext_key\n\n @ext_key.setter\n def ext_key(self, value):\n self._ext_key = value\n @property\n def ext_value(self):\n return self._ext_value\n\n @ext_value.setter\n def ext_value(self, value):\n self._ext_value = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.ext_key:\n if hasattr(self.ext_key, 'to_alipay_dict'):\n params['ext_key'] = self.ext_key.to_alipay_dict()\n else:\n params['ext_key'] = self.ext_key\n if self.ext_value:\n if hasattr(self.ext_value, 'to_alipay_dict'):\n params['ext_value'] = self.ext_value.to_alipay_dict()\n else:\n params['ext_value'] = self.ext_value\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = OrderExtInfo()\n if 'ext_key' in d:\n o.ext_key = d['ext_key']\n if 'ext_value' in d:\n o.ext_value = d['ext_value']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/OrderExtInfo.py","file_name":"OrderExtInfo.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"597162832","text":"from django.shortcuts import render, HttpResponseRedirect, HttpResponse, reverse\nfrom django.contrib.auth.decorators import login_required\n\nfrom payments.models import Billing, History, Referral\nfrom settings.models import Settings\n\nimport json\n\n\n@login_required(login_url='/dashboard/login/')\ndef history(request):\n history = History.objects.filter(user_id=request.user.id)\n return render(request, 'payments/history.html', {'history': history})\n\n\n@login_required(login_url='/dashboard/login/')\ndef referral(request, uuid):\n billing = Billing.objects.get(referral_link_id=uuid)\n Referral.objects.create(user=billing.user)\n return HttpResponseRedirect(reverse('auth_clients:reg'))\n\n\n@login_required(login_url='/dashboard/login/')\ndef count_amc(request):\n eth = request.POST.get('eth')\n\n settings = Settings.objects.first()\n amc = float(eth) / float(settings.price_amc)\n response = json.dumps({'amc': amc, 'eth': eth})\n return HttpResponse(response)\n\n\n@login_required(login_url='/dashboard/login/')\ndef update(request):\n if request.POST and request.is_ajax():\n eth_wallet = request.POST.get('eth_wallet')\n print(eth_wallet)\n Billing.objects.filter(user_id=request.user.id).update(eth_wallet=eth_wallet)\n\n response = json.dumps({'message': 'ETH обновлен.'})\n return HttpResponse(response)\n return HttpResponseRedirect(reverse('dashboard:main'))\n","sub_path":"payments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39026139","text":"# -*- coding: utf-8 -*-\n\nfrom pandas_datareader import data\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\n# We would like all available data from 01/01/2000 until 12/31/2016.\nstart_date = '2018-01-01'\nend_date = '2019-01-01'\n\n# User pandas_reader.data.DataReader to load the desired data. As simple as that.\n#source = data.DataReader('005930.KS', 'yahoo', start_date, end_date)#삼성전자\n#source = data.DataReader('207940.KS', 'yahoo', start_date, end_date)#바이오로직스\nsource = data.DataReader('006400.KS', 'yahoo', start_date, end_date)#sdi\n\n#%%\nadj_data = source['Adj Close']\ndata = source['Close']\n\n#ret = data.pct_change(1)\nlog_ret = np.log(data/data.shift(1))\n\ndef min_max_norm(wdata):\n return ( wdata[-1] - wdata.min() )/ (wdata.max()-wdata.min())\ndef mean_std_norm(wdata):\n return ( wdata[-1] - wdata.mean() )/ wdata.std()\n\n\ndef svd_whiten(X):\n# a = source[X]\n U, s, Vt = np.linalg.svd(X, full_matrices=False)\n # U and Vt are the singular matrices, and s contains the singular values.\n # Since the rows of both U and Vt are orthonormal vectors, then U * Vt\n # will be white\n X_white = np.dot(U, Vt)\n return X_white[-1]\n\ndef rolling_whiten(src,window=20,min_periods=10):\n ret = []\n for i in range(src.__len__()):\n if i < min_periods-1:\n ret.append([0 for i in range(src.columns.__len__())])\n elif i 0 ] =100000\n#\n#action.plot()\n#\n#print('total benefit :',log_ret[action>0].sum())\n\n\n#log_ret.hist(bins=50)\n\n#data.rolling(30).mean().plot()\n#data.rolling(30).var().plot()\n\n\n\n\n\n\n\n","sub_path":"stock_lab.py","file_name":"stock_lab.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"92291243","text":"class TwoStacks:\n def __init__(self, size):\n self.size = size\n self.arr = [0]*size\n self.top1 = 0\n self.top2 = size-1\n\n\n def push1(self, val):\n if self.top1 <= self.top2:\n self.arr[self.top1] = val\n self.top1 += 1\n else:\n print(\"stack overflow\")\n\n def push2(self, val):\n if self.top1 <= self.top2:\n self.arr[self.top2] = val\n self.top2 -= 1\n else:\n print(\"stack overflow\")\n\n def pop1(self):\n if self.top1 > 0:\n self.top1 = self.top1 - 1\n val = self.arr[self.top1]\n self.arr[self.top1] = 0\n return val\n else:\n print(\"stack underflow\") \n\n def pop2(self):\n if self.top2 < self.size-1:\n self.top2 = self.top2 + 1\n val = self.arr[self.top2]\n self.arr[self.top2] = 0 \n return val\n else:\n print(\"stack underflow\") \n \n\nstack = TwoStacks(3)\nstack.push1(1)\nstack.push1(5)\nstack.push2(3)\nstack.push2(2)\nprint(stack.arr)","sub_path":"3. Data Structures/Stack Package/Problems/TwoStacks_OneList.py","file_name":"TwoStacks_OneList.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"299813021","text":"# hoppeLength\nimport random\nhoppeLength = int(input('ほっぺの長さ: '))\nsweat = input('汗をかきますか?(y or n): ')\nhoppe = ['', '']\nfor i in range(2):\n for j in range(hoppeLength):\n if random.randint(0, 1) == 1: hoppe[i] += ';'\n else: hoppe[i] += ' '\nprint('(っ' + hoppe[0] + '´ω`' + hoppe[1] + 'c)')\n","sub_path":"Others/hoppeLength.py","file_name":"hoppeLength.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"178542205","text":"# Copyright (c) 2019 Graphcore Ltd. 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\nimport random\nimport numpy as np\nimport torch\n\nimport popart\nimport onnx\n\nfrom tests.utils import run_py, copy_weights_to_torch, run_fwd_model, check_tensors, check_model\nfrom tests import torch_lamb\n\n\ndef get_mapping(config, init=None):\n if init is None:\n init = {}\n embedding_proj = {\n \"bert.embeddings.word_embeddings.weight\": \"Embedding/Embedding_Dict\",\n \"bert.embeddings.position_embeddings.weight\": \"Embedding/Positional_Dict\",\n \"bert.embeddings.token_type_embeddings.weight\": \"Embedding/Segment_Dict\",\n \"bert.embeddings.LayerNorm.weight\": \"Embedding/Gamma\",\n \"bert.embeddings.LayerNorm.bias\": \"Embedding/Beta\",\n }\n init.update(**embedding_proj)\n for i in range(config.num_layers):\n if config.split_qkv:\n init.update(**{\n f\"bert.encoder.layer.{i}.attention.self.query.weight\": f\"Layer{i}/Attention/Q\",\n f\"bert.encoder.layer.{i}.attention.self.key.weight\": f\"Layer{i}/Attention/K\",\n f\"bert.encoder.layer.{i}.attention.self.value.weight\": f\"Layer{i}/Attention/V\",\n })\n else:\n init.update(**{\n f\"bert.encoder.layer.{i}.attention.self.query.weight\": f\"Layer{i}/Attention/QKV\",\n f\"bert.encoder.layer.{i}.attention.self.key.weight\": f\"Layer{i}/Attention/QKV\",\n f\"bert.encoder.layer.{i}.attention.self.value.weight\": f\"Layer{i}/Attention/QKV\",\n })\n init.update(**{\n f\"bert.encoder.layer.{i}.attention.output.dense.weight\": f\"Layer{i}/Attention/Out\",\n f\"bert.encoder.layer.{i}.attention.output.LayerNorm.weight\": f\"Layer{i}/Attention/Gamma\",\n f\"bert.encoder.layer.{i}.attention.output.LayerNorm.bias\": f\"Layer{i}/Attention/Beta\",\n f\"bert.encoder.layer.{i}.intermediate.dense.weight\": f\"Layer{i}/FF/1/W\",\n f\"bert.encoder.layer.{i}.intermediate.dense.bias\": f\"Layer{i}/FF/1/B\",\n f\"bert.encoder.layer.{i}.output.dense.weight\": f\"Layer{i}/FF/2/W\",\n f\"bert.encoder.layer.{i}.output.dense.bias\": f\"Layer{i}/FF/2/B\",\n f\"bert.encoder.layer.{i}.output.LayerNorm.weight\": f\"Layer{i}/FF/Gamma\",\n f\"bert.encoder.layer.{i}.output.LayerNorm.bias\": f\"Layer{i}/FF/Beta\",\n })\n return init\n\n\ndef get_transform(config, init=None):\n if init is None:\n init = {}\n\n def q_transform(arr):\n return arr[:, 0:config.hidden_size].T\n\n def k_transform(arr):\n return arr[:, config.hidden_size:config.hidden_size * 2].T\n\n def v_transform(arr):\n return arr[:, config.hidden_size * 2:config.hidden_size * 3].T\n\n for i in range(config.num_layers):\n layer = {\n f\"bert.encoder.layer.{i}.attention.self.query.weight\": np.transpose if config.split_qkv else q_transform,\n f\"bert.encoder.layer.{i}.attention.self.key.weight\": np.transpose if config.split_qkv else k_transform,\n f\"bert.encoder.layer.{i}.attention.self.value.weight\": np.transpose if config.split_qkv else v_transform,\n f\"bert.encoder.layer.{i}.attention.output.dense.weight\": np.transpose,\n f\"bert.encoder.layer.{i}.intermediate.dense.weight\": np.transpose,\n f\"bert.encoder.layer.{i}.output.dense.weight\": np.transpose,\n }\n init.update(**layer)\n return init\n\n\ndef fwd_graph(popart_model, torch_model, mapping=None, transform=None, replication_factor=1, replicated_tensor_sharding = False):\n # ------------------- PopART --------------------\n config = popart_model.config\n builder = popart_model.builder\n\n sequence_info = popart.TensorInfo(\n \"UINT32\", [config.micro_batch_size * config.sequence_length])\n indices = builder.addInputTensor(sequence_info)\n positions = builder.addInputTensor(sequence_info)\n segments = builder.addInputTensor(sequence_info)\n data = {\n indices: np.random.randint(\n 0, config.vocab_length, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32),\n positions: np.random.randint(\n 0, config.sequence_length, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32),\n segments: np.random.randint(\n 0, 2, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32)\n }\n\n output = popart_model.build_graph(indices, positions, segments)\n ipus = popart_model.total_ipus\n\n proto = builder.getModelProto()\n\n outputs, _ = run_py(proto,\n data,\n output,\n replication_factor=replication_factor,\n replicated_tensor_sharding=replicated_tensor_sharding,\n ipus=ipus)\n\n\n # ----------------- PopART -> PyTorch ----------------\n proto = onnx.load_model_from_string(proto)\n\n inputs = {\n \"input_ids\": data[indices].reshape(replication_factor * config.micro_batch_size,\n config.sequence_length).astype(np.int32),\n \"position_ids\": data[positions].reshape(replication_factor * config.micro_batch_size,\n config.sequence_length).astype(np.int32),\n \"token_type_ids\": data[segments].reshape(replication_factor * config.micro_batch_size,\n config.sequence_length).astype(np.int32)\n }\n\n torch_to_onnx = get_mapping(config, init=mapping)\n\n transform_weights = get_transform(config, init=transform)\n\n # ------------------- PyTorch -------------------------\n # Turn off dropout\n torch_model.eval()\n copy_weights_to_torch(torch_model, proto,\n torch_to_onnx, transform_weights)\n\n torch_outputs = run_fwd_model(inputs, torch_model)\n\n check_tensors(torch_outputs, outputs)\n\n\ndef bwd_graph(popart_model,\n torch_model,\n popart_loss_fn,\n torch_loss_fn,\n mapping=None,\n transform=None,\n replication_factor=1,\n replicated_tensor_sharding=False,\n opt_type=\"SGD\"):\n np.random.seed(1984)\n random.seed(1984)\n torch.manual_seed(1984)\n\n # ------------------- PopART --------------------\n config = popart_model.config\n builder = popart_model.builder\n\n sequence_info = popart.TensorInfo(\n \"UINT32\", [config.micro_batch_size * config.sequence_length])\n indices = builder.addInputTensor(sequence_info)\n positions = builder.addInputTensor(sequence_info)\n segments = builder.addInputTensor(sequence_info)\n data = {\n indices: np.random.randint(\n 0, config.vocab_length, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32),\n positions: np.random.randint(\n 0, config.sequence_length, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32),\n segments: np.random.randint(\n 0, 2, (replication_factor, config.micro_batch_size * config.sequence_length)).astype(np.uint32)\n }\n num_reps = 5\n output = popart_model.build_graph(indices, positions, segments)\n ipus = popart_model.total_ipus\n\n loss = popart_loss_fn(output)\n\n proto = builder.getModelProto()\n\n if opt_type == \"SGD\":\n optimizer = popart.ConstSGD(1e-3)\n elif opt_type == \"LAMB\":\n optMap = {\n \"defaultLearningRate\": (1e-3, True),\n \"defaultBeta1\": (0.9, True),\n \"defaultBeta2\": (0.999, True),\n \"defaultWeightDecay\": (0.0, True),\n \"maxWeightNorm\": (10.0, True),\n \"defaultEps\": (1e-8, True),\n \"lossScaling\": (1.0, True),\n }\n optimizer = popart.Adam(optMap,\n mode=popart.AdamMode.Lamb)\n elif opt_type == \"LAMB_NO_BIAS\":\n optMap = {\n \"defaultLearningRate\": (1, False),\n \"defaultBeta1\": (0, False),\n \"defaultBeta2\": (0, False),\n \"defaultWeightDecay\": (0.0, False),\n \"defaultEps\": (1e-8, False),\n \"lossScaling\": (1.0, False),\n }\n optimizer = popart.Adam(optMap,\n mode=popart.AdamMode.LambNoBias)\n else:\n raise ValueError(f\"Unknown opt_type={opt_type}\")\n\n\n outputs, post_proto = run_py(proto,\n data,\n output,\n loss=loss,\n optimizer=optimizer,\n replication_factor=replication_factor,\n replicated_tensor_sharding=replicated_tensor_sharding,\n ipus=ipus,\n num_reps=num_reps)\n\n # ----------------- PopART -> PyTorch ----------------\n proto = onnx.load_model_from_string(proto)\n\n inputs = {\n \"input_ids\": data[indices].reshape(replication_factor * config.micro_batch_size, config.sequence_length).astype(np.int32),\n \"position_ids\": data[positions].reshape(replication_factor * config.micro_batch_size, config.sequence_length).astype(np.int32),\n \"token_type_ids\": data[segments].reshape(replication_factor * config.micro_batch_size, config.sequence_length).astype(np.int32)\n }\n\n torch_to_onnx = get_mapping(config, init=mapping)\n\n transform_weights = get_transform(config, init=transform)\n\n # ------------------- PyTorch -------------------------\n # Turn off dropout\n torch_model.eval()\n\n copy_weights_to_torch(torch_model, proto,\n torch_to_onnx, transform_weights)\n\n if opt_type == \"SGD\":\n optim = torch.optim.SGD(torch_model.parameters(), 1e-3,\n weight_decay=0.0, momentum=0.0)\n elif opt_type == \"LAMB\":\n optim = torch_lamb.Lamb(torch_model.parameters(),\n lr=1e-3, weight_decay=0.0, biasCorrection=True)\n\n for _ in range(num_reps):\n torch_outputs = torch_model(\n **{k: torch.from_numpy(t).long() for k, t in inputs.items()})\n torch_loss = torch_loss_fn(torch_outputs)\n torch_loss.backward()\n optim.step()\n optim.zero_grad()\n\n check_tensors([output.detach().numpy()\n for output in torch_outputs], outputs, margin=1.5e-06)\n\n check_model(torch_model, post_proto,\n torch_to_onnx, transform_weights,\n margin=5e-5)\n","sub_path":"applications/popart/bert/tests/unit/pytorch/full_graph_utils.py","file_name":"full_graph_utils.py","file_ext":"py","file_size_in_byte":11113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540092406","text":"from peewee import *\nimport os\nfrom Animal import Animal\n\ndb = SqliteDatabase('animalia.db')\n\nclass Consulta(Model):\n data = CharField()\n servico = CharField()\n horario = CharField()\n animal = ForeignKeyField(Animal)\n confirma = CharField()\n myID = CharField()\n class Meta:\n database = db\n def __str__ (self):\n return self.servico+\" em \"+self.data+\": \"+self.horario+\" confirmado: \"+self.confirma+\\\n \" ID da consulta: \"+self.myID+\" | animal: \"+str(self.animal)\n\nif __name__ == '__main__':\n arq = 'animalia.db'\n if os.path.exists(arq):\n os.remove(arq)\n\n try:\n db.connect()\n db.create_tables([Animal,Consulta])\n except OperationalError as e:\n print(\"Erro ao criar tabelas: \"+str(e))\n\n print(\"TESTE ANIMAL\")\n a1 = Animal.create(nomeDono=\"Katia\", tipoAnimal=\"Cachorro\", raca=\"Dobermann\")\n print(a1)\n\n print(\"TESTE CONSULTA\")\n c1 = Consulta.create(data=\"23/09/2019\",servico=\"Aplicação Vacina\",horario=\"14:00\", animal=a1, confirma=\"Sim\", myID=\"00001\")\n\n c1 = Consulta.create(data=\"23/09/2019\",servico=\"Aplicação Vacina\",horario=\"15:00\", animal=a1, confirma=\"Sim\", myID=\"00002\")\n\n todos = Consulta.select ()\n for con in todos:\n print(con)\n\n","sub_path":"ClassesPython/Consulta.py","file_name":"Consulta.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"609228264","text":"#-*-coding: utf-8-*-\nfrom flask import render_template, request, redirect, url_for, flash\nfrom flask import session, jsonify\nfrom datetime import timedelta\nfrom database import db_session\nfrom calculator import app\nfrom forms import DemountForm, TileForm\nfrom forms import LoginForm, RegisterForm\nimport methods\nfrom sqlalchemy.exc import IntegrityError\nfrom forms import WallForm, FloorForm\nfrom forms import DoorwayForm, CeilingForm\nfrom forms import ElectricForm, SanitaryForm, OtherForm\nfrom forms import AddRecordForm, EditForm, RateForm\n#3from flask.ext.login import LoginManager\n#from flask.ext.sqlalchemy import SQLAlchemy\nfrom flask_login import (LoginManager, login_required, login_user, \n current_user, logout_user, UserMixin)\nfrom database import User\n\n\nlogin_manager = LoginManager()\n'''The login manager contains the code that lets your application\n and Flask-Login work together, such as how to load a user from an ID, \n where to send users when they need to log in, and the like.\n\nOnce the actual application object has been created,\n you can configure it for login with:'''\n\nlogin_manager.init_app(app)\n\n@login_manager.user_loader\ndef load_user(userid):\n return User.get(userid)\n\n\ndef make_record(works):\n for work in works:\n try:\n present = session['data']\n if work not in present:\n session['data'].append(work)\n except:\n session['data'] = [0]\n\n\n@app.route('/home', methods=['GET', 'POST'])\ndef show_work():\n \n session.permanent = True\n app.permanent_session_lifetime = timedelta(minutes=30) \n \n demount = DemountForm(request.form)\n floor = FloorForm(request.form)\n wall = WallForm(request.form)\n doorway = DoorwayForm(request.form)\n ceiling = CeilingForm(request.form)\n tile = TileForm(request.form)\n electric = ElectricForm(request.form)\n sanitary = SanitaryForm(request.form)\n other = OtherForm(request.form)\n chosen = []\n try:\n for each in session['data']:\n chosen.append(each)\n except:\n session['data'] = [0]\n selected = methods.get_selected(chosen)\n return render_template('home.html', demount=demount, tile=tile, selected=selected,\n floor=floor, wall=wall, doorway=doorway, ceiling=ceiling,\n electric=electric, sanitary=sanitary, other=other)\n\n\n@app.route('/home/', methods=['GET', 'POST'])\ndef select_work(url):\n db = url\n if db:\n form = DemountForm(request.form)\n work = form.name.data\n make_record(work)\n return redirect(url_for('show_work'))\n\n\n@app.route('/get_result')\ndef get_result():\n ident = []\n amount = []\n ids = methods.get_all_ids()\n for each in ids:\n value = request.args.get(str(each), '0', type=str)\n if int(value) != 0:\n ident.append(each)\n amount.append(int(value))\n res = methods.calc(ident, amount)\n return jsonify(result=res)\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm(request.form)\n try:\n if (request.method == 'POST') and form.validate():\n methods.add_user(form.username.data, form.password.data)\n flash('You are registered.')\n flash('You can login now.')\n login = True\n return render_template('register.html', form = form, login = login)\n elif request.method == 'POST':\n flash(\"Fill all fields, please\")\n except IntegrityError:\n db_session.rollback()\n flash('That User name is not available')\n return render_template('register.html', form = form)\n return render_template('register.html', form = form)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm(request.form)\n if (request.method == 'POST') and form.validate():\n methods.check_if_admin(form.username.data, form.password.data)\n if session[\"permission\"] == \"authenticated\":\n session['data'] = [0]\n #session['present'] = 'present'\n session[\"logout\"] = False\n return redirect(url_for('show_work'))\n elif session[\"permission\"] == \"authorized\":\n session['data'] = [0]\n #session['present'] = 'present'\n session[\"logout\"] = False\n return redirect(url_for('show_work'))\n elif session[\"permission\"] == \"incorrect\":\n flash('Wrong password. Try again.')\n register = True\n return render_template('login.html', form = form, register = register)\n elif session[\"permission\"] == \"denied\":\n register = False\n flash('No such user. You need to register first')\n return render_template('login.html', form = form, register = register)\n elif request.method == 'POST' and form.username.data =='' or \\\n form.password.data == '':\n flash('Fill in all fields, please.')\n return render_template('login.html', form = form)\n else:\n return render_template('login.html', form = form)\n\n\n@app.route('/logout')\ndef logout():\n # remove the username from the session if it's there\n session.pop(\"username\")\n session.pop(\"permission\")\n session[\"data\"] = [0]\n return redirect(url_for('show_work'))\n\n\n@app.route('/clear')\ndef clear_selection():\n session['data'] = [0]\n return redirect(url_for('show_work'))\n\n\n@app.route('/delete/')\ndef delete(url):\n chosen = []\n for each in session['data']:\n chosen.append(each)\n chosen.remove(int(url))\n session['data'] = chosen\n return redirect(url_for('show_work'))\n\n\n@app.route('/database')\ndef show_database():\n add_form = AddRecordForm(request.form)\n database = methods.get_db()\n rate_form = RateForm(request.form)\n current_rate = methods.get_current_rate()\n return render_template('database.html', database = database, add_form = add_form, rate_form = rate_form, \n current_rate = current_rate)\n\n\n@app.route('/deletefromdb/')\ndef delete_record(url):\n methods.del_record(url)\n return redirect(url_for('show_database'))\n\n\n@app.route('/add_record', methods = ['GET', 'POST'])\ndef add_record():\n add_form = AddRecordForm(request.form)\n if request.method == 'POST' and request.form['btn'] == u'Добавить':\n flash('got post')\n methods.add_record(add_form.name.data, add_form.work.data, add_form.price.data, add_form.dimension.data)\n return redirect(url_for('show_database'))\n\n\n@app.route('/edit/', methods=['GET', 'POST'])\ndef edit(id):\n e_form = EditForm(request.form)\n e_form.id = int(id)\n edit = True\n add_form = AddRecordForm(request.form)\n rate_form = RateForm(request.form)\n database = methods.get_db()\n current_rate = methods.get_current_rate()\n return render_template('database.html', e_form=e_form, edit = edit, database = database, add_form = add_form,\n rate_form = rate_form, current_rate = current_rate)\n\n\n@app.route('/edit_name/', methods=['GET', 'POST'])\ndef edit_record(id):\n e_form = EditForm(request.form)\n add_form = AddRecordForm(request.form)\n database = methods.get_db()\n if request.form['btn'] == 'edit':\n id = id\n name = e_form.name.data\n price = e_form.price.data\n dimension = e_form.dimension.data\n methods.edit(id, name, price, dimension)\n return redirect(url_for('show_database'))\n return redirect(url_for('show_database'))\n\n\n@app.route('/change_rate', methods = ['GET', 'POST'])\ndef change_rate():\n rate_form = RateForm(request.form)\n if request.form['btn'] == u'Изменить':\n rate = rate_form.rate.data\n methods.new_rate(rate)\n return redirect(url_for('show_database'))\n return redirect(url_for('show_database'))\n","sub_path":"calculator/calculator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"248623591","text":"str=input(\"Enter the string or the sentence:\\n\")\ncounts=dict()\n\nfor i in str:\n counts[i]=counts.get(i,0)+1\n\nprint(\"The dictionary is:\\n\",counts)\n\nbigword=None\nbigcount=None\n\n\nfor word,count in counts.items():\n if bigcount is None or count> bigcount:\n bigword=word\n bigcount=count\n\nprint(bigword,bigcount)\n","sub_path":"dictmax.py","file_name":"dictmax.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"83794296","text":"#TCP_Message_manager.py\n\nimport time\n\n#TYPE: HNA-INDIVITUAL-TEST-CASE\n#MODIFICATION: This file does NOT need to change\n#DATE: 15-04-2020\n#TO-DOs: \n# -Handle the data if the message has arrived partially -->till now i havent have that problem but should be done in the future\n\"\"\"\nDESCRIPTION:\nThis file is used to read the data from the TCP buffer and split it according to the header of the message\n\nExample:\n original message= helloworld\n server sends = 0010helloworld --> header equals to the message lenght\n \nbased on the header it is possible to determine if the message has arrived complete or not\nand if more than one message has arrived to the buffer \n\"\"\" \n\n\n\nTCP_Buffer= \"0014Testing_Buffer0010my message0008the-rest0002hi0005heo\"\n\nheader_length=4\ninit_position=0\nTCP_messages=[ ]\n\n#get the splited data based in the incomming message\n#returns--> a list containing the separated messages as elements\n#if more than one element , it means that the socket received more than one message\n#Parameters:\n#TCP_Buffer: is the raw message we receive from the server (socket)\ndef getTCPdata(TCP_Buffer):\n\n while TCP_Buffer:\n char_to_read=int (TCP_Buffer[init_position: header_length])\n \n if len(TCP_Buffer)-header_length>char_to_read-1:\n TCP_message=TCP_Buffer[header_length:header_length+char_to_read]\n TCP_messages.append(TCP_message)\n TCP_Buffer=TCP_Buffer[header_length+char_to_read: len(TCP_Buffer)]\n else:\n print (\"less chars-->partial message\", TCP_Buffer)\n break\n \n \n #time.sleep(1)\n\n return TCP_messages\n \nif __name__ == \"__main__\":\n\n print(getTCPdata(TCP_Buffer))","sub_path":"HNA_Individual_Test_Case/TCP_Message_manager.py","file_name":"TCP_Message_manager.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"10034281","text":"import chess\nfrom random import choice\n\n\ndef nb_games(b, depth):\n if depth == 0 or b.is_game_over():\n return 1\n\n cpt = 0\n for m in b.legal_moves:\n b.push(m)\n cpt += nb_games(b, depth - 1)\n b.pop()\n return cpt\n\n\ndef piece_to_value(piece):\n piece = piece.symbol().lower()\n if piece == 'r':\n return 5\n elif piece == 'n' or piece == 'b':\n return 3\n elif piece == 'q':\n return 9\n elif piece == 'k':\n return 200\n return 1\n\n\ndef pawn_to_queen_heuristic(b):\n board_map = b.piece_map()\n target_queen = None\n own_pawn = None\n added_value = 0\n if b.turn :\n target_queen = 'q'\n own_pawn = 'P'\n else:\n target_queen = 'Q'\n own_pawn = 'p'\n\n # find enemy queen\n enemy_queen_position = -1\n for k in board_map:\n if board_map[k].symbol() == target_queen:\n enemy_queen_position = k\n break\n if enemy_queen_position >= 0:\n for k in board_map:\n if board_map[k].symbol() == own_pawn:\n added_value += 1 / chess.square_distance(enemy_queen_position, k)\n return added_value\n\n\ndef shannon_heuristique(b):\n board_map = b.piece_map()\n white_value = 0\n black_value = 0\n for k in board_map:\n piece = board_map[k]\n if piece.color:\n white_value += piece_to_value(piece)\n else:\n black_value += piece_to_value(piece)\n\n\n return white_value - black_value\n\n #return black_value - white_value\n\n\ndef get_heuristique(b):\n return shannon_heuristique(b) + pawn_to_queen_heuristic(b)\n\n\ndef min_minimax(b, depth):\n if depth == 0:\n return get_heuristique(b)\n\n value = 1_000_000\n for m in b.legal_moves:\n b.push(m)\n value = min(value, max_minimax(b, depth - 1))\n b.pop()\n return value\n\n\ndef max_minimax(b, depth):\n if depth == 0:\n return get_heuristique(b)\n\n value = -1_000_000\n for m in b.legal_moves:\n b.push(m)\n value = max(value, min_minimax(b, depth - 1))\n b.pop()\n return value\n\n\ndef found_best_move(b, depth):\n if b.is_game_over():\n return None\n best_move_value = -1_000_000\n value = -1_000_000\n for m in b.legal_moves:\n b.push(m)\n value = max(value, min_minimax(b, depth - 1))\n if value > best_move_value:\n best_move_value = value\n best_move = m\n b.pop()\n return best_move\n\n\ndef min_alphabeta(b, alpha, beta, depth):\n if b.is_game_over() or depth == 0:\n return get_heuristique(b)\n\n value = 1_000_000\n for m in b.legal_moves:\n b.push(m)\n val = max_alphabeta(b, alpha, beta, depth - 1)\n value = min(value, val)\n b.pop()\n if alpha >= value:\n return value\n beta = min(alpha, value)\n return value\n\n\ndef max_alphabeta(b, alpha, beta, depth):\n if b.is_game_over() or depth == 0:\n return get_heuristique(b)\n\n value = -1_000_000\n for m in b.legal_moves:\n b.push(m)\n val = min_alphabeta(b, alpha, beta, depth - 1)\n value = max(value, val)\n b.pop()\n if value >= beta:\n return value\n alpha = max(alpha, value)\n return value\n\n\ndef found_best_move_alphabet(b, depth):\n if b.is_game_over():\n return None\n best_move_value = -1_000_000\n value = -1_000_000\n for m in b.legal_moves:\n b.push(m)\n value = max_alphabeta(b, value, min_alphabeta(b, value, 1_000_000, depth - 1), depth)\n if value > best_move_value:\n best_move_value = value\n best_move = m\n b.pop()\n return best_move\n\n\n\n\nif __name__ == \"__main__\":\n board = chess.Board()\n print(found_best_move(board, 3))\n","sub_path":"src/chess/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"61112914","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nimport csv\nfrom strip_html import *\n\nfilename = ''\n\n\n\ndef browsehtml():\n global filename\n filename = filedialog.askopenfilename(filetypes=(\n (\"HTML files\", \"*.html;*.htm\")\n , (\"All files\", \"*.*\")))\n if filename:\n try:\n file_path_html.set(filename)\n except:\n messagebox.showerror(\"Open Source File\", \"Failed to read file \\n'%s'\" % filename)\n return\n\ndef file_save():\n f = filedialog.asksaveasfile(mode='w', defaultextension=\".csv\")\n if f is None: # asksaveasfile return `None` if dialog closed with \"cancel\".\n return\n print(filename)\n data = parse_html(filename)\n\n\n\n with f as out:\n csv_out = csv.writer(out, lineterminator='\\n')\n for row in data:\n csv_out.writerow(row)\n\n file_path_csv.set(\"CSV Saved Successfully!\")\n f.close() # `()` was missing.\n\n\n\nroot = Tk()\nroot.title(\"Southwire: HTML to CSV Converter\")\nroot.call('wm', 'iconphoto', root._w, PhotoImage(file='ico.gif'))\nroot.geometry('{}x{}'.format(1000, 200))\ncontent = ttk.Frame(root)\ncontent.grid(column=0, row=0)\nframe = ttk.Frame(content, borderwidth=5, relief=\"sunken\", width=200, height=100)\n\nfile_path_html = StringVar(value='')\nfile_path_csv = StringVar(value='')\n\n\n\nttk.Label(content, text=\"Browse for HTML File: \").grid(column=0, row=0, sticky=W)\nttk.Button(content, text = \"Browse HTML\", command = browsehtml).grid(column=1, row=0)\nttk.Label(content, textvariable=file_path_html).grid(column=2, row=0, sticky=W)\n\nttk.Label(content, text=\"Save As CSV: \").grid(column=0, row=1, sticky=W)\nttk.Button(content, text = \"Save CSV\", command = file_save).grid(column=1, row=1)\nttk.Label(content, textvariable=file_path_csv).grid(column=2, row=1, sticky=W)\n\n\n\nroot.mainloop()","sub_path":"src/html_csv.py","file_name":"html_csv.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"423815873","text":"import mcpi.minecraft as minecraft\nimport mcpi.block as block\n\nclass House(object):\n def __init__(self, mc, x, y, z, width, height):\n self.x = x\n self.y = y\n self.z = z\n self.width = width\n self.height = height\n self.mc = mc\n\n def build_ceiling_floor(self):\n for i in range(self.width):\n for j in range(self.width):\n self.mc.setBlock(self.x + i, self.y, self.z + j, block.GRASS.id)\n self.mc.setBlock(self.x + i, self.y + self.height, self.z + j, block.TNT.id)\n\n def build_walls(self):\n for i in range(self.width):\n for k in range(self.height):\n self.mc.setBlock(self.x + i, self.y + k, self.z, 89)\n self.mc.setBlock(self.x + i, self.y + k, self.z + self.width - 1, 89)\n self.mc.setBlock(self.x, self.y + k, self.z + i, 89)\n self.mc.setBlock(self.x + self.width - 1, self.y + k, self.z + i, 89)\n\n def build_windows_door(self):\n # windows\n window_length = 4\n window_margin = (int(self.width / 2) - window_length / 2, int(self.height / 2) - window_length / 2)\n for m in range(window_length):\n for n in range(window_length):\n self.mc.setBlock(self.x + window_margin[0] + m, self.y + window_margin[1] + n, self.z, block.GLASS.id)\n self.mc.setBlock(self.x + window_margin[0] + m, self.y + window_margin[1] + n, self.z + self.width - 1, block.GLASS.id)\n self.mc.setBlock(self.x, self.y + window_margin[1] + n, self.z + window_margin[0] + m, block.GLASS.id)\n # door\n door_length = 3\n door_height = 4\n for a in range(door_height):\n for b in range(door_length):\n self.mc.setBlock(self.x + self.width - 1, self.y + 1 + a, self.z + int(self.width / 2) + b, 0)\n\n def build_all(self):\n self.build_ceiling_floor()\n self.build_walls()\n self.build_windows_door()\n\ndef main():\n mc = minecraft.Minecraft.create()\n pos = mc.player.getTilePos()\n house_num = 3\n interval = 20\n for i in range(house_num):\n for j in range(house_num):\n for k in range(house_num):\n house = House(mc, pos.x+i*interval, pos.y+j*interval, pos.z+k*interval, 12, 8)\n house.build_all()\n\nmain()\n\n\n","sub_path":"students/ChenYizhou/house.py","file_name":"house.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"408899012","text":"# Copyright (c) 2015 App Annie Inc. All rights reserved.\n\nfrom tests.qa.base import BaseSeleniumTestCase\nfrom tests.qa.constants.constants import Devices, Stores, Granularity, IOSCategories, GPCategories, MARKETS\nfrom tests.qa.utils import csv_utils, datetime_utils, product_utils, basic_utils\nfrom tests.qa.pages.intelligence.top_chart_page import INTTopPage\nfrom tests.qa.services.intelligence.dailyapi.dailyapi_app import DailyAPIAppService\n\n\nclass TrialCSVDownloadTest(BaseSeleniumTestCase):\n\n def c36463_partial_trial_user_download_csv_test(self):\n user = 'partial_trial_store@appannie-int.com'\n device = Devices.ALL\n store_id = product_utils.find_id_by_store(Stores.US, device)\n category_id = product_utils.find_id_by_category(IOSCategories.Overall, device)\n date = datetime_utils.get_random_day_in_last_month()\n top_page = INTTopPage(self.selenium).prepare_top_chart(user, date, device, store_id, category_id, 1000)\n self.assertFalse(top_page.is_trial_csv_download_helptip_exist())\n\n\nclass BasicCSVDownloadTest(BaseSeleniumTestCase):\n\n def setUp(self):\n BaseSeleniumTestCase.setUp(self)\n self.user = 'ult@appannie-int.com'\n self.stores = Stores.US\n self.top_rank = 100\n self.granularity = Granularity.daily\n self.date = datetime_utils.get_random_day_in_last_month()\n\n def download_check_csv_content(self, device, category):\n store_id = product_utils.find_id_by_store(self.stores, device)\n category_id = product_utils.find_id_by_category(category, device)\n top_page = INTTopPage(self.selenium).prepare_top_chart(\n self.user, self.date, device, store_id, category_id, self.top_rank, self.granularity)\n top_page.click_download_csv_button()\n file_name_content = csv_utils.get_csv_file_name_content(list_length=0)\n file_name = file_name_content['file_name']\n file_content = file_name_content['dict_content']\n self.assertTrue(file_name)\n self.assertIn(\"Top_Apps_Chart\", file_name)\n self.assertIn(self.date, file_name)\n # if product_utils.get_market_from_device(device) != MARKETS[1]:\n # self.assertIn(device.lower(), file_name.lower())\n # else:\n # self.assertIn(MARKETS[1], file_name)\n self.assertIn(category, file_name)\n self.assertGreater(len(file_content), 5)\n feed_id = product_utils.find_id_by_feed(file_content[0]['Type'], device)\n db_est = DailyAPIAppService(device).get_app_estimate_with_granularity(\n store_id, (feed_id,), (category_id,), file_content[0]['App ID'], self.date, self.granularity)\n self.assertIn(str(db_est), file_content[0]['Value'])\n\n def c36160_ios_top_chart_test(self):\n device = Devices.IOS\n category = IOSCategories.Music\n self.download_check_csv_content(device, category)\n\n def c36159_unified_top_chart_test(self):\n device = Devices.ALL\n category = IOSCategories.Applications\n self.download_check_csv_content(device, category)\n\n def c36162_iphone_top_chart_test(self):\n device = Devices.IPHONE\n category = IOSCategories.Games\n self.download_check_csv_content(device, category)\n\n def c36161_ipad_top_chart_test(self):\n device = Devices.IPAD\n category = IOSCategories.Applications\n self.download_check_csv_content(device, category)\n\n def c36163_gp_top_chart_test(self):\n device = Devices.ANDROID\n category = GPCategories.Games\n self.download_check_csv_content(device, category)\n\n def tearDown(self):\n csv_utils.clean_csv_dir()\n BaseSeleniumTestCase.tearDown(self)\n","sub_path":"tests/qa/cases/intelligence/top_chart/csv_download/test_top_app_csv_download.py","file_name":"test_top_app_csv_download.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"400674330","text":"def load_words_from_file(filename):\n \"\"\" Read words from filename, return list of words. \"\"\"\n f = open(filename, \"r\")\n file_content = f.read()\n f.close()\n wds = file_content.split()\n return wds\n\nbigger_vocab = load_words_from_file(\"vocab.txt\")\nprint(\"There are {0} words in the vocab, starting with\\n {1} \"\n .format(len(bigger_vocab), bigger_vocab[:6]))","sub_path":"Practice/prac02.py","file_name":"prac02.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"557479307","text":"def insertPending(self, payer, payee, description, amount):\n makeReceipt = \"INSERT INTO pending(payer, payee, description, amount) VALUES (?, ?, ?, ?);\"\n arguments = (payer, payee, description, amount)\n cursor = self.conn.cursor()\n cursor.execute(makeReceipt, arguments)\n self.conn.commit()\n\ndef getPending(self, payer, payee):\n getPending = \"SELECT * FROM pending WHERE payer=? AND payee=?;\"\n arguments = (payer, payee)\n cursor = self.conn.cursor()\n cursor.execute(getPending, arguments)\n self.printTable(\"pending\")\n\n rows = cursor.fetchall()\n list = []\n if rows != []:\n for row in rows:\n list.append(row)\n else:\n return None\n return list\n\ndef getAllPending(self, payee):\n getPending = \"SELECT * FROM pending WHERE payee=?;\"\n arguments = (payee,)\n cursor = self.conn.cursor()\n cursor.execute(getPending, arguments)\n\n rows = cursor.fetchall()\n\n list = []\n if rows != []:\n for row in rows:\n list.append(row)\n else:\n return None\n\n self.conn.commit()\n return list\n\ndef deleteAllPending(self, payee):\n deleteQuery = \"DELETE FROM pending WHERE payee=?;\"\n arguments = (payee,)\n cursor = self.conn.cursor()\n cursor.execute(deleteQuery, arguments)\n self.conn.commit()\n","sub_path":"db/pendings_table.py","file_name":"pendings_table.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"509061224","text":"import tkinter\r\n\r\n\r\nclass MyGUI:\r\n def __init__(self):\r\n self.main_window = tkinter.Tk()\r\n self.canvas = tkinter.Canvas(self.main_window, width=160, height=160)\r\n self.canvas.create_polygon(60, 20, 100, 20, 140, 60, 140, 100, 100, 140, 60, 140, 20, 100, 20, 60, fill='blue',\r\n outline='black', width=2)\r\n self.canvas.pack()\r\n tkinter.mainloop()\r\n\r\n\r\nmy_gui = MyGUI()\r\n","sub_path":"canvas_draw_polygon.py","file_name":"canvas_draw_polygon.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"621143332","text":"from collect import save_all_stocks\nfrom analysis import momentum_analysis,from_online\nfrom tracker import track_buys_sells,cull_stocks,plot_debt\nimport time\nimport datetime as dt\nimport numpy as np\n\n#save_all_stocks()\n#momentum_analysis()\n#track_buys_sells('eqb.TO')\n#cull_stocks()\n\ndef is_worktime():\n '''Checks if the current time aligns with regular trading times for the east coast'''\n now = dt.datetime.today()\n if now.date().weekday()<5 and dt.time(9,30) <= now.time() and \\\n now.time() <= dt.time(16,30):\n return True\n else:\n return False\n \ndef run(): \n \n if is_worktime():\n pass\n elif is_worktime()==False:\n #save_all_stocks()\n #momentum_analysis()\n #cull_stocks()\n \n with open('acceptable.txt') as f:\n content = f.readlines()\n acceptable = [x.strip() for x in content] \n \n ticker = 'ECN.TO'\n max_buy = 96\n max_sell = 110\n \n plot_debt(ticker=ticker,max_buy=max_buy,max_sell=max_sell)\n \nrun()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"571015394","text":"from analysis import Analysis_page\nfrom pred import stock_pred\nimport yfinance as yf\nimport streamlit as st\nimport datetime\nimport webbrowser\nimport keras.backend.tensorflow_backend as tb\ntb._SYMBOLIC_SCOPE.value = True\nyf.pdr_override()\ntoday = datetime.date.today()\n\n\ndef navi():\n pages= {\n 'Analysis Stock': Analysis_page,\n 'Get Predictions': stock_pred\n }\n st.sidebar.title(\"DASHBOARD\")\n\n selection = st.sidebar.radio(\"Select your page\", tuple(pages.keys()))\n pages[selection]()\n\n\n\nimport base64\n\nmain_bg = \"14.jpg\"\nmain_bg_ext = \"jpg\"\n\nside_bg = '16.jpg'\nside_bg_ext = \"jpg\"\n\nst.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n)\nif __name__ == '__main__':\n navi()\n\n\n\n\n","sub_path":"STOCK/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483118696","text":"import time\n\nfrom selenium.webdriver import Chrome\n\n\ndriver = Chrome()\n\ndriver.get('http://www.baidu.com')\n\ntime.sleep(3)\n\n# 最小化\ndriver.minimize_window()\n\n# 最大化\ndriver.maximize_window()\n\n# 访问豆瓣\ndriver.get('http://www.douban.com')\n\n# 后退\ndriver.back()\n\n# 前进\ndriver.forward()\n\n# 刷新\ndriver.refresh()\n\n# 获取网页标题\nprint(driver.title)\n\n# 获取 URL\nprint(driver.current_url)\n\n# 截屏\ndriver.save_screenshot('test.png')\n\n# 获取窗口句柄,窗口id, 还有名字。\nprint(driver.current_window_handle)\n\n# 关闭标签页,当只有一个标签打开的时候, 执行close就相当于额关闭了浏览器。\ndriver.close()\n\n# 关闭浏览器\ndriver.quit()","sub_path":"等待代码和笔记/d1_ui.py","file_name":"d1_ui.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"32001283","text":"'''\nCreated on May 2, 2018\n\n@author: chapmacl\n'''\n\nimport csv\nimport re\n\nr = csv.reader(open('flu_tweets.csv'))\nlines = list(r)\ntext = lines[0][0]\nfor x in range(0, lines.__len__()):\n text = lines[x][1]\n text = re.sub(r\"https\\S+\", \"\", text)\n text = re.sub(r\"@\\S+\", \"\", text) \n text = re.sub(\"RT\", \"\", text)\n text = re.sub(\"\\n\", \" \", text)\n lines[x][1] = text\n\nwriter = csv.writer(open('test.csv', \"w\", newline=''))\nwriter.writerows(lines)\n\n","sub_path":"Cleaner.py","file_name":"Cleaner.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"198723605","text":"from typing import Dict, Union, List\n\nfrom zkay_ast.ast import FunctionCallExpr, BuiltinFunction, BooleanLiteralExpr, NumberLiteralExpr, \\\n\tReclassifyExpr, AllExpr, MeExpr, ReturnStatement, RequireStatement, AssignmentStatement, Block, TypeName, \\\n\tVariableDeclaration, FunctionDefinition, IdentifierExpr, VariableDeclarationStatement, ConstructorDefinition, \\\n\tExpression, AST, AnnotatedTypeName, StateVariableDeclaration, ContractDefinition, Mapping, \\\n\tConstructorOrFunctionDefinition, Parameter, Identifier\nfrom zkay_ast.visitor.visitor import AstVisitor\n\n\nclass Simulator(AstVisitor):\n\n\tdef __init__(self):\n\t\tsuper().__init__(None)\n\t\tself.location_getter = LocationGetter(self)\n\n\t\t# set later by call\n\t\tself.state: Dict = {}\n\t\tself.me: str = None\n\t\tself.return_value = None\n\t\tself.parameters: List = None\n\t\tself.values: Dict[Union[Parameter, Expression], object] = None\n\t\tself.owners: Dict[Union[Parameter, Expression], str] = None\n\n\tdef visit(self, ast: AST):\n\t\tf = self.get_visit_function(ast.__class__)\n\t\tif f:\n\t\t\tret = f(ast)\n\t\t\tif isinstance(ast, Expression) and ast.parent is not None and not isinstance(ast.parent, AnnotatedTypeName):\n\t\t\t\tself.values[ast] = ret\n\n\t\t\t\tif ast.annotated_type:\n\t\t\t\t\tprivacy = ast.annotated_type.privacy_annotation\n\t\t\t\t\tself.owners[ast] = self.visit_privacy_annotation(privacy)\n\t\t\treturn ret\n\t\telse:\n\t\t\traise NotImplementedError(ast.__class__, ast)\n\n\tdef visit_privacy_annotation(self, expr: Expression):\n\t\tlabel = expr.privacy_annotation_label()\n\t\tif isinstance(label, Identifier):\n\t\t\treturn self.state[label.parent]\n\t\telse:\n\t\t\treturn self.visit(label)\n\n\tdef call(self, f: ConstructorOrFunctionDefinition, me: str, parameters: List):\n\t\tself.me = me\n\t\tself.return_value = None\n\t\tself.parameters = parameters\n\t\tself.values = {}\n\t\tself.owners = {}\n\t\treturn self.visit(f)\n\n\tdef evaluate(self, state: Dict, expr: Expression, me: str):\n\t\tself.state = state\n\t\tself.me = me\n\t\tself.values = {}\n\t\tself.owners = {}\n\t\treturn self.visit(expr)\n\n\tdef state_by_name(self):\n\t\tret = {}\n\t\tfor k, v in self.state.items():\n\t\t\tassert(isinstance(k, StateVariableDeclaration))\n\t\t\tret[k.idf.name] = v\n\t\treturn ret\n\n\tdef visitFunctionCallExpr(self, ast: FunctionCallExpr):\n\t\tf = ast.func\n\t\targs = [self.visit(a) for a in ast.args]\n\t\tif isinstance(f, BuiltinFunction):\n\t\t\tif f.op == 'index':\n\t\t\t\tm, i = self.location_getter.visit(ast)\n\n\t\t\t\tif i not in m:\n\t\t\t\t\tt = ast.annotated_type.type_name\n\t\t\t\t\tif isinstance(t, Mapping):\n\t\t\t\t\t\tm[i] = {}\n\t\t\t\t\telif t == TypeName.uint_type():\n\t\t\t\t\t\tm[i] = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tSimulationException(f'No default value for type {t}', ast)\n\t\t\t\treturn m[i]\n\t\t\telif f.op == 'parenthesis':\n\t\t\t\treturn args[0]\n\t\t\telif f.op == 'ite':\n\t\t\t\tif args[0]:\n\t\t\t\t\treturn args[1]\n\t\t\t\telse:\n\t\t\t\t\treturn args[2]\n\t\t\telif f.op == '/':\n\t\t\t\treturn args[0] // args[1]\n\t\t\telif f.is_arithmetic() or f.is_comp():\n\t\t\t\texpr = f.format_string().format(*args)\n\t\t\t\ttry:\n\t\t\t\t\tr = eval(expr)\n\t\t\t\texcept TypeError as e:\n\t\t\t\t\traise SimulationException(f'Could not compute {expr}', ast) from e\n\t\t\t\treturn r\n\t\t\telif f.op == '==':\n\t\t\t\treturn args[0] == args[1]\n\t\t\telif f.op == '!=':\n\t\t\t\treturn args[0] != args[1]\n\t\t\telif f.op == '&&':\n\t\t\t\treturn args[0] and args[1]\n\t\t\telif f.op == '||':\n\t\t\t\treturn args[0] or args[1]\n\t\t\telif f.op == '!':\n\t\t\t\treturn not args[0]\n\t\t\telse:\n\t\t\t\traise SimulationException(f'Unsupported operation {f.op}', ast)\n\t\telse:\n\t\t\traise NotImplementedError('Function call')\n\n\tdef visitBooleanLiteralExpr(self, ast: BooleanLiteralExpr):\n\t\treturn ast.value\n\n\tdef visitNumberLiteralExpr(self, ast: NumberLiteralExpr):\n\t\treturn ast.value\n\n\tdef visitIdentifierExpr(self, ast: IdentifierExpr):\n\t\tm, i = self.location_getter.visit(ast)\n\t\treturn m[i]\n\n\tdef visitMeExpr(self, _: MeExpr):\n\t\treturn self.me\n\n\tdef visitAllExpr(self, _: AllExpr):\n\t\treturn 'all'\n\n\tdef visitReclassifyExpr(self, ast: ReclassifyExpr):\n\t\treturn self.visit(ast.expr)\n\n\tdef visitReturnStatement(self, ast: ReturnStatement):\n\t\tself.return_value = self.visit(ast.expr)\n\n\tdef visitRequireStatement(self, ast: RequireStatement):\n\t\tcond = self.visit(ast.condition)\n\t\tif not cond:\n\t\t\traise SimulationException(f'\"require\" condition does not hold in state {self.state}', ast)\n\n\tdef visitAssignmentStatement(self, ast: AssignmentStatement):\n\t\tm, i = self.location_getter.visit(ast.lhs)\n\t\te = self.visit(ast.rhs)\n\t\tm[i] = e\n\n\tdef visitBlock(self, ast: Block):\n\t\tfor s in ast.statements:\n\t\t\tself.visit(s)\n\t\t\tif self.return_value:\n\t\t\t\treturn self.return_value\n\n\tdef visitTypeName(self, ast: TypeName):\n\t\traise SimulationException('Should not evaluate types', ast)\n\n\tdef visitVariableDeclarationStatement(self, ast: VariableDeclarationStatement):\n\t\tself.handle_declaration(ast.variable_declaration, ast.expr)\n\n\tdef handle_function_definition(self, ast: ConstructorOrFunctionDefinition):\n\t\tfor i, p in enumerate(ast.parameters):\n\t\t\tv = self.parameters[i]\n\t\t\tself.state[p] = v\n\n\t\t\tself.values[p] = v\n\t\t\tself.owners[p] = self.visit(p.annotated_type.privacy_annotation.privacy_annotation_label())\n\n\t\tr = self.visit(ast.body)\n\n\t\t# only keep state variables\n\t\tfor k in set(self.state.keys()):\n\t\t\tif not isinstance(k, StateVariableDeclaration):\n\t\t\t\tdel self.state[k]\n\n\t\treturn r\n\n\tdef visitFunctionDefinition(self, ast: FunctionDefinition):\n\t\treturn self.handle_function_definition(ast)\n\n\tdef handle_declaration(self, d: Union[VariableDeclaration, StateVariableDeclaration], expr: Expression):\n\t\tif expr:\n\t\t\te = self.visit(expr)\n\t\t\tself.state[d] = e\n\t\telif isinstance(d.annotated_type.type_name, Mapping):\n\t\t\tself.state[d] = {}\n\t\telse:\n\t\t\tself.state[d] = None\n\n\tdef visitConstructorDefinition(self, ast: ConstructorDefinition):\n\t\tassert(isinstance(ast.parent, ContractDefinition))\n\t\tfor d in ast.parent.state_variable_declarations:\n\t\t\tself.handle_declaration(d, d.expr)\n\t\treturn self.handle_function_definition(ast)\n\n\nclass LocationGetter(AstVisitor):\n\n\tdef __init__(self, s: Simulator):\n\t\tsuper().__init__(None)\n\t\tself.s = s\n\n\tdef visitFunctionCallExpr(self, ast: FunctionCallExpr):\n\t\tf = ast.func\n\t\tif isinstance(f, BuiltinFunction):\n\t\t\tif f.op == 'index':\n\t\t\t\tarr = self.s.visit(ast.args[0])\n\t\t\t\tindex = self.s.visit(ast.args[1])\n\t\t\t\treturn arr, index\n\t\traise ValueError(ast)\n\n\tdef visitIdentifierExpr(self, ast: IdentifierExpr):\n\t\treturn self.s.state, ast.target\n\n\nclass SimulationException(Exception):\n\n\tdef __init__(self, msg, ast: AST):\n\t\tsuper().__init__(f'{msg}\\nFor: {str(ast)}')\n","sub_path":"src/transaction/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"493831222","text":"from django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.conf.urls import url,include\nfrom . import views\n\nurlpatterns=[\n url('^$',views.home,name = 'home'),\n url('driver/profile',views.profile_info, name='profile'),\n url('update/',views.profile_update, name='update'),\n url('driver/destination',views.destination, name = 'destination'),\n url('driver/contact',views.contact, name = 'contact'),\n url('about',views.about, name = 'about'),\n]\n\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47417364","text":"\"\"\"\npoll_server.py 完成tcp并发\n重点代码\n\n思路分析: 创建监听套接字先进行监控\n 产生新的套接字也加入到监控中\n\"\"\"\nfrom socket import *\nfrom select import *\n\n# 创建监听套接字\ns = socket()\ns.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\ns.bind(('0.0.0.0', 8888))\ns.listen(3)\n\n# 创建poll对象\np = poll()\np.register(s, POLLIN) # 将s设置关注\n\n# 建立一个查找字典,用于通过文件描述符查找其对应的IO对象\n# 跟关注的IO保持一致\nfdmap = {s.fileno(): s}\n\n# 循环监控IO\nwhile True:\n events = p.poll() # 阻塞等待IO发生\n print(events) # [(fileno,event)]\n for fd, event in events:\n # if结构区分哪个IO就绪 fd->fileno event->IO类别\n if fd == s.fileno():\n c, addr = fdmap[fd].accept()\n print(\"Connect from\", addr)\n p.register(c, POLLIN | POLLERR) # 关注客户端套接字\n fdmap[c.fileno()] = c # 将其添加到查找字典\n # 通过按位与判断是否为POLLIN就绪\n elif event & POLLIN:\n data = fdmap[fd].recv(1024).decode()\n if not data:\n p.unregister(fd) # 取消关注\n fdmap[fd].close()\n del fdmap[fd] # 从字典中移除\n continue\n print(data)\n fdmap[fd].send(b'OK')\n","sub_path":"month02,ziliao/day10/poll_server.py","file_name":"poll_server.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"202955917","text":"from django.conf import settings\nfrom django.views.generic.edit import ModelFormMixin\nfrom django_datatables_view.base_datatable_view import BaseDatatableView\nfrom insitu.utils import ALL_OPTIONS_LABEL\nfrom insitu.views.protected.views import ProtectedView\n\n\nclass ESDatatableView(BaseDatatableView, ProtectedView):\n def get_initial_queryset(self):\n return self.document.search()\n\n def ordering(self, qs):\n sorting_cols = 0\n if self.pre_camel_case_notation:\n try:\n sorting_cols = int(self._querydict.get('iSortingCols', 0))\n except ValueError:\n sorting_cols = 0\n else:\n sort_key = 'order[{0}][column]'.format(sorting_cols)\n while sort_key in self._querydict:\n sorting_cols += 1\n sort_key = 'order[{0}][column]'.format(sorting_cols)\n\n order = []\n order_columns = self.get_order_columns()\n for i in range(sorting_cols):\n # sorting column\n sort_dir = 'asc'\n try:\n if self.pre_camel_case_notation:\n sort_col = int(self._querydict.get('iSortCol_{0}'.format(i)))\n # sorting order\n sort_dir = self._querydict.get('sSortDir_{0}'.format(i))\n else:\n sort_col = int(self._querydict.get('order[{0}][column]'.format(i)))\n # sorting order\n sort_dir = self._querydict.get('order[{0}][dir]'.format(i))\n except ValueError:\n sort_col = 0\n\n sdir = '-' if sort_dir == 'desc' else ''\n sortcol = order_columns[sort_col]\n\n if isinstance(sortcol, list):\n for sc in sortcol:\n order.append('{0}{1}'.format(sdir, sc.replace('.', '__')))\n else:\n order.append('{0}{1}'.format(sdir, sortcol.replace('.', '__')))\n\n if order:\n for i in range(0, len(order)):\n if order[i] == 'name':\n order[i] = 'name.raw'\n if order[i] == '-name':\n order[i] = '-name.raw'\n return qs.order_by(*order)\n return qs\n\n def filter_queryset(self, search):\n \"\"\"\n Where `search` is a django_elasticsearch_dsl.search.Search object.\n \"\"\"\n for filter_ in self.filters:\n value = self.request.GET.get(filter_)\n if not value or value == ALL_OPTIONS_LABEL:\n continue\n search = search.query('term', **{filter_: value})\n\n search_text = self.request.GET.get('search[value]', '')\n if search_text:\n search = search.query(\n 'query_string', default_field='name',\n query='\"' + search_text + '\"'\n )\n\n if (\n search.count() > settings.MAX_RESULT_WINDOW or not\n hasattr(self, 'filter_fields')):\n # If there are more than MAX_RESULT_WINDOW matching objects in the\n # database, don't bother syncing the filter options. It would be too\n # complicated and costly.\n return search\n\n search = search[0:settings.MAX_RESULT_WINDOW]\n qs = search.to_queryset() # If there are ever more than 10,000\n # items in the database, this will have to be reimplemented entirely.\n objects = qs.values_list(*self.filter_fields)\n\n self._filter_options = dict([\n (\n filter_,\n {\n 'options': options,\n 'selected': self.request.GET.get(filter_)\n }\n )\n for filter_, options in\n zip(\n self.filters,\n [\n sorted([opt for opt in set(options) if opt\n not in ['', None]])\n for options in zip(*objects)\n ]\n )\n ])\n return search\n\n def get_context_data(self, *args, **kwargs):\n ret = super().get_context_data(*args, **kwargs)\n if hasattr(self, '_filter_options'):\n ret.update({\n 'filters': self._filter_options\n })\n return ret\n\n\nclass CreatedByMixin:\n def form_valid(self, form):\n self.object = form.save(created_by=self.request.user)\n return super(ModelFormMixin, self).form_valid(form)\n","sub_path":"insitu/views/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519438689","text":"# Hint: You may not need all of these. Remove the unused functions.\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n \n ticketDict = {}\n tripArr = []\n\n for ticket in tickets:\n ticketDict[ticket.source] = ticket.destination\n \n currentSource = ticketDict['NONE']\n\n while currentSource != \"NONE\":\n\n tripArr.append(currentSource)\n\n currentSource = ticketDict[currentSource]\n \n tripArr.append('NONE')\n\n\n return tripArr\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"561163122","text":"import logging\r\nimport numba\r\nimport numpy as np\r\nfrom enum import Enum\r\n\r\nfrom climate_indices import compute, palmer, thornthwaite, utils\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\nclass Distribution(Enum):\r\n \"\"\"\r\n Enumeration type for distribution fittings used for SPI and SPEI.\r\n \"\"\"\r\n pearson_type3 = 'Pearson Type III'\r\n gamma = 'gamma'\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n# valid upper and lower bounds for indices that are fitted/transformed to a distribution (SPI and SPEI)\r\n_FITTED_INDEX_VALID_MIN = -3.09\r\n_FITTED_INDEX_VALID_MAX = 3.09\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n#@numba.jit\r\ndef spi(precips,\r\n scale,\r\n distribution,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n periodicity):\r\n '''\r\n Computes SPI (Standardized Precipitation Index).\r\n\r\n :param precips: 1-D numpy array of precipitation values, in any units, first value assumed to correspond\r\n to January of the initial year if the periodicity is monthly, or January 1st of the initial\r\n year if daily\r\n :param scale: number of time steps over which the values should be scaled before the index is computed\r\n :param distribution: distribution type to be used for the internal fitting/transform computation\r\n :param data_start_year: the initial year of the input precipitation dataset\r\n :param calibration_year_initial: initial year of the calibration period\r\n :param calibration_year_final: final year of the calibration period\r\n :param periodicity: the periodicity of the time series represented by the input data, valid/supported values are\r\n 'monthly' and 'daily'\r\n 'monthly' indicates an array of monthly values, assumed to span full years, i.e. the first\r\n value corresponds to January of the initial year and any missing final months of the final\r\n year filled with NaN values, with size == # of years * 12\r\n 'daily' indicates an array of full years of daily values with 366 days per year, as if each\r\n year were a leap year and any missing final months of the final year filled with NaN values,\r\n with array size == (# years * 366)\r\n :return SPI values fitted to the gamma distribution at the specified time step scale, unitless\r\n :rtype: 1-D numpy.ndarray of floats of the same length as the input array of precipitation values\r\n '''\r\n\r\n # we expect to operate upon a 1-D array, so if we've been passed a 2-D array we flatten it, otherwise raise an error\r\n shape = precips.shape\r\n if len(shape) == 2:\r\n precips = precips.flatten()\r\n elif len(shape) != 1:\r\n message = 'Invalid shape of input array: {0} -- only 1-D and 2-D arrays are supported'.format(shape)\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # if we're passed all missing values then we can't compute anything, return the same array of missing values\r\n if (np.ma.is_masked(precips) and precips.mask.all()) or np.all(np.isnan(precips)):\r\n return precips\r\n\r\n # remember the original length of the array, in order to facilitate returning an array of the same size\r\n original_length = precips.size\r\n\r\n # get a sliding sums array, with each time step's value scaled by the specified number of time steps\r\n scaled_precips = compute.sum_to_scale(precips, scale)\r\n\r\n # reshape precipitation values to (years, 12) for monthly, or to (years, 366) for daily\r\n if periodicity == 'monthly':\r\n\r\n scaled_precips = utils.reshape_to_2d(scaled_precips, 12)\r\n\r\n elif periodicity == 'daily':\r\n\r\n scaled_precips = utils.reshape_to_2d(scaled_precips, 366)\r\n\r\n else:\r\n\r\n raise ValueError('Invalid periodicity argument: %s' % periodicity)\r\n\r\n if distribution == 'gamma':\r\n # print('gamma distribution is used')\r\n # fit the scaled values to a gamma distribution and transform to corresponding normalized sigmas\r\n transformed_fitted_values = compute.transform_fitted_gamma(scaled_precips,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n periodicity)\r\n elif distribution == 'Pearson Type III':\r\n\r\n # fit the scaled values to a Pearson Type III distribution and transform to corresponding normalized sigmas\r\n transformed_fitted_values = compute.transform_fitted_pearson(scaled_precips,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n periodicity)\r\n\r\n # clip values to within the valid range, reshape the array back to 1-D\r\n spi = np.clip(transformed_fitted_values, _FITTED_INDEX_VALID_MIN, _FITTED_INDEX_VALID_MAX).flatten()\r\n\r\n # return the original size array\r\n return spi[0:original_length]\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n#@numba.jit\r\ndef spei(scale,\r\n distribution,\r\n periodicity,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n precips_mm,\r\n pet_mm=None,\r\n temps_celsius=None,\r\n latitude_degrees=None):\r\n '''\r\n Compute SPEI fitted to the gamma distribution.\r\n\r\n PET values are subtracted from the precipitation values to come up with an array of (P - PET) values, which is\r\n then scaled to the specified months scale and finally fitted/transformed to SPEI values corresponding to the\r\n input precipitation time series.\r\n\r\n If an input array of temperature values is provided then PET values are computed internally using the input\r\n temperature array, data start year, and latitude value (all three of which are required in combination).\r\n In this case an input array of PET values should not be specified and if so will result in an error being\r\n raised indicating invalid arguments.\r\n\r\n If an input array of PET values is provided then neither an input array of temperature values nor a latitude\r\n should be specified, and if so will result in an error being raised indicating invalid arguments.\r\n\r\n :param scale: the number of months over which the values should be scaled before computing the indicator\r\n :param distribution: distribution type to be used for the internal fitting/transform computation\r\n :param periodicity: the periodicity of the time series represented by the input data, valid/supported values are\r\n 'monthly' and 'daily'\r\n 'monthly' indicates an array of monthly values, assumed to span full years, i.e. the first\r\n value corresponds to January of the initial year and any missing final months of the final\r\n year filled with NaN values, with size == # of years * 12\r\n 'daily' indicates an array of full years of daily values with 366 days per year, as if each\r\n year were a leap year and any missing final months of the final year filled with NaN values,\r\n with array size == (# years * 366)\r\n :param precips_mm: an array of monthly total precipitation values, in millimeters, should be of the same size\r\n (and shape?) as the input temperature array\r\n :param pet_mm: an array of monthly PET values, in millimeters, should be of the same size (and shape?) as the input\r\n precipitation array, must be unspecified or None if using an array of temperature values as input\r\n :param temps_celsius: an array of monthly average temperature values, in degrees Celsius, should be of the same size\r\n (and shape?) as the input precipitation array, must be unspecified or None if using an array\r\n of PET values as input\r\n :param data_start_year: the initial year of the input datasets (assumes that the two inputs cover the same period)\r\n :param latitude_degrees: the latitude of the location, in degrees north, must be unspecified or None if using\r\n an array of PET values as an input, and must be specified if using an array of temperatures\r\n as input, valid range is -90.0 to 90.0 (inclusive)\r\n :return: an array of SPEI values\r\n :rtype: numpy.ndarray of type float, of the same size and shape as the input temperature and precipitation arrays\r\n '''\r\n\r\n # if we're passed all missing values then we can't compute anything, return the same array of missing values\r\n if (np.ma.is_masked(precips_mm) and precips_mm.mask.all()) or np.all(np.isnan(precips_mm)):\r\n return precips_mm\r\n\r\n # validate the function's argument combinations\r\n if temps_celsius is not None:\r\n\r\n # since we have temperature then it's expected that we'll compute PET internally, so we shouldn't have PET as an input\r\n if pet_mm is not None:\r\n message = 'Incompatible arguments: either temperature or PET arrays can be specified as arguments, but not both'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # we'll need both the latitude and data start year in order to compute PET\r\n elif (latitude_degrees is None) or (data_start_year is None):\r\n message = 'Missing arguments: since temperature is provided as an input then both latitude ' + \\\r\n 'and the data start year must also be specified, and one or both is not'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # validate that the two input arrays are compatible\r\n elif precips_mm.size != temps_celsius.size:\r\n message = 'Incompatible precipitation and temperature arrays'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n elif periodicity != 'monthly':\r\n # our PET currently uses a monthly version of Thornthwaite's equation and therefore's only valid for monthly\r\n message = 'Unsupported periodicity: \\'{0}\\' '.format(periodicity) + \\\r\n '-- only monthly time series is supported when providing temperature and latitude inputs'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # compute PET\r\n pet_mm = pet(temps_celsius, latitude_degrees, data_start_year)\r\n # print(pet_mm)\r\n\r\n elif pet_mm is not None:\r\n\r\n # make sure there's no confusion by not allowing a user to specify unnecessary parameters\r\n if latitude_degrees is not None:\r\n message = 'Invalid argument: since PET is provided as an input then latitude must be absent'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # validate that the two input arrays are compatible\r\n elif precips_mm.size != pet_mm.size:\r\n message = 'Incompatible precipitation and PET arrays'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n else:\r\n\r\n message = 'Neither temperature nor PET array was specified, one or the other is required for SPEI'\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # subtract the PET from precipitation, adding an offset to ensure that all values are positive\r\n p_minus_pet = (precips_mm.flatten() - pet_mm.flatten()) + 1000.0\r\n\r\n # remember the original length of the input array, in order to facilitate returning an array of the same size\r\n original_length = precips_mm.size\r\n\r\n # get a sliding sums array, with each element's value scaled by the specified number of time steps\r\n scaled_values = compute.sum_to_scale(p_minus_pet, scale)\r\n\r\n if distribution == 'gamma':\r\n\r\n # fit the scaled values to a gamma distribution and transform to corresponding normalized sigmas\r\n transformed_fitted_values = compute.transform_fitted_gamma(scaled_values,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n periodicity)\r\n\r\n elif distribution == 'Pearson Type III':\r\n\r\n # fit the scaled values to a Pearson Type III distribution and transform to corresponding normalized sigmas\r\n transformed_fitted_values = compute.transform_fitted_pearson(scaled_values,\r\n data_start_year,\r\n calibration_year_initial,\r\n calibration_year_final,\r\n periodicity)\r\n\r\n # clip values to within the valid range, reshape the array back to 1-D\r\n spei = np.clip(transformed_fitted_values, _FITTED_INDEX_VALID_MIN, _FITTED_INDEX_VALID_MAX).flatten()\r\n\r\n # return the original size array\r\n return spei[0:original_length], pet_mm\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n@numba.jit\r\ndef scpdsi(precip_time_series,\r\n pet_time_series,\r\n awc,\r\n data_start_year,\r\n calibration_start_year,\r\n calibration_end_year):\r\n '''\r\n This function computes the self-calibrated Palmer Drought Severity Index (scPDSI), Palmer Drought Severity Index\r\n (PDSI), Palmer Hydrological Drought Index (PHDI), Palmer Modified Drought Index (PMDI), and Palmer Z-Index.\r\n\r\n :param precip_time_series: time series of precipitation values, in inches\r\n :param pet_time_series: time series of PET values, in inches\r\n :param awc: available water capacity (soil constant), in inches\r\n :param data_start_year: initial year of the input precipitation and PET datasets,\r\n both of which are assumed to start in January of this year\r\n :param calibration_start_year: initial year of the calibration period\r\n :param calibration_end_year: final year of the calibration period\r\n :return: four numpy arrays containing SCPDSI, PDSI, PHDI, and Z-Index values respectively\r\n '''\r\n\r\n return palmer.scpdsi(precip_time_series,\r\n pet_time_series,\r\n awc,\r\n data_start_year,\r\n calibration_start_year,\r\n calibration_end_year)\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n@numba.jit\r\ndef pdsi(precip_time_series,\r\n pet_time_series,\r\n awc,\r\n data_start_year,\r\n calibration_start_year,\r\n calibration_end_year):\r\n '''\r\n This function computes the Palmer Drought Severity Index (PDSI), Palmer Hydrological Drought Index (PHDI),\r\n and Palmer Z-Index.\r\n\r\n :param precip_time_series: time series of monthly precipitation values, in inches\r\n :param pet_time_series: time series of monthly PET values, in inches\r\n :param awc: available water capacity (soil constant), in inches\r\n :param data_start_year: initial year of the input precipitation and PET datasets,\r\n both of which are assumed to start in January of this year\r\n :param calibration_start_year: initial year of the calibration period\r\n :param calibration_end_year: final year of the calibration period\r\n :return: four numpy arrays containing PDSI, PHDI, PMDI, and Z-Index values respectively\r\n '''\r\n\r\n return palmer.pdsi(precip_time_series,\r\n pet_time_series,\r\n awc,\r\n data_start_year,\r\n calibration_start_year,\r\n calibration_end_year)\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n@numba.jit\r\ndef percentage_of_normal(values,\r\n scale,\r\n data_start_year,\r\n calibration_start_year,\r\n calibration_end_year,\r\n periodicity):\r\n '''\r\n This function finds the percent of normal values (average of each calendar month or day over a specified\r\n calibration period of years) for a specified time steps scale. The normal precipitation for each calendar time step\r\n is computed for the specified time steps scale, and then each time step's scaled value is compared against the\r\n corresponding calendar time step's average to determine the percentage of normal. The period that defines the\r\n normal is described by the calibration start and end years arguments. The calibration period typically used\r\n for US climate monitoring is 1981-2010.\r\n\r\n :param values: 1-D numpy array of precipitation values, any length, initial value assumed to be January of the data\r\n start year (January 1st of the start year if daily periodicity), see the description of the\r\n *periodicity* argument below for further clarification\r\n :param scale: integer number of months over which the normal value is computed (eg 3-months, 6-months, etc.)\r\n :param data_start_year: the initial year of the input monthly values array\r\n :param calibration_start_year: the initial year of the calibration period over which the normal average for each\r\n calendar time step is computed\r\n :param calibration_start_year: the final year of the calibration period over which the normal average for each\r\n calendar time step is computed\r\n :param periodicity: the periodicity of the time series represented by the input data, valid/supported values are\r\n 'monthly' and 'daily'\r\n 'monthly' indicates an array of monthly values, assumed to span full years, i.e. the first\r\n value corresponds to January of the initial year and any missing final months of the final\r\n year filled with NaN values, with size == # of years * 12\r\n 'daily' indicates an array of full years of daily values with 366 days per year, as if each\r\n year were a leap year and any missing final months of the final year filled with NaN values,\r\n with array size == (# years * 366)\r\n :return: percent of normal precipitation values corresponding to the scaled precipitation values array\r\n :rtype: numpy.ndarray of type float\r\n '''\r\n\r\n # if doing monthly then we'll use 12 periods, corresponding to calendar months, if daily assume years w/366 days\r\n if periodicity == 'monthly':\r\n periodicity = 12\r\n elif periodicity == 'daily':\r\n periodicity = 366\r\n else:\r\n message = 'Invalid periodicity argument: \\'{0}\\''.format(periodicity)\r\n _logger.error(message)\r\n raise ValueError(message)\r\n\r\n # bypass processing if all values are masked\r\n if np.ma.is_masked(values) and values.mask.all():\r\n return values\r\n\r\n # make sure we've been provided with sane calibration limits\r\n if data_start_year > calibration_start_year:\r\n raise ValueError('Invalid start year arguments (data and/or calibration): calibration start year ' + \\\r\n 'is before the data start year')\r\n elif ((calibration_end_year - calibration_start_year + 1) * 12) > values.size:\r\n raise ValueError('Invalid calibration period specified: total calibration years exceeds the actual ' + \\\r\n 'number of years of data')\r\n\r\n # get an array containing a sliding sum on the specified time step scale -- i.e. if the scale is 3 then the first\r\n # two elements will be np.NaN, since we need 3 elements to get a sum, and then from the third element to the end\r\n # the values will equal the sum of the corresponding time step plus the values of the two previous time steps\r\n scale_sums = compute.sum_to_scale(values, scale)\r\n\r\n # extract the timesteps over which we'll compute the normal average for each time step of the year\r\n calibration_years = calibration_end_year - calibration_start_year + 1\r\n calibration_start_index = (calibration_start_year - data_start_year) * periodicity\r\n calibration_end_index = calibration_start_index + (calibration_years * periodicity)\r\n calibration_period_sums = scale_sums[calibration_start_index:calibration_end_index]\r\n\r\n # for each time step in the calibration period, get the average of the scale sum\r\n # for that calendar time step (i.e. average all January sums, then all February sums, etc.)\r\n averages = np.full((periodicity,), np.nan)\r\n for i in range(periodicity):\r\n averages[i] = np.nanmean(calibration_period_sums[i::periodicity])\r\n\r\n #TODO replace the below loop with a vectorized implementation\r\n # for each time step of the scale_sums array find its corresponding\r\n # percentage of the time steps scale average for its respective calendar time step\r\n percentages_of_normal = np.full(scale_sums.shape, np.nan)\r\n for i in range(scale_sums.size):\r\n\r\n # make sure we don't have a zero divisor\r\n divisor = averages[i % periodicity]\r\n if divisor > 0.0:\r\n\r\n percentages_of_normal[i] = scale_sums[i] / divisor\r\n\r\n return percentages_of_normal\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------\r\n@numba.jit\r\ndef pet(temperature_celsius,\r\n latitude_degrees,\r\n data_start_year):\r\n\r\n '''\r\n This function computes potential evapotranspiration (PET) using Thornthwaite's equation.\r\n\r\n :param temperature_celsius: an array of average temperature values, in degrees Celsius\r\n :param latitude_degrees: the latitude of the location, in degrees north, must be within range [-90.0 ... 90.0] (inclusive), otherwise\r\n a ValueError is raised\r\n :param data_start_year: the initial year of the input dataset\r\n :return: an array of PET values, of the same size and shape as the input temperature values array, in millimeters/time step\r\n :rtype: 1-D numpy.ndarray of floats\r\n '''\r\n\r\n # make sure we're not dealing with all NaN values\r\n if np.ma.isMaskedArray(temperature_celsius) and temperature_celsius.count() == 0:\r\n\r\n # we started with all NaNs for the temperature, so just return the same as PET\r\n return temperature_celsius\r\n\r\n else:\r\n\r\n # we were passed a vanilla Numpy array, look for indices where the value == NaN\r\n nan_indices = np.isnan(temperature_celsius)\r\n if np.all(nan_indices):\r\n\r\n # we started with all NaNs for the temperature, so just return the same\r\n return temperature_celsius\r\n\r\n # make sure we're not dealing with a NaN or out-of-range latitude value\r\n if latitude_degrees is not None and not np.isnan(latitude_degrees) and \\\r\n (latitude_degrees < 90.0) and (latitude_degrees > -90.0):\r\n\r\n # compute and return the PET values using Thornthwaite's equation\r\n return thornthwaite.potential_evapotranspiration(temperature_celsius, latitude_degrees, data_start_year)\r\n\r\n else:\r\n message = 'Invalid latitude value: {0} (must be in degrees north, between -90.0 and 90.0 inclusive)'.format(latitude_degrees)\r\n _logger.error(message)\r\n raise ValueError(message)\r\n","sub_path":"drought_indicator/climate_indices/indices.py","file_name":"indices.py","file_ext":"py","file_size_in_byte":24678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"583784147","text":"#PolevskoyPizza.py - простой калькулятор стоимости пиццы\n\n#Спросить человека, сколько пицц он хочет,\n#получить число с помощью функции eva1()\nnumber_of_pizzas = eval(input(\"Сколько пицц вы хотите? \"))\n#Запросить стоимость пиццы по меню\ncost_per_pizza = eval(input(\"Сколько стоит пицца? \"))\n\n#Подсчитать общую стоимость пиццы как подытог\nsubtotal = number_of_pizzas * cost_per_pizza\n#Посчитать сумму налога с продаж по ставке 8% от подытога\ntax_rate = 0.08 #Сохранить 8% как добное значение 0.08\nsales_tax = subtotal * tax_rate\n\n#Пиплюсовать налог с продаж к подытогу для подчёта итога\ntotal = subtotal + sales_tax\n\n#Показать пользователю общую сумму к оплпте,\n#в том числе налог\nprint(\"Полная стоимость $\", total)\nprint(\"В том числе $\", subtotal, \" за пиццу и\")\nprint(\"$\", sales_tax, \"налог с продаж\")\ninput()\n\n","sub_path":"PolevskoyPizza.py","file_name":"PolevskoyPizza.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"111838683","text":"bl_info = {\n \"name\": \"Blender Export Script Template\",\n \"author\": \"Rumcode\",\n \"blender\": (2,7,5),\n \"version\": (0,0,1),\n \"location\": \"File > Import-Export\",\n \"description\": \"Export to my super cool format\",\n \"category\": \"Import-Export\"\n}\n\nimport bpy\nfrom .Exporter import Exporter\n\ndef menu_func(self, context):\n self.layout.operator(Exporter.bl_idname, text=\"My Format(.fmt)\")\n\ndef register():\n bpy.utils.register_module(__name__)\n bpy.types.INFO_MT_file_export.append(menu_func)\n \ndef unregister():\n bpy.utils.unregister_module(__name__)\n bpy.types.INFO_MT_file_export.remove(menu_func)\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"io_export_template/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631707203","text":"from cogs.utils import database\nfrom sys import argv\nimport asyncio\nimport os\n\nthreshold = int(argv[1])\n\ntags_db = database.Database('tags.json')\ntags_dict = tags_db.all()\nnew_db = database.Database('tags-new.json')\n\nasync def do_things():\n for tag_name, tag_info in tags_dict.items():\n if tag_info['uses'] > threshold:\n await new_db.put(tag_name, tag_info)\n\n await new_db.save()\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(do_things())\nos.remove('tags.json')\nos.rename('tags-new.json', 'tags.json')\n","sub_path":"tag_cleanup.py","file_name":"tag_cleanup.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"40727540","text":"import json\nimport operator\nimport os\nimport csv\nfrom math import log\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef list_percentage(tar):\n tot = 0\n for item in tar:\n tot += item\n\n for i, item in enumerate(tar):\n tar[i] = item / tot\n\n return tar\n\n\ndef init_main(files):\n # read sa dict.\n sa = {}\n for file in files:\n with open('./sa/'+file+'.json', 'r') as rf:\n sa_ = json.loads(rf.read())\n sa = dict(sa, **sa_)\n\n # read attr. list\n with open('./sa/data/attr.txt', 'r') as rf:\n attr = rf.readlines()\n for i, val in enumerate(attr):\n if val[-1] == '\\n':\n attr[i] = val[:-1]\n\n return sa, attr\n\n\ndef del_dependence_dict(pre, stops):\n post = {}\n\n for key in pre:\n tmp = []\n\n for i, _ in enumerate(pre[key]):\n if not i in stops:\n tmp.append(pre[key][i])\n\n post[key] = tmp\n\n return post\n\n\ndef del_dependence_list(pre, stops):\n post = []\n\n for i, _ in enumerate(pre):\n if not i in stops:\n post.append(pre[i])\n\n return post\n\n\ndef cal_weight(weight):\n tot = 0 # total count\n for i in weight:\n tot += i\n\n for i, _ in enumerate(weight):\n if weight[i] is not 0:\n weight[i] = log(tot / weight[i])\n else:\n weight[i] = 1\n\n return weight\n\n\ndef attr_sort(attr, tmp):\n # result\n ret = {}\n for i, _ in enumerate(tmp):\n ret[attr[i]] = tmp[i]\n\n return sorted(ret.items(), key=operator.itemgetter(1), reverse=True)\n\n\ndef csv_writer(OUT_PATH, limit=0):\n fw = open(OUT_PATH, 'w', newline='')\n wt = csv.writer(fw)\n\n if limit == 0:\n wt.writerow(['level', 'count'] + [num for num in range(1, 21)])\n else:\n wt.writerow(['level', 'count'] + [num for num in range(1, (limit+1))])\n\n for tar in sa_list:\n # 속성별로 tf-idf 순으로 정렬\n ret = sorted(words[attr.index(tar[0])].items(), key=operator.itemgetter(1), reverse=True)\n\n if limit == 0:\n wt.writerow([tar[0]] + [len(ret)] + [x[0] for x in ret])\n wt.writerow([tar[1]] + [''] + [x[1] for x in ret])\n else:\n wt.writerow([tar[0]] + [len(ret)] + [x[0] for x in ret][:limit])\n wt.writerow([tar[1]] + [''] + [x[1] for x in ret][:limit])\n\n fw.close()\n print(\"complete: WRITE -\", OUT_PATH)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n init\n\n sa: sa dict. - const.\n attr: list of attr. - const.\n scaler: norm. - const.\n stops: list of dependency attr. - const.\n limit: max len. of csv's rows\n \"\"\"\n stops = [0, 1, 4, 8, 16, 23, 27, 33, 38, 43] # 종속적인/값이없는 속성 제외\n limit = 20\n\n sa, attr = init_main(['close_0', 'open_0'])\n sa = del_dependence_dict(sa, stops)\n attr = del_dependence_list(attr, stops)\n num_ = len(attr)\n\n scaler = MinMaxScaler(feature_range=(0, 1))\n\n \"\"\"\n LOOP\n \"\"\"\n years = list(range(2000, 2018)) # years range: 2000 ~ 2017\n keywords = ['불행', '행복']\n\n for year in years:\n for keyword in keywords:\n\n \"\"\"\n read tf-idf\n \"\"\"\n tfidf = {}\n with open('./tfidf' + '/' + str(year) + '/' + keyword + '.txt', 'r', encoding='UTF-8') as rf:\n while True:\n name = rf.readline()[:-1]\n val = rf.readline()[:-1]\n if name == '' and val == '':\n break\n \n if float(val) != 0.0:\n tfidf[name] = float(val) # except what tf-idf is 0.0\n \n rf.readline()\n\n \"\"\"\n most dominated attr.\n \n words: 속성마다 속하는 단어 list-tfidf 쌍을 저장\n \"\"\"\n tmp = []\n for i in range(num_):\n tmp.append(0)\n\n weight = []\n for i in range(num_):\n weight.append(0)\n\n words = []\n for i in range(num_):\n words.append({})\n\n # cal\n for key in tfidf:\n if key in sa:\n for i, _ in enumerate(sa[key]):\n if sa[key][i] == 1:\n tmp[i] += tfidf[key]\n weight[i] += 1\n (words[i])[key] = tfidf[key]\n\n weight = cal_weight(weight)\n for i, _ in enumerate(tmp):\n tmp[i] *= weight[i] # apply weight\n\n \"\"\"\n result\n \n sa_list: series(list) of most influential attr.\n \"\"\"\n # tmp = list_percentage(tmp) # percentage\n tmp = list((scaler.fit_transform(np.array(tmp).reshape(-1, 1)).reshape(1, -1))[0])\n\n sa_list = [x for x in attr_sort(attr, tmp)]\n # print(year, keyword, [x[0] for x in attr_sort(attr, tmp)])\n\n \"\"\"\n words list per attr.\n \"\"\"\n OUT_PATH = './sa/csv/' + str(year) + '_' + keyword + '.csv'\n if not os.path.exists('./sa/csv'):\n os.makedirs('./sa/csv')\n csv_writer(OUT_PATH, limit=0)\n\n OUT_PATH = './sa/csv_limit/' + str(year) + '_' + keyword + '.csv'\n if not os.path.exists('./sa/csv_limit'):\n os.makedirs('./sa/csv_limit')\n csv_writer(OUT_PATH, limit=limit) # apply limit\n","sub_path":"sa_apply.py","file_name":"sa_apply.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"301865613","text":"# Сетка\n\n\"\"\"\n\nКоманда grid рисует сетку:\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx=np.linspace(-10,10,50)\nplt.plot(x,np.sin(x)/x)\nplt.plot(x,1-x**2/6)\nplt.plot(x,1-x**2/6+x**4/120)\nplt.ylim(-0.3,1.1)\nplt.legend(('f(x)','Teylor 3','Taylor 5'),shadow=True, fancybox=True)\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.text(-9.0,0.16,'Maximum')\nplt.grid()\nplt.show()","sub_path":"Machine_Learning/matplotlib/lab4.6-grid.py","file_name":"lab4.6-grid.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"590030220","text":"#!/usr/bin/python3\n\"\"\" Module for testing file storage\"\"\"\nfrom models.engine.file_storage import FileStorage\nfrom models.engine import file_storage\nfrom os import environ\nimport models\nimport pep8\nimport unittest\n\nFileStorage = file_storage.FileStorage\nstorage_type = environ[\"HBNB_TYPE_STORAGE\"]\n\n\nclass test_fileStorage(unittest.TestCase):\n \"\"\" Class to test the file storage method \"\"\"\n @unittest.skipIf(storage_type == 'db', \"no testing file storage\")\n def test_all_returns_dict(self):\n \"\"\"Test return the FileStorage.__objects\"\"\"\n storage = FileStorage()\n new_dict = storage.all()\n self.assertEqual(type(new_dict), dict)\n self.assertIs(new_dict, storage._FileStorage__objects)\n\n\nclass TestFileStorageDocs(unittest.TestCase):\n \"\"\" Test Place documentation and pep8 \"\"\"\n\n def test_pep8_FileStorage(self):\n \"\"\" Test models/engine/file_storage.py PEP8 \"\"\"\n pep8s = pep8.StyleGuide(quiet=True)\n result = pep8s.check_files(['models/engine/file_storage.py'])\n self.assertEqual(result.total_errors, 0)\n\n def test_pep8_test_FileStorage(self):\n \"\"\" Test tests/test_models/test_engine/test_storage.py PEP8 \"\"\"\n pep8s = pep8.StyleGuide(quiet=True)\n result = pep8s.check_files(\n ['tests/test_models/test_engine/test_file_storage.py'])\n self.assertEqual(result.total_errors, 0)\n\n def test_docstring_FileStorage_module(self):\n \"\"\" Test file_storage.py module docstring \"\"\"\n self.assertIsNot(file_storage.__doc__, None)\n self.assertTrue(len(file_storage.__doc__) >= 1)\n\n def test_docstring_FileStorage_class(self):\n \"\"\"Test FileStorage class docstring \"\"\"\n self.assertIsNot(file_storage.__doc__, None)\n self.assertTrue(len(file_storage.__doc__) >= 1)\n","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341429343","text":"from sklearn.metrics import accuracy_score, precision_score, recall_score\n\n\nclass RegressorStats:\n @staticmethod\n def get_stats(y_real, y_pred):\n precision = precision_score(y_real, y_pred, average='macro')\n recall = recall_score(y_real, y_pred, average='macro')\n\n return {\n 'accuracy': accuracy_score(y_real, y_pred),\n 'precision': precision,\n 'recall': recall,\n 'f0.5': RegressorStats.f_beta_score(precision, recall, beta=0.5),\n 'f1': RegressorStats.f_beta_score(precision, recall, beta=1),\n 'f2': RegressorStats.f_beta_score(precision, recall, beta=2)\n }\n\n\n @staticmethod\n def f_beta_score(precision, recall, beta=1):\n beta_sq = beta ** 2\n\n return (1 + beta_sq) * precision * recall / (beta_sq * precision + recall)\n\n\n @staticmethod\n def mean_error(regressors, value):\n sum = 0\n total = 0\n\n for regressor in regressors:\n sum += regressor[value][regressor['final_iteration']]\n total += 1\n\n return sum / total\n","sub_path":"Projeto3/metric/regressor_stats.py","file_name":"regressor_stats.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"627777145","text":"from math import *\n\n#función original\ndef fx(x):\n aux= x**2+x-2\n return aux\n#función despejada\ndef gx(x):\n aux= sqrt(2-x)\n return aux\n#=====================#\n# Programa Punto Fijo \n# x0: punto inicial\n# xk: punto medio\n# gx: función a obtener la raiz\n# tol: tolerancia\n# ERA: error aproximado \n# nk: número máximo de iteraciones\n# \ndef puntofijo(fx,gx,x0,tol,nk):\n print(\"iter\",\"x0\",\" \",\"xk\",\" \",\"ERA\", \" \", \"f(xk)\" )\n for i in range(1,nk):\n xk = gx(x0)\n ERA = 100*abs(xk-x0)/abs(xk) # xk diferente de cero\n print(i, round(x0,6), \" \",round(xk,6), \" \", round(ERA,3),\" \", round(abs(fx(xk)),5) )\n x0=xk # actualizando \n if(ERA 2:\n raise ValueError('Found multiple entities for {:s}'.format(\n entity_repr(entity_type, entity_spec)))\n elif len(stdout_lines) == 1:\n raise RuntimeError('Called entity_needs_modify() for {:s}, but it does not exist'.format(\n entity_repr(entity_type, entity_spec)))\n\n keys = [k.strip().lower() for k in stdout_lines[0].strip().split('|')]\n values = [v.strip() for v in stdout_lines[1].strip().split('|')]\n\n if entity_type == 'account':\n # XXX input is \"description\" but output is \"descr\"\n keys = [k if k != 'descr' else 'description' for k in keys]\n\n if entity_type == 'user':\n # XXX input is \"defaultaccount\" but output is \"def acct\"\n keys = [k if k != 'def acct' else 'defaultaccount' for k in keys]\n\n if entity_type == 'association':\n # XXX input is \"defaultqos\" but output is \"def qos\"\n keys = [k if k != 'def qos' else 'defaultqos' for k in keys]\n\n existing_spec = dict(zip(keys, values))\n\n if entity_type == 'account' and 'parent' in entity_spec:\n existing_spec['parent'] = get_account_parent(entity_spec['account'])\n\n for key, new_value in entity_spec.items():\n if new_value != existing_spec[key]:\n logger.debug('key=\"{:s}\" existing_value=\"{:s}\" new_value=\"{:s}\"'.format(key, existing_spec[key], new_value))\n return True\n\n return False\n\n\ndef modify_entity(entity_type, entity_spec):\n args = ['sacctmgr', 'modify', '-i', ENTITY_TYPE_MAP[entity_type], 'where']\n for id_field in ENTITY_ID_FIELDS[entity_type]:\n args.append('{:s}={:s}'.format(id_field, entity_spec[id_field]))\n args.append('set')\n for key, value in entity_spec.items():\n if key not in ENTITY_ID_FIELDS[entity_type]:\n args.append('{:s}={:s}'.format(key, value))\n run_cmd(args)\n\n\ndef create_or_modify_entity(entity_type, entity_spec, dry_run=False):\n r = entity_repr(entity_type, entity_spec)\n\n if not entity_exists(entity_type, entity_spec):\n if dry_run:\n logger.warning('Would create {:s}.'.format(r))\n return\n create_entity(entity_type, entity_spec)\n if entity_exists(entity_type, entity_spec):\n logger.warning('Created {:s}.'.format(r))\n else:\n logger.error('Tried to create {:s}, but it did not do anything.'.format(r))\n elif entity_needs_modify(entity_type, entity_spec):\n if dry_run:\n logger.warning('Would modify {:s}.'.format(r))\n return\n modify_entity(entity_type, entity_spec)\n if entity_needs_modify(entity_type, entity_spec):\n logger.error('Tried to modify {:s}, but it did not do anything.'.format(r))\n else:\n logger.warning('Modified {:s}.'.format(r))\n else:\n logger.info('{:s} is up-to-date.'.format(r))\n\n\ndef list_entities(entity_type):\n args = [\n 'sacctmgr', 'list', '-P', ENTITY_TYPE_MAP[entity_type],\n 'format={:s}'.format(','.join(ENTITY_ID_FIELDS[entity_type])),\n ]\n if entity_type == 'association':\n args.append('withassoc')\n result = run_cmd(args)\n\n stdout_lines = result.stdout.strip().split('\\n')\n keys = [k.strip().lower() for k in stdout_lines[0].strip().split('|')]\n return [\n dict(zip(\n keys,\n [v.strip() for v in row.strip().split('|')],\n ))\n for row in stdout_lines[1:]\n ]\n\n\ndef delete_entity(entity_type, entity_spec, dry_run=False):\n r = entity_repr(entity_type, entity_spec)\n\n if dry_run:\n logger.warning('Would delete {:s}.'.format(r))\n return\n\n args = ['sacctmgr', 'delete', '-i', ENTITY_TYPE_MAP[entity_type], 'where']\n for id_field in ENTITY_ID_FIELDS[entity_type]:\n args.append('{:s}={:s}'.format(id_field, entity_spec[id_field]))\n subprocess.run(args, check=True)\n if entity_exists(entity_type, entity_spec):\n logger.error('Tried to delete {:s}, but it did not do anything.'.format(r))\n else:\n logger.warning('Deleted {:s}.'.format(r))\n\n\ndef main():\n p = argparse.ArgumentParser()\n p.add_argument('json_file')\n p.add_argument('--delete', action='store_true',\n help=\"Delete unrecognized entities\")\n p.add_argument('--dry-run', action='store_true',\n help=\"Only print changes that would be made - don't take any actions\")\n args = p.parse_args()\n\n data = parse_input(args.json_file)\n\n for entity_type in data.keys():\n if entity_type not in ENTITY_ID_FIELDS:\n raise ValueError('Entity type {:s} not supported.'.format(entity_type))\n\n # create or modify\n for entity_type in ENTITY_ID_FIELDS.keys():\n if entity_type in data:\n assert isinstance(data[entity_type], list)\n for entity in data[entity_type]:\n assert isinstance(entity, dict)\n create_or_modify_entity(entity_type, entity, dry_run=args.dry_run)\n\n # delete\n if args.delete:\n for entity_type in reversed(ENTITY_ID_FIELDS.keys()):\n new_entities = data.get(entity_type, [])\n for existing_entity in list_entities(entity_type):\n # FIXME N^2 runtime\n should_delete = True\n for new_entity in new_entities:\n matches = True\n for field in ENTITY_ID_FIELDS[entity_type]:\n if new_entity[field] != existing_entity[field]:\n matches = False\n break\n if matches:\n should_delete = False\n break\n if should_delete:\n delete_entity(entity_type, existing_entity, dry_run=args.dry_run)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"roles/slurm-perf/templates/etc/slurm/shared/bin/sacctmgr_wrapper_migrate_data.py","file_name":"sacctmgr_wrapper_migrate_data.py","file_ext":"py","file_size_in_byte":10211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27263028","text":"from datetime import datetime, timedelta\n\nfrom utils import Session, permission_test\n\nsample_sync = {\n \"name\": \"name\",\n \"course\": \"CS-UY 3224\",\n \"hidden\": True,\n \"github_template\": \"wabscale/xv6-public\",\n \"github_repo_required\": True,\n \"unique_code\": \"aa11bb22\",\n \"pipeline_image\": \"registry.digitalocean.com/anubis/assignment/aa11bb2233\",\n \"date\": {\n \"release\": str(datetime.now() - timedelta(hours=2)),\n \"due\": str(datetime.now() + timedelta(hours=12)),\n \"grace\": str(datetime.now() + timedelta(hours=13)),\n },\n \"description\": \"This is a very long description that encompasses the entire assignment\\n\",\n \"questions\": [\n {\"pool\": 1, \"questions\": [{\"q\": \"What is 3*4?\", \"a\": \"12\"}, {\"q\": \"What is 3*2\", \"a\": \"6\"}]},\n {\"pool\": 2, \"questions\": [{\"q\": \"What is sqrt(144)?\", \"a\": \"12\"}]}\n ],\n \"tests\": [\"abc123\"],\n}\n\n\ndef test_assignment_admin():\n superuser = Session('superuser')\n\n permission_test('/admin/assignments/list')\n\n assignment = superuser.get('/admin/assignments/list')['assignments'][0]\n assignment_id = assignment['id']\n _tests = superuser.get(f'/admin/assignments/get/{assignment_id}')['tests']\n assignment_test_id = _tests[0]['id']\n\n permission_test(f'/admin/assignments/get/{assignment_id}')\n permission_test(f'/admin/assignments/assignment/{assignment_id}/questions/get/student')\n permission_test(f'/admin/assignments/tests/toggle-hide/{assignment_test_id}')\n permission_test(f'/admin/assignments/save', method='post', json={'assignment': assignment})\n permission_test(f'/admin/assignments/sync', method='post', json={'assignment': sample_sync})\n","sub_path":"api/tests/test_assignment_admin.py","file_name":"test_assignment_admin.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"312450398","text":"#! /usr/bin/env python\n# encoding: utf-8\n# Thomas Zellman 2009\n\ntop = '.'\nout = 'build'\n\ndef set_options(opt):\n\topt.tool_options('compiler_cc')\n\topt.tool_options('javaw')\n\ndef configure(conf):\n\tconf.check_tool('compiler_cc')\n\tconf.check_tool('java')\n\n\t# on mandriva, at least, libjvm.so is difficult to find\n\t#conf.env.LIBPATH_JAVA = \"/usr/lib/jvm/java-1.6.0-sun-1.6.0.13/jre/lib/amd64/server/\"\n\tconf.check_jni_headers()\n\ndef build(bld):\n\tbld(features='javac seq', source_root='src/java')\n\tbld(features='jar seq', basedir='src/java',\n\t\t\t\t\tdestfile='stringUtils.jar')\n\n\tlib = bld(features='cc cshlib',\n\t\t\t\t\t\t\tincludes='src/jni/include',\n\t\t\t\t\t\t\ttarget='stringUtils',\n\t\t\t\t\t\t\tuselib='JAVA')\n\tlib.find_sources_in_dirs('src/jni/source')\n\n","sub_path":"demos/jni/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"69832749","text":"import json\nimport unittest\n\nfrom sauth.tests.helpers import make_user\nfrom sfile.tests.helpers import make_file\n\nfrom dvlp.tests import helpers as TH\nfrom dvlp.spreadsheet import main\nfrom dvlp.spreadsheet import model as M\n\n\nclass TestEmpty(unittest.TestCase):\n\n def setUp(self):\n self.api = TH.configure_functional_oauth_app(main.main)\n self.user = make_user(\n oauth=[dict(client_id=None, token='token-value')],\n password='foobar')\n self.api.authorize('token-value')\n\n def test_root(self):\n res = self.api.get('/1.0/', status=200)\n self.assertEqual(\n res.json, dict(user='test@example.com', version='1.0'))\n\n def test_lists(self):\n res = self.api.get('/1.0/list/', status=200)\n self.assertEqual(res.json, dict(lists=[]))\n\n def test_list_from_url(self):\n f = make_file(\n self.user, 'test.csv',\n 'test@example.com\\n')\n mapping = dict(header=False, sheet=0, email=0)\n res = self.api.post(\n '/1.0/list/',\n params=json.dumps(dict(\n file_nonce=f.metadata.nonce,\n mapping=mapping)),\n status=201)\n self.assertEqual(res.json['mapping'], mapping)\n\n\nclass TestWithList(unittest.TestCase):\n\n def setUp(self):\n self.api = TH.configure_functional_oauth_app(main.main)\n self.user = make_user(\n oauth=[dict(client_id=None, token='token-value')],\n password='foobar')\n self.api.authorize('token-value')\n content1 = '\\n'.join([\n 'id,name,email',\n 'r1,Example1,test1@example.com',\n 'r2,Example2,test2@example.com',\n 'r3,Example3,test3@example.com',\n 'r4,Example4,test4@example.com'])\n content2 = '\\n'.join([\n 's1,Example1,test1@example.com',\n 's2,Example2,test2@example.com',\n 's3,Example3,test3@example.com',\n 's4,Example4,test4@example.com'])\n f1 = make_file(\n self.user, 'test.csv',\n content=content1)\n f2 = make_file(\n self.user, 'test.csv',\n content=content2)\n self.lst1 = TH.make_list(\n self.user, f1,\n mapping=dict(header=True, sheet=0, email=2))\n self.lst2 = TH.make_list(\n self.user, f2,\n mapping=dict(header=False, sheet=0, email=2))\n\n def test_lists(self):\n res = self.api.get('/1.0/list/', status=200)\n self.assertEqual(len(res.json['lists']), 2)\n res_lst = res.json['lists'][0]\n self.assertIn('mapping', res_lst)\n\n def test_get_list(self):\n res = self.api.get(\n str('/1.0/list/%s/' % self.lst1._id),\n status=200)\n self.assertIn('mapping', res.json)\n\n def test_remap_list(self):\n mapping = dict(header=True, sheet=4, email=1)\n res = self.api.put(\n str('/1.0/list/%s/mapping/' % self.lst1._id),\n params=json.dumps(mapping),\n status=200)\n self.assertEqual(res.json, mapping)\n\n def test_delete_list(self):\n res = self.api.delete(\n str('/1.0/list/%s/' % self.lst1._id),\n status=204)\n self.assertEqual(\n M.List.query.find(dict(status='active')).count(), 1)\n self.assertEqual(\n M.List.query.find(dict(status='inactive')).count(), 1)\n res = self.api.get('/1.0/list/', status=200)\n self.assertEqual(len(res.json['lists']), 1)\n\n def test_get_subscribers(self):\n res = self.api.get(\n str('/1.0/list/%s/subscribers.csv' % self.lst1._id))\n self.assertEqual(\n res.body,\n '1,test1@example.com\\r\\n'\n '2,test2@example.com\\r\\n'\n '3,test3@example.com\\r\\n'\n '4,test4@example.com\\r\\n')\n\n def test_get_subscribers_nohdr(self):\n res = self.api.get(\n str('/1.0/list/%s/subscribers.csv' % self.lst2._id))\n self.assertEqual(\n res.body,\n '1,test1@example.com\\r\\n'\n '2,test2@example.com\\r\\n'\n '3,test3@example.com\\r\\n'\n '4,test4@example.com\\r\\n')\n\n def test_append_list(self):\n content = '\\n'.join([\n '0,A,B,C,D',\n '1,a,b,c,d',\n '2,a,b,c,d',\n '3,a,b,c,d',\n '4,a,b,c,d',\n ])\n f = make_file(\n self.user, 'test-appended.csv',\n content=content)\n self.api.post(\n str('/1.0/list/%s/' % self.lst1._id),\n params=json.dumps(dict(file_nonce=f.metadata.nonce)),\n status=200)\n res = self.api.get(\n str('/1.0/list/%s/appended.csv' % self.lst1._id),\n status=200)\n self.assertEqual(\n res.body,\n '0,A,B,C,D,id,name,email\\r\\n'\n '1,a,b,c,d,r1,Example1,test1@example.com\\r\\n'\n '2,a,b,c,d,r2,Example2,test2@example.com\\r\\n'\n '3,a,b,c,d,r3,Example3,test3@example.com\\r\\n'\n '4,a,b,c,d,r4,Example4,test4@example.com\\r\\n')\n\n def test_append_list_nohdr(self):\n content = '\\n'.join([\n '0,A,B,C,D',\n '1,a,b,c,d',\n '2,a,b,c,d',\n '3,a,b,c,d',\n '4,a,b,c,d',\n ])\n f = make_file(\n self.user, 'test-appended.csv',\n content=content)\n self.api.post(\n str('/1.0/list/%s/' % self.lst2._id),\n params=json.dumps(dict(file_nonce=f.metadata.nonce)),\n status=200)\n res = self.api.get(\n str('/1.0/list/%s/appended.csv' % self.lst2._id),\n status=200)\n self.assertEqual(\n res.body,\n '0,A,B,C,D\\r\\n'\n '1,a,b,c,d,s1,Example1,test1@example.com\\r\\n'\n '2,a,b,c,d,s2,Example2,test2@example.com\\r\\n'\n '3,a,b,c,d,s3,Example3,test3@example.com\\r\\n'\n '4,a,b,c,d,s4,Example4,test4@example.com\\r\\n')\n\n\n\n","sub_path":"dvlp/tests/functional/test_functional_spreadsheet.py","file_name":"test_functional_spreadsheet.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"126244745","text":"\nimport os\nimport sys\nimport yaml\n\nfrom os.path import abspath, \\\n expanduser, \\\n realpath, \\\n samefile, \\\n islink\n\nRED=1\nGREEN=2\nBLUE=4\n\ncwd = None\nfiles = None\n\ndef current_dir():\n global cwd\n cwd = cwd or os.path.realpath(os.getcwd() + '/files')\n return cwd \n\ndef print_colored(args, end = \"\\n\"):\n print( \"\\033[1;3%dm %-18s \\033[0m %s \" % args, end=end)\n\ndef get_files():\n global files \n files = files or sorted(os.listdir(current_dir()))\n return files\n\ndef get_custom_rules():\n custom = None\n if os.path.exists('__custom'):\n custom = yaml.load( open('__custom') )\n return custom\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"593121577","text":"\"\"\"A library that contains a function for creating the extra set.\"\"\"\n\nimport numpy\nimport os\n\nimport tools.tools as tls\n\ndef create_extra(path_to_root, width_crop, nb_extra, path_to_extra):\n \"\"\"Creates the extra set.\n \n RGB images are converted into luminance images.\n Then, the luminance images are cropped. Finally,\n the extra set is filled with the luminance crops\n and it is saved.\n \n Parameters\n ----------\n path_to_root : str\n Path to the folder containing RGB images.\n width_crop : int\n Width of the crop.\n nb_extra : int\n Number of luminance crops in the\n extra set.\n path_to_extra : str\n Path to the file in which the extra set\n is saved. The path must end with \".npy\".\n \n Raises\n ------\n RuntimeError\n If there are not enough RGB images\n to create the extra set.\n \n \"\"\"\n if os.path.isfile(path_to_extra):\n print('\"{}\" already exists.'.format(path_to_extra))\n print('Delete it manually to recreate the extra set.')\n else:\n luminances_uint8 = numpy.zeros((nb_extra, width_crop, width_crop, 1), dtype=numpy.uint8)\n list_names = os.listdir(path_to_root)\n i = 0\n extensions = ('jpg', 'JPEG', 'png')\n for name in list_names:\n if name.endswith(extensions):\n path_to_rgb = os.path.join(path_to_root, name)\n try:\n rgb_uint8 = tls.read_image_mode(path_to_rgb,\n 'RGB')\n crop_uint8 = tls.crop_option_2d(tls.rgb_to_ycbcr(rgb_uint8)[:, :, 0],\n width_crop,\n False)\n except (TypeError, ValueError) as err:\n print(err)\n print('\"{}\" is skipped.\\n'.format(path_to_rgb))\n continue\n luminances_uint8[i, :, :, 0] = crop_uint8\n i += 1\n if i == nb_extra:\n break\n \n # If the previous loop was not broken,\n # `luminances_uint8` is not full. In\n # this case, the program crashes as the\n # extra set should not contain any \"zero\"\n # luminance crop.\n if i != nb_extra:\n raise RuntimeError('There are not enough RGB images at \"{}\" to create the extra set.'.format(path_to_root))\n numpy.save(path_to_extra, luminances_uint8)\n\n\n","sub_path":"kodak_tensorflow/datasets/extra/extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"469053332","text":"import pandas as pd\nimport numpy as np\nimport math\n\n# Import hurricane data\nHurricane_nyc = pd.read_csv(\"/Users/farukhsaidmuratov/PycharmProjects/CallForCodeTeamWeatherPrediction/HurricaneNYCDataSet.csv\")\n\n# Drop data columns not relevant to severity in terms of socio-economics\nHurricane_nyc = Hurricane_nyc.drop(labels=[\"Category_UL\", \"Humidity_UL(Relative Humidity)\", \"Total_Duration(estimated_hours)\", \"Name\", \"SST_UL(F)\", \"WindSpeed_UL(mph)\"], axis=1)\n\n# Extract date\nHurricane_nyc[\"Date\"] = Hurricane_nyc[\"Date\"].str.slice(-4)\n\n# Get frequency of date\nfreq = Hurricane_nyc[\"Date\"].value_counts().sort_index()\n\n# Fill in years without any count with 0\nyears = list(range(2000, 2018))\nfor y in years:\n if str(y) not in freq.index:\n freq[str(y)] = 0\nfreq = pd.DataFrame(freq.sort_index())\n\n# Create dataframe to hold years from 2000-2017\nS_se = pd.DataFrame()\nS_se[\"Year\"] = list(range(2000, 2018))\n\nfreq = freq.reset_index()\n# Concatenate date\nS_se = pd.concat([S_se, freq], axis=1)\n\nS_se = S_se.drop(labels=\"index\", axis=1)\n\n# Rename frequency column\nS_se = S_se.rename(index=str, columns={\"Date\": \"Frequency\"})\nS_se.to_csv(path_or_buf=\"S_se.csv\", index=False)\n\n# Calculations for S_se done by hand \n'''\n# Get distance from average frequency compared to that year\nS_se[\"S_se\"] = np.where(S_se[\"Frequency\"] > 0, Hurricane_nyc[\"Fatalities\"]**2 + Hurricane_nyc[\"Economic_Loss(USD million estimated)\"]**2, 0)\n\nS_se.to_csv(path_or_buf=\"S_se.csv\", index=False)\n'''\n","sub_path":"SseScoreCalc.py","file_name":"SseScoreCalc.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"520342945","text":"# coding: UTF-8\n\n# モジュールのインポート\nimport urllib.request as req\nfrom bs4 import BeautifulSoup\n\n# import time\n\n# スクレイピングするURLを設定\nurl = \"https://www.amazon.co.jp/s/ref=nb_sb_noss_2?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&url=search-alias%3Daps&field-keywords=python\"\n\n# そのURLのオブジェクトを生成\nwebpage = req.urlopen(url)\nprint(webpage)\n\n# BeautifulSoupを使って解析\nsoup = BeautifulSoup(webpage, 'html.parser')\n# result = soup.find(\"img\").select(\".hogehoge-class\")\nresult = soup.select(\".a-size-base-plus.a-color-base.a-text-normal\")\n\n# 結果を標準出力に出力\nprint(result)\n","sub_path":"scraping1.py","file_name":"scraping1.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"204781721","text":"import pandas as pd\nimport numpy as np\nimport glob\nimport os \nimport MySQLdb\n\n\n# Change this to your directory\nfiledir = \"/Users/liangjh/Downloads/FNMA-loanperf/\"\n\n# Load database connection\n# Change this to your specific database parameters\n# print(\"Loading database connection...\")\ndb_conn = MySQLdb.connect(host = \"localhost\", user = \"root\", db = \"resi_collateral\")\n\n#\n# LOAD PERFORMANCE FILES\n#\n\nperformance_files = glob.glob(filedir + \"*Performance*.txt\")\nfor filename in performance_files:\n print(\"Loading file: \" + filename)\n df = pd.read_csv(filename, sep = \"|\", header = None, usecols = list(range(0,26)))\n df.columns = [ \"loan_id\", \"monthly_report_period\", \"servicer_name\", \n \"curr_rate\", \"curr_upb\", \"age\", \"months_to_maturity_legal\",\n \"months_to_maturity_adj\", \"maturity_date\", \"msa\",\n \"curr_delq_status\", \"mod_flag\", \"zero_bal_code\", \"zero_bal_eff_date\",\n \"last_paid_install_date\", \"fcl_date\", \"disp_date\", \"fcl_cost\", \"prop_pres_cost\",\n \"asset_recov_cost\", \"misc_expenses\", \"tax_holding_prop\", \"net_sale_proceeds\",\n \"crd_enh_proceeds\", \"repurchase_proceeds\", \"other_fcl_proceeds\"\n ]\n \n df[\"monthly_report_period\"] = pd.to_datetime(df[\"monthly_report_period\"], format = \"%m/%d/%Y\")\n df[\"maturity_date\"] = pd.to_datetime(df[\"maturity_date\"], format = \"%m/%Y\")\n df[\"zero_bal_eff_date\"] = pd.to_datetime(df[\"zero_bal_eff_date\"], format = \"%m/%Y\")\n df[\"last_paid_install_date\"] = pd.to_datetime(df[\"last_paid_install_date\"], format = \"%m/%d/%Y\")\n df[\"fcl_date\"] = pd.to_datetime(df[\"fcl_date\"], format = \"%m/%d/%Y\")\n df[\"disp_date\"] = pd.to_datetime(df[\"disp_date\"], format = \"%m/%d/%Y\")\n \n pd.io.sql.write_frame(df, con = db_conn, name = \"loan_performance\", flavor = \"mysql\", if_exists = \"append\", chunksize = 1001)\n\n\n\n\n\n","sub_path":"fnma_analysis/load_fnma_files_perf.py","file_name":"load_fnma_files_perf.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"235842495","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport localflavor.us.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('credits', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DataDisplayAccessRequest',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=64)),\n ('title', models.CharField(max_length=128)),\n ('affiliation', models.CharField(max_length=128, verbose_name=b'Institution or Affiliation')),\n ('city_state', models.CharField(max_length=64, verbose_name=b'City/State')),\n ('email', models.EmailField(max_length=75)),\n ('summary', models.TextField(verbose_name=b'Summary description of your research')),\n ('how_data_used', models.TextField(verbose_name=b'How will STARS data be used in your research?')),\n ('will_publish', models.BooleanField(default=False, verbose_name=b'Click here if you will be distributing or publishing the data?')),\n ('audience', models.TextField(verbose_name=b'Who is the intended audience for your research?')),\n ('period', models.DateField(verbose_name=b'Requesting access starting on this date (mm/dd/yyyy)')),\n ('end', models.DateField(verbose_name=b'Access requested until (mm/dd/yyyy)')),\n ('has_instructor', models.BooleanField(default=False, verbose_name=b'Is there an academic instructor or advisor who will provide guidance on how this data will be used?')),\n ('instructor', models.TextField(null=True, verbose_name=b'If yes, list name of instructor, title of instructor, and e-mail address.', blank=True)),\n ('date', models.DateField(auto_now_add=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EligibilityQuery',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=64)),\n ('title', models.CharField(max_length=128)),\n ('email', models.EmailField(max_length=75)),\n ('institution', models.CharField(max_length=128)),\n ('requesting_institution', models.CharField(max_length=128, null=True, blank=True)),\n ('other_affiliates', models.BooleanField(default=False)),\n ('included_in_boundary', models.BooleanField(default=False)),\n ('separate_administration', models.BooleanField(default=False)),\n ('rationale', models.TextField()),\n ('date', models.DateTimeField(auto_now_add=True, null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SteeringCommitteeNomination',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=16)),\n ('last_name', models.CharField(max_length=16)),\n ('email', models.EmailField(max_length=75)),\n ('affiliation', models.CharField(max_length=128, verbose_name=b'Institution or Affiliation')),\n ('phone_number', localflavor.us.models.PhoneNumberField(max_length=20)),\n ('why', models.TextField(verbose_name=b'Why would you be excited to serve on the STARS Steering Committee?')),\n ('skills', models.TextField(verbose_name=b'What specific skills or background would you bring to the STARS Steering Committee that would help advance STARS?')),\n ('successful', models.TextField(verbose_name=b'How can you help STARS become a successful rating system?')),\n ('strengths', models.TextField(verbose_name=b'What do you consider to be the strengths and weaknesses of STARS?')),\n ('perspectives', models.TextField(verbose_name=b'What perspectives or representation of stakeholder groups would you bring to the STARS Steering Committee?')),\n ('resume', models.FileField(max_length=255, upload_to=b'sc_apps')),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='TAApplication',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=16)),\n ('last_name', models.CharField(max_length=16)),\n ('title', models.CharField(max_length=64)),\n ('department', models.CharField(max_length=64)),\n ('institution', models.CharField(max_length=128, verbose_name=b'Institution/Organization Affiliation')),\n ('phone_number', localflavor.us.models.PhoneNumberField(max_length=20)),\n ('email', models.EmailField(max_length=75)),\n ('instituion_type', models.CharField(max_length=32, verbose_name=b'Institution/Organization Type', choices=[(b'2-year', b\"2-year Associate's College\"), (b'baccalaureate', b'Baccalaureate College'), (b'masters', b\"Master's Institution\"), (b'research', b'Research University'), (b'non-profit', b'Non-profit Organization'), (b'gov', b'Government Agency'), (b'for-profit', b'For-profit Business'), (b'other', b'Other')])),\n ('skills_and_experience', models.TextField()),\n ('related_associations', models.TextField()),\n ('resume', models.FileField(max_length=255, upload_to=b'ta_apps')),\n ('credit_weakness', models.TextField(null=True, blank=True)),\n ('date_registered', models.DateTimeField(auto_now_add=True)),\n ('subcategories', models.ManyToManyField(to='credits.Subcategory')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"stars/apps/custom_forms/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"167103905","text":"#! /home/cristopher/Enthought/Canopy_64bit/User/bin/python\n\nimport curses\nfrom curses import wrapper\nfrom curses.textpad import Textbox, rectangle\nimport time\nfrom sets import Set\nimport thread\nimport random\nfrom pyfiglet import figlet_format\nfrom itertools import chain, repeat, islice\nimport os.path\nfrom exparser import *\n\n## Workings\n## buf holds a list of \"blocks\"\n## Each \"block\" holds a list of \"lines\"\n## Each \"line\" holds a string\n## When the up arrow is pressed when the cursor is at y0\n#### The offset changes, same for \"down\"\nclass Cursor:\n\tdef __init__(self, y, x):\n\t\tself.y = y\n\t\tself.x = x\n\ndef main(stdscr):\n\tmyscreen = curses.initscr()\n\tcurses.start_color()\n\tcurses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)\n\tcurses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)\n\tcurses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)\n\tcurses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\tcurses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_RED)\n\tbuf = []\n\tbufN = 0\n\tbuf.append([[\"\" for n in range(4095)]])\n\toffset = 0\n\toffsetX = 0\n\tcursor = Cursor(1,0)\n\tkey = 0\n\tmode = 0\n\tprog_run = 1\n\tsave_name = \"\"\n\tprev_x = 0\n\tprev_y = 0\n\tcurses.mousemask(1)\n\tcurses.raw()\n\tinitalize()\n\n\tdef saveFile(name):\n\t\tif os.path.isfile(name):\n\t\t\tf = open(name,'r+')\n\t\telse: \n\t\t\tf = file(name,'w')\n\t\tfor line in buf[0][0]:\n\t\t\tif len(line) > 1:\n\t\t\t\tif line.startswith('\\n'):\n\t\t\t\t\tf.write('\\n')\n\t\t\t\telif not line.endswith('\\n'):\n\t\t\t\t\tf.write(line + '\\n')\n\t\tf.close\n\n\tdef openFile(name):\n\t\tif os.path.isfile(name):\n\t\t\tf = open(name,'r+')\n\t\t\tl = f.readlines()\n\t\t\tif len(l) > 4025:\n\t\t\t\tn = len(l) - 4025\n\t\t\t\tbuf.append([[\"\" for n in range(n)]])\n\t\t\tfor line in range(len(l)):\n\t\t\t\tif l[line].startswith('\\n'):\n\t\t\t\t\tcontinue\n\t\t\t\tif l[line].endswith('\\n'):\n\t\t\t\t\tl[line] = l[line][:-1]\n\t\t\t\tbuf[0][0][line + 1] = l[line]\n\t\t\tf.close\n\n\tdef basicGUI():\n\t\t## Explanation of controls\n\t\tif x > 47:\n\t\t\tif mode == 0:\n\t\t\t\tmyscreen.addstr(y-1, 0, \"Save File - C^s\", curses.color_pair(4))\n\t\t\t\tmyscreen.addstr(y-1, 16, \"Open File - C^o\", curses.color_pair(4))\n\t\t\t\tmyscreen.addstr(y-1, 32, \"Export(HTML) - C^e\", curses.color_pair(4))\n\t\t\tif mode == 1:\n\t\t\t\tmyscreen.addstr(y-1, 0, \"Save File - C^s\", curses.color_pair(4))\n\t\t\t\tmyscreen.addstr(y-1, 16, save_name, curses.color_pair(4))\n\t\t\tif mode == 2:\n\t\t\t\tmyscreen.addstr(y-1, 0, \"Open File - C^s\", curses.color_pair(4))\n\t\t\t\tmyscreen.addstr(y-1, 16, save_name, curses.color_pair(4))\t\t\t\n\n\t\t## The actual text\n\t\t## Loop goes here\n\t\tfor string in range(len(buf[0][0])):\n\t\t\tif string < (y-2):\n\n\n\t\t\t\t## Math\n\t\t\t\tif classify(buf[0][0][string + offset][(offsetX):((x-1) + offsetX)])[0] == 1:\n\t\t\t\t\tmyscreen.addstr(string, 0, ('\\t'*(tabOffset/7))+classify(buf[0][0][string + offset][(0+offsetX):((x-1) + offsetX)])[1], curses.color_pair(2) | curses.A_BOLD)\n\t\t\t\t\tcontinue\n\n\t\t\t\t## H3\n\t\t\t\tif string > 2:\n\t\t\t\t\tif string < len(buf[0][0]) and buf[0][0][(string-1) + offset].startswith(\"\\t\") and buf[0][0][(string) + offset].startswith(\"\\t\"*2) and buf[0][0][(string+1) + offset].startswith(\"\\t\"*3):\n\t\t\t\t\t\tmyscreen.addstr(string, 0, buf[0][0][string + offset][(0+offsetX):((x-1) + offsetX)], curses.A_BOLD)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t## H2\n\t\t\t\tif string > 1:\n\t\t\t\t\tif string < len(buf[0][0]) and buf[0][0][(string) + offset].startswith(\"\\t\") and buf[0][0][(string+1) + offset].startswith(\"\\t\"*2) and not(buf[0][0][(string) + offset].startswith(\"\\t\"*2)) :\n\t\t\t\t\t\tmyscreen.addstr(string, 0, buf[0][0][string + offset][(0+offsetX):((x-1) + offsetX)], curses.A_BOLD)\n\t\t\t\t\t\tcontinue\n\t\t\t\t## H1\n\t\t\t\tif string < len(buf[0][0]) and buf[0][0][(string + 1) + offset].startswith(\"\\t\") and not(buf[0][0][(string) + offset].startswith(\"\\t\")):\n\t\t\t\t\tmyscreen.addstr(string, 0, buf[0][0][string + offset][(0+offsetX):((x-1) + offsetX)], curses.A_BOLD)\n\t\t\t\telse:\n\t\t\t\t\tmyscreen.addstr(string, 0, buf[0][0][string + offset][(0+offsetX):((x-1) + offsetX)])\n\n\twhile 1==prog_run:\n\t\tmyscreen.clear()\n\t\ty, x = myscreen.getmaxyx()\n\t\t##########################\n\n\t\tif mode == 1 and key > 32 and key < 176:\n\t\t\tif key == 127:\n\t\t\t\tsave_name = save_name[:-1]\n\t\t\t\tif cursor.x > 16:\n\t\t\t\t\tcursor.x = cursor.x - 1\n\t\t\telse:\n\t\t\t\tsave_name = save_name + chr(key)\n\t\telif key == curses.KEY_RESIZE:\n\t\t\ty, x = myscreen.getmaxyx()\n\t\telif mode == 2 and key > 32 and key < 176:\n\t\t\tif key == 127:\n\t\t\t\tsave_name = save_name[:-1]\n\t\t\t\tif cursor.x > 16:\n\t\t\t\t\tcursor.x = cursor.x - 1\n\t\t\telse:\n\t\t\t\tsave_name = save_name + chr(key)\n\t\telif key == curses.KEY_UP and mode == 0:\n\t\t\tif cursor.y > 0:\n\t\t\t\tcursor.y = cursor.y - 1\n\t\t\tif cursor.y < 1:\n\t\t\t\tcurses.curs_set(0)\n\t\t\t\tif offset > 0:\n\t\t\t\t\toffset = offset-1\n\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\telif key == curses.KEY_DOWN and mode == 0:\n\t\t\tif cursor.y == y-3:\n\t\t\t\toffset = offset + 1\n\t\t\telse:\n\t\t\t\tcursor.y = cursor.y + 1\n\t\t\tif cursor.y > 0:\n\t\t\t\tcurses.curs_set(1)\n\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\telif key == curses.KEY_RIGHT and mode == 0:\n\t\t\tif cursor.x < (x-1):\n\t\t\t\tcursor.x = cursor.x + 1\n\t\t\telse:\n\t\t\t\toffsetX = offsetX + 1\n\t\telif key == curses.KEY_LEFT and mode == 0:\n\t\t\tif cursor.x > 0:\n\t\t\t\tcursor.x = cursor.x - 1\n\t\t\telse:\n\t\t\t\tif offsetX > 0:\n\t\t\t\t\toffsetX = offsetX - 1\n\t\telif key == 19:\n\t\t\tif mode == 0:\n\t\t\t\tmode = 1\n\t\t\t\tprev_x = cursor.x\n\t\t\t\tprev_y = cursor.y\n\t\t\t\tcursor.x = 16\n\t\t\t\tcursor.y = y - 1\n\t\t\telse:\n\t\t\t\tmode = 0\n\t\t\t\tsave_name = \"\"\n\t\t\t\tcursor.x = prev_x\n\t\t\t\tcursor.y = prev_y\n\t\telif key == 15:\n\t\t\tif mode == 0:\n\t\t\t\tmode = 2\n\t\t\t\tprev_x = cursor.x\n\t\t\t\tprev_y = cursor.y\n\t\t\t\tcursor.x = 16\n\t\t\t\tcursor.y = y - 1\n\t\t\telse:\n\t\t\t\tmode = 0\n\t\t\t\tsave_name = \"\"\n\t\t\t\tcursor.x = prev_x\n\t\t\t\tcursor.y = prev_y\n\t\telif key == 27:\n\t\t\tprog_run = 0\n\t\telif key == 127:\n\t\t\tisTab = 0\n\t\t\ttabOffset = 0\n\t\t\tif buf[0][0][cursor.y + offset].endswith('\\t'):\n\t\t\t\tisTab = 1\n\t\t\tfor character in buf[0][0][cursor.y + offset]:\n\t\t\t\tif character == '\\t':\n\t\t\t\t\ttabOffset = tabOffset + 7\n\t\t\tbuf[0][0][cursor.y + offset] = buf[0][0][cursor.y + offset][:(cursor.x+offsetX-1 - tabOffset)] + buf[0][0][cursor.y + offset][(cursor.x+offsetX- tabOffset):]\n\t\t\tif cursor.x > 0:\n\t\t\t\tcursor.x = cursor.x -1\n\t\t\t\tif isTab == 1:\n\t\t\t\t\tcursor.x = cursor.x - 7\n\t\t\telif cursor.y > 0 and cursor.x == 0:\n\t\t\t\tif buf[0][0][cursor.y + offset] == \"\":\n\t\t\t\t\tdel buf[0][0][cursor.y + offset]\n\t\t\t\tcursor.y = cursor.y - 1\n\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\tif cursor.y == 0 and offset > 0:\n\t\t\t\toffset = offset-1\n\t\telif key == 10:\n\t\t\tif mode == 0:\n\t\t\t\tif cursor.y == (y-3):\n\t\t\t\t\toffset = offset + 1\n\t\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\t\telif cursor.x < min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1):\n\t\t\t\t\tbuf[0][0].insert((cursor.y + offset), \"\")\n\t\t\t\t\tcursor.y = cursor.y + 1\n\t\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\t\telse:\n\t\t\t\t\tcursor.y = cursor.y + 1\n\t\t\t\t\tif buf[0][0][cursor.y-1] == \"\":\n\t\t\t\t\t\tbuf[0][0].insert((cursor.y + offset), \"\")\n\t\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\tif mode == 1:\n\t\t\t\tmode = 0\n\t\t\t\tsaveFile(save_name)\n\t\t\t\tsave_name = \"\"\n\t\t\t\tcursor.x = prev_x\n\t\t\t\tcursor.y = prev_y\n\t\t\tif mode == 2:\n\t\t\t\tmode = 0\n\t\t\t\topenFile(save_name)\n\t\t\t\tsave_name = \"\"\n\t\t\t\tcursor.x = prev_x\n\t\t\t\tcursor.y = prev_y\n\t\telif key == curses.KEY_MOUSE:\n\t\t\t_, mx, my, _, _ = curses.getmouse()\n\t\t\tif my == y-1:\n\t\t\t\tif mx > 16 and mx < 32:\n\t\t\t\t\tif mode == 0:\n\t\t\t\t\t\tmode = 2\n\t\t\t\t\t\tprev_x = cursor.x\n\t\t\t\t\t\tprev_y = cursor.y\n\t\t\t\t\t\tcursor.x = 16\n\t\t\t\t\t\tcursor.y = y - 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tmode = 0\n\t\t\t\t\t\tsave_name = \"\"\n\t\t\t\t\t\tcursor.x = prev_x\n\t\t\t\t\t\tcursor.y = prev_y\n\t\t\t\telif mx < 16:\n\t\t\t\t\tif mode == 0:\n\t\t\t\t\t\tmode = 1\n\t\t\t\t\t\tprev_x = cursor.x\n\t\t\t\t\t\tprev_y = cursor.y\n\t\t\t\t\t\tcursor.x = 16\n\t\t\t\t\t\tcursor.y = y - 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tmode = 0\n\t\t\t\t\t\tsave_name = \"\"\n\t\t\t\t\t\tcursor.x = prev_x\n\t\t\t\t\t\tcursor.y = prev_y\t\t\t\t\n\t\t\telse:\n\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\t\tcursor.y = my\n\t\telif key != 0 and mode == 0:\n\t\t\ttabOffset = 0\n\t\t\tfor character in buf[0][0][cursor.y + offset]:\n\t\t\t\tif character == '\\t':\n\t\t\t\t\ttabOffset = tabOffset + 7\n\t\t\tif len(buf[0][0][cursor.y + offset]) < (cursor.x + offsetX - tabOffset):\n\t\t\t\tbuf[0][0][cursor.y + offset] = buf[0][0][cursor.y + offset] + chr(key)\n\t\t\telse:\n\t\t\t\tbuf[0][0][cursor.y + offset] = buf[0][0][cursor.y + offset][:cursor.x + offsetX - tabOffset] + chr(key) + buf[0][0][cursor.y + offset][cursor.x + offsetX - tabOffset:]\n\t\t\tif key == 9 and cursor.x < (x-8):\n\t\t\t\tcursor.x = cursor.x + 7\n\t\t\tif cursor.x < (x-2):\n\t\t\t\tcursor.x = cursor.x + 1\n\t\t\telse: \n\t\t\t\tcursor.y = cursor.y + 1\n\t\t\t\tcursor.x = min(len(buf[0][0][cursor.y + offset].replace('\\t', \" \")), x-1)\n\t\t\n\t\t## Basic GUI\n\t\tbasicGUI()\n\t\t\n\t\t## Move cursor to the proper position\n\t\tif cursor.y > 0:\n\t\t\tmyscreen.move(cursor.y, cursor.x)\n\t\telse:\n\t\t\tmyscreen.move(1, cursor.x)\n\n\t\t#####################\n\t\tmyscreen.refresh()\n\t\tkey = myscreen.getch()\n\nwrapper(main)\n","sub_path":"nota.py","file_name":"nota.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"157860250","text":"# -*- coding: utf-8 -*-\n\nimport base64\nimport datetime\nfrom hashlib import sha256\nimport logging\nimport json\nfrom json import JSONDecodeError\n\nfrom odoo import models, fields, api, _\nfrom odoo.http import request\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT\nfrom odoo.exceptions import ValidationError\nfrom odoo.addons.payment.models.payment_acquirer import _partner_split_name\n\nfrom werkzeug import urls\nimport requests\n\n_logger = logging.getLogger(__name__)\n\n\ndef get_customer_info(partner_id, country_id=False):\n if not country_id:\n country_id = partner_id.country_id\n\n return {\n \"firstName\": \"\" if partner_id.is_company else _partner_split_name(partner_id.name)[0],\n \"lastName\": partner_id.name if partner_id.is_company else _partner_split_name(partner_id.name)[1],\n \"email\": partner_id.email or \"\",\n \"address1\": partner_id.street[:40] if partner_id.street else \"\",\n \"city\": partner_id.city or \"\",\n \"country\": country_id.code or \"\",\n \"ip\": request.httprequest.remote_addr or \"\"\n }\n\n\ndef sha256_hash(text: str):\n return sha256(text.encode(\"utf-8\")).hexdigest()\n\n\ndef base64_encode(text: str):\n return base64.b64encode(text.encode(\"utf-8\")).decode(\"ascii\")\n\n\nclass AffipayError(Exception):\n def __init__(self, message, response: requests.Response):\n super().__init__(message)\n self.response = response\n\n\nclass PaymentAcquirer(models.Model):\n ######################\n # Private attributes #\n ######################\n _inherit = \"payment.acquirer\"\n _affipay_oauth_credentials = \"blumon_pay_ecommerce_api:blumon_pay_ecommerce_api_password\"\n\n ###################\n # Default methods #\n ###################\n\n ######################\n # Fields declaration #\n ######################\n provider = fields.Selection(selection_add=[(\"affipay\", \"Affipay\")])\n affipay_username = fields.Char(\"Merchant Account ID\",\n required_if_provider=\"affipay\",\n groups=\"base.group_user\",\n help=\"The username and password are provided by Affipay.\"\n )\n affipay_password = fields.Char(\"Merchant Password\",\n required_if_provider=\"affipay\",\n groups=\"base.group_user\",\n help=\"The username and password are provided by Affipay.\"\n )\n\n # * This field will be changed/refreshed using _refresh_access_token() if:\n # * It is not set; or it is expired\n affipay_access_token = fields.Char(\n \"Affipay Auth Access Token\", default=None)\n affipay_prod_auth_url = fields.Char(\"Production Auth URL\",\n groups=\"base.group_user\",\n help=\"The Production URL to use when authenticating.\")\n affipay_prod_ecommerce_url = fields.Char(\"Production eCommerce URL\",\n groups=\"base.group_user\",\n help=\"The Production URL to use when adding token or charging.\")\n affipay_sandbox_auth_url = fields.Char(\"Sandbox Auth URL\",\n groups=\"base.group_user\",\n help=\"The Sandbox URL to use when authenticating.\")\n affipay_sandbox_ecommerce_url = fields.Char(\"Sandbox eCommerce URL\",\n groups=\"base.group_user\",\n help=\"The Sandbox URL to use when adding token or charging.\")\n\n ##############################\n # Compute and search methods #\n ##############################\n\n ############################\n # Constrains and onchanges #\n ############################\n\n #########################\n # CRUD method overrides #\n #########################\n\n ##################\n # Action methods #\n ##################\n @api.model\n def affipay_s2s_form_process(self, data):\n return self.env[\"payment.token\"].sudo().create({\n **data,\n \"name\": \"XXXXXXXXXXXX%s - %s\" % (data.get(\"cc_number\")[-4:], data.get(\"cc_holder_name\")),\n \"acquirer_id\": int(data.get(\"acquirer_id\")),\n \"partner_id\": int(data.get(\"partner_id\"))\n })\n\n def affipay_s2s_form_validate(_, data):\n return all(\n [data.get(key)\n for key in\n [\"cc_number\",\n \"cc_brand\",\n \"cc_holder_name\",\n \"cc_expiry\",\n \"cc_cvc\"\n ]\n ])\n\n ####################\n # Business methods #\n ####################\n def _get_affipaypay_url(self, action):\n self.ensure_one()\n default_auth_url = \"https://sandbox-tokener.blumonpay.net/oauth/token\"\n default_ecommerce_url = \"https://sandbox-ecommerce.blumonpay.net/ecommerce/v2/charge\"\n urls = {\n \"prod\": {\n \"oauth\": self.affipay_prod_auth_url or default_auth_url,\n \"ecommerce\": self.affipay_prod_ecommerce_url or default_ecommerce_url,\n },\n \"test\": {\n \"oauth\": self.affipay_sandbox_auth_url or default_auth_url,\n \"ecommerce\": self.affipay_sandbox_ecommerce_url or default_ecommerce_url,\n }\n }\n return urls[self.environment][action]\n\n\n def _affipay_request(self, url, headers=False, data=False, params=False, json=False, method=\"POST\"):\n self.ensure_one()\n try:\n response = requests.request(\n method, url, data=data, json=json, params=params, headers=headers)\n\n json = response.json()\n if json.get(\"error\"):\n raise AffipayError(json.get(\"error_description\"), response)\n\n response.raise_for_status()\n return response\n except (requests.exceptions.ConnectionError, JSONDecodeError) as errc :\n _logger.error(errc)\n raise ValidationError(\"Affipay: The server is down.\")\n except requests.exceptions.HTTPError as err:\n _logger.error(err)\n response = err.response\n if \"application/json\" in response.headers.get(\"Content-Type\"):\n json = response.json()\n if json.get(\"error\"):\n raise AffipayError(\"Affipay: %s: %s\" % (\n json.get(\"error\"), json.get(\"error_description\")), response)\n raise ValidationError(\"An HTTP error has occurred: %s.\" % str(err))\n\n def _affipay_oauth_request(self, url, **kwargs):\n self.ensure_one()\n url = urls.url_join(self._get_affipaypay_url(\"oauth\"), url)\n headers = kwargs.get(\"headers\", {\n \"Authorization\": \"Basic %s\" % base64_encode(self._affipay_oauth_credentials)\n })\n try:\n response = self._affipay_request(url, headers=headers, **kwargs)\n return response.json()\n except AffipayError as e:\n res_json = e.response.json()\n err = res_json.get(\"error\", \"Error\")\n err_description = res_json.get(\n \"error_description\", \"Something is wrong with the request\")\n raise ValidationError(\"%s: %s\" % (err, err_description))\n\n def _affipay_ecommerce_request(self, url, eager_refresh=False, retries=2, **kwargs):\n self.ensure_one()\n if eager_refresh or not self.affipay_access_token:\n self._affipay_refresh_access_token()\n base_url = self._get_affipaypay_url(\"ecommerce\")\n url = urls.url_join(base_url, url)\n headers = kwargs.get(\"headers\", {\n \"Authorization\": \"Bearer %s\" % self.affipay_access_token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n })\n try:\n response = self._affipay_request(url, headers=headers, **kwargs)\n res_json = response.json()\n return res_json\n except AffipayError as e:\n res_json = e.response.json()\n if res_json.get(\"error\") == \"invalid_token\":\n _logger.warn(\n \"Affipay: Invalid access token. Refreshing access token.\")\n self._affipay_refresh_access_token()\n\n # * Retry request if received invalid token error\n if retries > 0:\n _logger.info(\n \"Affipay: Retrying request on %s. (%i retries left)\" % (url, retries))\n retries -= 1\n return self._affipay_ecommerce_request(url, retries=retries, **kwargs)\n raise e\n # raise ValidationError(\"affipay Error: %s %s\" % (err_code, err_description))\n\n def _affipay_refresh_access_token(self):\n self.ensure_one()\n data = self._affipay_oauth_request(\"/oauth/token\", data={\n \"grant_type\": \"password\",\n \"username\": self.affipay_username,\n \"password\": sha256_hash(self.affipay_password),\n })\n if not data.get(\"access_token\"):\n _logger.error(json.dumps(data))\n raise ValidationError(\"No access token given.\")\n self.affipay_access_token = data.get(\"access_token\")\n return self.affipay_access_token\n\n def _affipay_build_token_request_json(self, vals):\n partner_id = self.env[\"res.partner\"].browse(vals.get(\"partner_id\"))\n exp_month, exp_year = vals.get(\"cc_expiry\").split(\"/\")\n country_id = partner_id.country_id or self.company_id.country_id\n\n return {\n \"pan\": vals.get(\"cc_number\", \"\").replace(\" \", \"\"),\n \"expMonth\": exp_month.strip(),\n \"expYear\": \"20\" + exp_year.strip(),\n \"holderName\": vals.get(\"cc_holder_name\"),\n \"customerInformation\": get_customer_info(partner_id, country_id=country_id)\n }\n\n def _get_feature_support(self):\n \"\"\"Get advanced feature support by provider.\n\n Each provider should add its technical in the corresponding\n key for the following features:\n * tokenize: support saving payment data in a payment.tokenize\n object\n \"\"\"\n res = super(PaymentAcquirer, self)._get_feature_support()\n res[\"tokenize\"].append(\"affipay\")\n\n return res\n\n\nclass PaymentTransaction(models.Model):\n ######################\n # Private attributes #\n ######################\n _inherit = \"payment.transaction\"\n\n _affipay_supported_currencies_map = {\n \"MXN\": 484,\n }\n\n ###################\n # Default methods #\n ###################\n\n ######################\n # Fields declaration #\n ######################\n\n ##############################\n # Compute and search methods #\n ##############################\n\n ############################\n # Constrains and onchanges #\n ############################\n\n #########################\n # CRUD method overrides #\n #########################\n\n ##################\n # Action methods #\n ##################\n def affipay_s2s_do_transaction(self, **kwargs):\n self.ensure_one()\n if self.currency_id.name not in self._affipay_supported_currencies_map.keys():\n raise ValidationError(\n \"Currency %s not supported.\" % self.currency_id.name)\n payment_token = self.payment_token_id\n acquirer = self.acquirer_id\n try:\n ecommerce_data = acquirer._affipay_ecommerce_request(\"/ecommerce/v2/charge\", json={\n \"amount\": float(self.amount) if acquirer.environment == \"prod\" else min(float(self.amount), 20.0),\n \"currency\": self._affipay_supported_currencies_map[self.currency_id.name],\n \"noPresentCardData\": {\n \"cardToken\": payment_token.acquirer_ref,\n \"cvv\": payment_token.affipay_cc_cvc\n }\n })\n except AffipayError as e:\n ecommerce_data = e.response.json()\n return self._affipay_s2s_validate_tree(ecommerce_data)\n\n ####################\n # Business methods #\n ####################\n def _affipay_s2s_validate_tree(self, tree, call_type=\"charge\"):\n self.ensure_one()\n if self.state not in [\"draft\", \"pending\"]:\n _logger.info(\n \"Affipay: trying to validate an already validated transaction (ref %s)\", self.reference)\n return True\n if tree.get(\"status\") and tree.get(\"dataResponse\", {}).get(\"description\") == \"APROBADA\":\n self.write({\n \"date\": datetime.date.today().strftime(DEFAULT_SERVER_DATE_FORMAT),\n \"acquirer_reference\": tree.get(\"id\")\n })\n if call_type == \"charge\":\n # E-Commerce charge success\n if self.partner_id and not self.payment_token_id and \\\n (self.type == \"form_save\" or self.acquirer_id.save_token == \"always\"):\n self.payment_token_id = self.acquirer_id.affipay_s2s_form_process(\n dict(request.params)).id\n if self.payment_token_id:\n self.payment_token_id.verified = True\n self._set_transaction_done()\n self.execute_callback()\n return True\n error = tree.get(\"error\", {})\n error_code = error.get(\"code\", \"ERR\")\n error_description = error.get(\n \"description\", \"Affipay API gave an error response.\")\n _logger.error(json.dumps(tree))\n self._set_transaction_error(\n \"Affipay API Error: %s - %s\" % (error_code, error_description))\n return False\n\n\nclass PaymentToken(models.Model):\n ######################\n # Private attributes #\n ######################\n _inherit = \"payment.token\"\n\n ###################\n # Default methods #\n ###################\n\n ######################\n # Fields declaration #\n ######################\n affipay_cc_cvc = fields.Char(readonly=True)\n\n ##############################\n # Compute and search methods #\n ##############################\n\n ############################\n # Constrains and onchanges #\n ############################\n\n #########################\n # CRUD method overrides #\n #########################\n @api.model\n def affipay_create(self, vals):\n if vals.get(\"cc_number\") and vals.get(\"cc_cvc\"):\n payment_acquirer = self.env[\"payment.acquirer\"].browse(vals.get(\"acquirer_id\"))\n response = payment_acquirer._affipay_ecommerce_request(\"/cardToken/add\",\n json=payment_acquirer._affipay_build_token_request_json(vals))\n if response.get(\"status\") and response.get(\"dataResponse\"):\n vals.update({\n \"acquirer_ref\": response.get(\"dataResponse\")[\"id\"],\n \"name\": vals.get(\"name\"),\n \"affipay_cc_cvc\": vals.get(\"cc_cvc\")\n })\n return vals\n else:\n raise ValidationError(\"Error: %s\" % response.get(\n \"error\", {}).get(\"description\", \"\"))\n return {}\n\n ##################\n # Action methods #\n ##################\n\n ####################\n # Business methods #\n ####################\n","sub_path":"payment_affipay/models/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":14960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"125287653","text":"import urllib.request\nfrom urllib.error import URLError, HTTPError\nimport csv, os.path, socket\nurl = \"http://192.168.100.20:8080/file1.csv\"\nheader_in_csv = True\n\n\n#Download file from given url and save to current directory \n\ndef is_valid_ipv4_address(address):\n try:\n socket.inet_pton(socket.AF_INET, address)\n except AttributeError: # no inet_pton here, sorry\n try:\n socket.inet_aton(address)\n except socket.error:\n return False\n return address.count('.') == 3\n except socket.error: # not a valid address\n return False\n\n return True\n\ndef download_csv(url):\n position = list()\n csvfilename = url.split('/')[-1]\n\n #Try to open URL, return error codes\n try:\n response = urllib.request.urlopen(url)\n except HTTPError as e:\n print('The server couldn\\'t fulfill the request.')\n print('Error code: ', e.code)\n return \"Error accessing file.\"\n except URLError as e:\n print('We failed to reach a server.')\n print('Reason: ', e.reason)\n return \"Error connecting.\"\n else:\n print(response.info())\n csvfile_size = response.getheader(\"Content-Length\")\n print(\"File size: \" + csvfile_size)\n\n #Define size of buffer\n csvfile_buffer = int(csvfile_size) / 10 \n csvfile_buffer = int(csvfile_buffer)\n\n #Open file and write content to it\n file = open(csvfilename,'wb')\n content = response.read(csvfile_buffer)\n print(\"Writing: \",end='')\n while content:\n file.write(content)\n print(\"#\",end='')\n content = response.read(csvfile_buffer)\n file.close()\n\n return csvfile_size\n\ndef displaycsv(filename):\n print(\"\\nDevices:\")\n #Open CSV file - Source\n with open(filename,mode='r') as csvfile:\n file = csv.DictReader(csvfile)\n header = file.fieldnames\n print(header)\n #Open inventory file when we write\n with open('inventory', 'w') as invfile:\n\n invfile.write(\"[routers]\\n\")\n for row in file:\n\n port = row['port']\n name = row['name']\n ipaddr = row['IP']\n if port.isdigit() and is_valid_ipv4_address(ipaddr):\n\n print(name + \": Saved to invetory\")\n name.replace(\" \",\"\")\n port = int(port)\n\n invfile.write(name + \" \" + \"ansible_host=\" + ipaddr + \" \" + \"ansible_port=\" + repr(port) + \"\\n\")\n else:\n print(name + \": Wrong data type\")\n\n return 1\n\ndownload_csv(url)\nprint(displaycsv(\"file1.csv\"))\n\n#for line in content:\n# print(line)\n\n","sub_path":"download-csv.py","file_name":"download-csv.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"140920122","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"A simple example demonstrating the using paged output via the ppaged() method.\n\"\"\"\n\nimport cmd2\n\n\nclass PagedOutput(cmd2.Cmd):\n \"\"\" Example cmd2 application where we create commands that just print the arguments they are called with.\"\"\"\n\n def __init__(self):\n super().__init__()\n\n @cmd2.with_argument_list\n def do_page_file(self, args):\n \"\"\"Read in a text file and display its output in a pager.\"\"\"\n if not args:\n self.perror('page_file requires a path to a file as an argument', traceback_war=False)\n return\n\n with open(args[0], 'r') as f:\n text = f.read()\n self.ppaged(text)\n\n complete_page_file = cmd2.Cmd.path_complete\n\n\nif __name__ == '__main__':\n app = PagedOutput()\n app.cmdloop()\n","sub_path":"examples/paged_output.py","file_name":"paged_output.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"279226523","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n \nfrom .models import User as Profile\nfrom django.contrib.auth.models import User\nfrom datetime import date\n\nfrom django.contrib.auth.decorators import login_required\n# Create your views here.\n'''\n - userScores = dictionary to store each database users name and score. This allows me to loop through later and display the name and score of each user.\n - sorted_values = convert userScores from a dictionary of sorted scores. But this lacks the usernames attached to each score.\n - sorted_dict = is a completely sorted dictionary sorted on highscore with each key being a username and value being thier score.\n - top_three = dictionary containing the top three users based on the sorted_dict.\n - rest = dictionary of all users outside the top three.\n - first = dictionary containing key(username):value(high_score) for the top user.\n - second, third = same as first but for the second and third placed user.\n'''\n@login_required\ndef leaderboard(request):\n userScores = {}\n username = request.user.username\n for user1 in Profile.objects.all():\n userScores[user1.user_name]=user1.high_score \n dict1 = userScores\n sorted_values = sorted(dict1.values(),reverse=True) #Sort the values\n sorted_dict = {}\n for i in sorted_values:\n for k in dict1.keys():\n if dict1[k] == i and k not in sorted_dict:\n sorted_dict[k] = dict1[k]\n break\n top_three_users={k: sorted_dict[k] for k in list(sorted_dict)[:3]}\n rest={k: sorted_dict[k] for k in list(sorted_dict)[3:]}\n first={k: top_three_users[k] for k in list(top_three_users)[0:1]}\n second={k: top_three_users[k] for k in list(top_three_users)[1:2]}\n third={k: top_three_users[k] for k in list(top_three_users)[2:3]}\n context={\n \"users\": sorted_dict.items(),\n \"1rst\": first.items(),\n \"2nd\": second.items(),\n \"3rd\": third.items(),\n \"rest_of_users\":rest.items(),\n \"len_rest\": len(rest.items()),\n \"number_of_users\": Profile.objects.count(),\n }\n return render(request, 'leaderboard.html', context)","sub_path":"teamProject/leaderboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530328111","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Melisa,Morgane\n\"\"\"\n#%% Importation and parameters\n\nfrom src.Steps.run_steps import run_steps\nimport psutil\nimport caiman as cm\n\n# Settings interface\n\nprint('Choose the mouse, session, how many trial you want to analyse')\nmouse_number = int(input(\"mouse number : \"))\nsessions = input(\" sessions : \")\nprint('Number of trial from Steps.run_steps_session_wise import run_steps that you want to analyse, if you want to analyse only one trial enter the same number for the first trial and the final one')\ninit_trial = int(input(\"begin with trial : \"))\nend_trial = int(input(\" final trial to analyse: \"))\n\nprint('Choose which steps you want to run: 0 -> decoding, 1 -> cropping, 2 -> motion correction, 3 -> alignment, 4 -> equalization, 5 -> source extraction, 6 -> component evaluation, 7 -> registration, all -> every steps ')\nn_steps = input(' steps :')\n\n# start a cluster\n\nn_processes = psutil.cpu_count()\nc, dview, n_processes = cm.cluster.setup_cluster(backend='local', n_processes=n_processes, single_thread=False)\n\n# Create a loop for run steps\n\nprocess ='yes'\n\n# Run steps that you want\n\nwhile process == 'yes':\n\n run_steps(n_steps, mouse_number, sessions, init_trial, end_trial,dview)\n print('This step is finish. Do you want to run another step with those settings ? (yes or no)')\n process=input(\"answer : \")\n if process == 'yes':\n print('Choose which steps you want to run: 0 -> decoding, 1 -> cropping, 2 -> motion correction, 3 -> alignment, 4 -> equalization, 5 -> source extraction, 6 -> component evaluation, 7 -> registration, all -> every steps ')\n n_steps = input(' steps :')\n run_steps(n_steps, mouse_number, sessions, init_trial, end_trial, dview)\n if process == 'no':\n print('Thanks for having used this pipeline. I hope everything went alright for you :)')\n dview.terminate()\n else:\n print('you did not choose a viable choice retry ')\n process = input(\"answer : \")\n\n","sub_path":"src/Pipeline/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"107328281","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd \nfrom numpy.random import RandomState\nfrom sklearn.model_selection import KFold\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import cross_val_score\n\n\n# In[2]:\n\n\ndf = pd.read_csv (r'C:\\\\Users\\\\rezam\\\\Desktop\\\\New folder\\\\Datasets\\\\Q3\\Communities_Crime.csv', header=None)\n\n\n# ### The cleaning process of the dataset:\n# \n# ##### - The dataset had missing values in some columns. The values have been replaced the avrage of the values of the column. \n\n# In[3]:\n\n\ndf.shape\ndf.dtypes\ndf.info()\n\n\n# ### The cleaning process of the dataset 2:\n# ##### - The columns (indexes 0 & 3) had int64 datatypes which have been modified to float.\n# ##### - The column 29 had a missing value (object), and it has ben replaced the the avrage of related column.\n# ##### - The loops below indicate the indexes of those values.\n\n# In[4]:\n\n\ndf.columns\nfor col in df.columns:\n if str(df.iloc[:,col].dtypes) == 'object':\n print(col)\n# df.iloc[:,1]\n\n\n# In[5]:\n\n\ndf.columns\nfor col in df.columns:\n if str(df.iloc[:,col].dtypes) == 'int64':\n print(col)\n# df.iloc[:,1]\n\n\n# ### Data preparation:\n# ##### - The imported dataset has been devided in 80% train and 20% test.\n# ##### - The train dataset will be used for cross validation and the test data set will remain untouche for the final validation.\n\n# In[6]:\n\n\nfrom numpy.random import RandomState\nrng = RandomState()\ntrain = df.sample(frac=0.8, random_state=rng)\nfinal_test = df.loc[~df.index.isin(train.index)]\n\n\n# In[7]:\n\n\ntrain.shape\n\n\n# In[8]:\n\n\nfinal_test.shape\n\n\n# ### Observation:\n# ##### - The 80% train dataset has been allocated for cross validation.\n# ##### - The remaining 20% will be fitted to the best performed model. \n# ##### - The target has been set to the last column.\n\n# In[9]:\n\n\nX_first_train = train.iloc[:,0:126].to_numpy()\ny_first_train = train.iloc[:,-1:].to_numpy()\n\n\n# In[10]:\n\n\nX_first_train.shape\n\n\n# In[11]:\n\n\ny_first_train.shape\n\n\n# ### - Data preparation:\n\n# In[12]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X_first_train, y_first_train, test_size=0.2)\n\n\n# ### KFold cross validation (basic)\n\n# In[13]:\n\n\nkf = KFold(n_splits=5, random_state=42, shuffle=True)\n\n\n# In[14]:\n\n\nfor train_index, test_index in kf.split(df):\n# print(train_index, test_index)\n print(kf)\n\n\n# ### - Function for model (basic):\n\n# In[15]:\n\n\ndef get_score(model, X_train, X_test, y_train, y_test):\n model.fit(X_train, y_train)\n return model.score(X_test, y_test)\n\n\n# ##### - Linear regression\n\n# In[16]:\n\n\nget_score(LinearRegression(), X_train, X_test, y_train, y_test)\n\n\n# ##### - RidgeCV\n\n# In[17]:\n\n\nget_score(RidgeCV(), X_train, X_test, y_train, y_test)\n\n\n# ### - Cross_val_score function:\n# ##### - Linear regression\n\n# In[18]:\n\n\ncross_val_score(LinearRegression(), X_train, y_train,cv=5)\n\n\n# ##### - RidgeCV\n\n# In[19]:\n\n\ncross_val_score(RidgeCV(), X_train, y_train,cv=5)\n\n\n# ### - Cross_val_score function:\n# ##### - Tunning by using k fold cross validation.\n# \n# ##### - Linear regression:\n\n# In[20]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_train, y_train, cv=5)\nnp.average(scores1)\n\n\n# In[21]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_train, y_train, cv=3)\nnp.average(scores1)\n\n\n# In[22]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_train, y_train, cv=10)\nnp.average(scores1)\n\n\n# In[23]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_train, y_train, cv=20)\nnp.average(scores1)\n\n\n# In[24]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_train, y_train, cv=15)\nnp.average(scores1)\n\n\n# ##### - RidgeCV:\n\n# In[25]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1]),X_train, y_train, cv=3)\nnp.average(scores1)\n\n\n# In[26]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1e1]),X_train, y_train, cv=5)\nnp.average(scores1)\n\n\n# In[27]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1e2]),X_train, y_train, cv=10)\nnp.average(scores1)\n\n\n# In[28]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1e3]),X_train, y_train, cv=15)\nnp.average(scores1)\n\n\n# In[29]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1e4]),X_train, y_train, cv=20)\nnp.average(scores1)\n\n\n# ### - Best performed:\n\n# In[30]:\n\n\nX_final_train = final_test.iloc[:,0:126].to_numpy()\ny_final_train = final_test.iloc[:,-1:].to_numpy()\n\n\n# In[31]:\n\n\nX_final_train.shape\n\n\n# In[32]:\n\n\ny_final_train.shape\n\n\n# ##### - Linear regression:\n\n# In[33]:\n\n\nscores1 = cross_val_score(LinearRegression(),X_final_train, y_final_train, cv=10)\nnp.average(scores1)\n\n\n# ##### - RidgeCV:\n\n# In[34]:\n\n\nscores1 = cross_val_score(RidgeCV(alphas=[1e1]),X_final_train, y_final_train, cv=5)\nnp.average(scores1)\n\n","sub_path":"Mohammad Hashtari (mini-project1)/Q3 with sklearn/mini_project1 (Q3) sklearn.py","file_name":"mini_project1 (Q3) sklearn.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"130250029","text":"import getopt\nimport sys\nimport multiprocessing\nfrom util import const\nimport os\nimport logging\nfrom cfg.validator import Validator\nfrom cfg.cfgMgr import ConfigManager\nfrom logging.handlers import TimedRotatingFileHandler\nfrom historical.histDataService import HistoricalDataService\n\nif __name__ == '__main__':\n multiprocessing.log_to_stderr(logging.DEBUG)\n opts, args = getopt.getopt(sys.argv[1:], 'he:', ['excode=', 'help'])\n\n excode = None\n\n for key, value in opts:\n\n if key in ['-h', '--help']:\n print('download tick data')\n print('arg:')\n print('-h\\t help')\n print('-e\\t exchange code as ISO10383_MIC')\n raise SystemExit(0)\n if key in ['-e', '--excode']:\n excode = value.upper()\n\n # Process(target=server_push, args=(server_push_port,)).start()\n\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter(const.log_format)\n\n handler = TimedRotatingFileHandler(const.hist_log_path + excode + \"/\"\n + str(os.getpid()) + const.hist_file_log, when='midnight')\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n logger.info(\"%r main pid is %r\" % (excode, os.getpid()))\n conf = ConfigManager(Validator(const.schema_file, logger), const.config_file)\n\n hist = HistoricalDataService(logger, conf, excode)\n hist.process()\n pass\n","sub_path":"src/histMain.py","file_name":"histMain.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"282607128","text":"import numpy as np\nimport tensorflow as tf\n\nimport bayesflow as bf\nimport bayesflow.util as util\n\n\nfrom bayesflow.models import ConditionalDistribution\nfrom bayesflow.models.q_distributions import QDistribution\n\ndef layer(inp, w, b):\n if len(inp.get_shape()) == 2:\n return tf.matmul(inp, w) + b\n else:\n return tf.pack([tf.matmul(inp_slice, w) + b for inp_slice in tf.unpack(inp)])\n\ndef init_weights(*shape):\n return tf.Variable(tf.random_normal(shape, stddev=0.01, dtype=tf.float32))\n\ndef init_zero_vector(n_out):\n return tf.Variable(tf.zeros((n_out,), dtype=tf.float32))\n\nclass VAEDecoderBernoulli(ConditionalDistribution):\n def __init__(self, z, w1, w2, b1, b2, **kwargs):\n super(VAEDecoderBernoulli, self).__init__(z=z, w1=w1, w2=w2, b1=b1, b2=b2, **kwargs)\n\n def inputs(self):\n return (\"z\", \"w1\", \"w2\", \"b1\", \"b2\")\n \n def _compute_shape(self, z_shape, w1_shape, w2_shape, b1_shape, b2_shape):\n d_latent = z_shape[-1]\n d_output, = b2_shape\n return z_shape[:-1] + (d_output,)\n \n def _compute_dtype(self, z_dtype, w1_dtype, w2_dtype, b1_dtype, b2_dtype):\n assert(z_dtype == w1_dtype)\n assert(z_dtype == w2_dtype)\n assert(z_dtype == b1_dtype)\n assert(z_dtype == b2_dtype)\n return z_dtype\n \n def _sample(self, z, w1, w2, b1, b2, return_probs=False):\n\n g = tf.Graph()\n with g.as_default():\n z = tf.convert_to_tensor(z)\n w1 = tf.convert_to_tensor(w1)\n w2 = tf.convert_to_tensor(w2)\n b1 = tf.convert_to_tensor(b1)\n b2 = tf.convert_to_tensor(b2)\n\n h1 = tf.nn.tanh(layer(z, w1, b1))\n h2 = tf.nn.sigmoid(layer(h1, w2, b2))\n\n init = tf.initialize_all_variables()\n \n sess = tf.Session(graph=g)\n sess.run(init)\n probs = sess.run(h2)\n\n if return_probs:\n return probs\n else:\n return np.asarray(np.random.rand(*probs.shape) < probs, dtype=self.dtype)\n \n def _logp(self, result, z, w1, w2, b1, b2):\n h1 = tf.nn.tanh(layer(z, w1, b1))\n h2 = tf.nn.sigmoid(layer(h1, w2, b2))\n self.pred_image = h2\n obs_lp = tf.reduce_sum(bf.dists.bernoulli_log_density(result, h2))\n return obs_lp\n\nclass VAEEncoder(QDistribution):\n\n def __init__(self, X, d_hidden, d_z):\n x_shape = util.extract_shape(X)\n d_x = x_shape[-1]\n z_shape = x_shape[:-1] + (d_z,)\n super(VAEEncoder, self).__init__(shape=z_shape)\n\n w3 = init_weights(d_x, d_hidden)\n w4 = init_weights(d_hidden, d_z)\n w5 = init_weights(d_hidden, d_z)\n b3 = init_zero_vector(d_hidden)\n b4 = init_zero_vector(d_z)\n b5 = init_zero_vector(d_z)\n \n h1 = tf.nn.tanh(layer(X, w3, b3))\n self.mean = layer(h1, w4, b4)\n self.variance = tf.exp(layer(h1, w5, b5))\n self.stddev = tf.sqrt(self.variance)\n self.stochastic_eps = tf.placeholder(dtype=self.mean.dtype, shape=self.output_shape, name=\"eps\")\n self.sample = self.stochastic_eps * self.stddev + self.mean\n self._entropy = tf.reduce_sum(bf.dists.gaussian_entropy(variance=self.variance))\n \n def sample_stochastic_inputs(self):\n sampled_eps = np.random.randn(*self.output_shape)\n return {self.stochastic_eps : sampled_eps}\n \n def entropy(self):\n return self._entropy\n","sub_path":"bayesflow/models/neural.py","file_name":"neural.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"473772231","text":"#!/usr/bin/env python3\n\nimport os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nimport pygame\nimport serial\nimport math\nimport sys\nimport time\nimport struct\nfrom dataclasses import dataclass, field\nfrom typing import List\n\n# set up the colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\n\n# debug define\nDEBUG_NO_HUD=1\n\n@dataclass\nclass scanData:\n packet_header: int = 0# 0x55AA\n packet_type: int = 0 # 0 or 1\n sample_quantity: int = 0\n starting_angle: int = 0\n end_angle: int = 0\n check_code: int = 0\n sampling_data: List[int] = field(default_factory=list)\n\n\nclass Controller:\n def __init__(self, port):\n self.port = port\n self.baud = 230400\n self.con = serial.Serial(self.port, self.baud, serial.EIGHTBITS,\n serial.PARITY_NONE, serial.STOPBITS_ONE)\n self.con.flush()\n self.con.flushInput()\n self.con.read_all()\n self.is_started = False\n\n def _send(self, payload):\n self.con.write(payload)\n\n\n def start(self):\n self._send(bytearray([0xA5, 0x60]))\n self.is_started = True\n\n\n def stop(self):\n self.is_started = False\n self._send(bytearray([0xA5, 0x65]))\n\n def convert_scan_data_header(self, packet):\n d = [hex(x) for x in packet]\n s = scanData()\n s.packet_header = int(d[1], 16) + int(d[0], 16)\n s.packet_type = int(d[2], 16)\n s.sample_quantity = int(d[3], 16)\n s.starting_angle = int(d[4], 16) + int(d[5], 16)\n s.end_angle = int(d[6], 16) + int(d[7], 16)\n s.check_code = int(d[8], 16) + int(d[9], 16)\n return s\n\n\n def read(self):\n if self.is_started == False:\n return None\n data = self.con.read(10)\n d = [hex(x) for x in data]\n if data[0] == 0xAA:\n scan_data = self.convert_scan_data_header(data)\n if scan_data.sample_quantity > 0:\n points = self.con.read(2 * scan_data.sample_quantity)\n d = [hex(x) for x in points]\n p = []\n for i in range(0, len(d), 2):\n p.append(int(d[i], 16) + int(d[i+1], 16))\n print(p)\n\n\n # print(points)\n\n\nclass Gui:\n def __init__(self, controller):\n self.controller = controller\n\n pygame.init()\n self.screen = pygame.display.set_mode([1280, 720])\n pygame.display.set_caption('Lidar Visualizer')\n\n if not DEBUG_NO_HUD:\n pygame.font.init()\n self.font = pygame.font.SysFont(\"arialttf\", 30)\n else:\n self.font = None\n\n\n def draw_radar_view(self):\n radar_center = (350, 350)\n for i in range(1, 5):\n pygame.draw.circle(self.screen, GREEN, radar_center, i*80, width=2)\n pygame.draw.circle(self.screen, GREEN, radar_center, 18)\n\n radar_len = 325\n for i in range(12):\n angle = i * 30\n x = int(radar_center[0] + math.cos(math.radians(angle)) * radar_len)\n y = int(radar_center[1] + math.sin(math.radians(angle)) * radar_len)\n pygame.draw.line(self.screen, GREEN, radar_center, (x,y), width=1)\n\n def draw_hud(self):\n textsurface = self.font.render('Controls', True, WHITE)\n self.screen.blit(textsurface, (900, 10))\n\n textsurface = self.font.render('S -> Start Lidar', True, WHITE)\n self.screen.blit(textsurface, (910, 100))\n\n textsurface = self.font.render('T -> Stop Lidar', True, WHITE)\n self.screen.blit(textsurface, (910, 150))\n\n textsurface = self.font.render('P -> Toggle freeze screen', True, WHITE)\n self.screen.blit(textsurface, (910, 200))\n\n def draw(self):\n self.draw_radar_view()\n pygame.draw.line(self.screen, WHITE, (850, 0), (850, 720), width=5)\n if not DEBUG_NO_HUD:\n self.draw_hud()\n\n\n def start(self):\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n return\n if event.key == pygame.K_s:\n print(\"Start\")\n self.controller.start()\n elif event.key == pygame.K_t:\n print(\"Stop\")\n self.controller.stop()\n\n self.controller.read()\n self.screen.fill(BLACK)\n self.draw()\n pygame.display.flip()\n\n def quit(self):\n self.controller.stop()\n pygame.quit()\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n sys.exit(\"USAGE: ./lidar_visualizer PORT\")\n c = Controller(sys.argv[1])\n g = Gui(c)\n g.start()\n g.quit()\n","sub_path":"lidar_visualizer/lidar_visualizer_custom.py","file_name":"lidar_visualizer_custom.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"334562879","text":"from django.test import TestCase\nfrom pedidos.models import *\nfrom factories import *\n\nclass TesteDePedido(TestCase):\n\n\tdef testa_realizacao_de_um_pedido_com_itens(self):\n\t\titem = ItemFactory()\n\t\tcelular = CelularFactory()\n\n\t\tpedido = celular.realizar_pedido((item, ))\n\n\t\tassert pedido in Pedido.objects.all()\n\t\tassert pedido.itens.first() == item\n\n\tdef testa_o_pagamento_de_um_pedido(self):\n\t\tpedido = PedidoFactory()\n\n\t\tpedido.comprar()\n\n\t\tcompra = Compra.objects.first()\n\t\tassert compra.pedido == pedido\n\n\tdef testa_a_entrega_de_pedido(self):\n\t\tpedido = PedidoFactory()\n\n\t\tpedido.entregar()\n\n\t\tself.assertTrue(pedido.foi_entregue)\n\n\tdef testa_a_listagem_de_pedidos_pendentes(self):\n\t\tpedidos = Pedido.obter_pendentes()\n\n\t\tassert all(map(lambda pedido: not pedido.foi_entregue, pedidos))","sub_path":"pedidos/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"653038508","text":"import sys\nsys.stdin = open(\"02_basic\\input.txt\", \"rt\")\n\nN = int(input())\narr = list(map(int, input().split()))\nmax = 0\nans = 0\n\n\ndef digit_sum(x):\n sum = 0\n for i in str(x):\n sum += int(i)\n return sum\n\n\nfor v in arr:\n cur = digit_sum(v)\n\n if ans < cur:\n ans = cur\n max = v\n\nprint(max)\n","sub_path":"02_basic/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"189349742","text":"a = {\n 'name': ' Nguyen Van A',\n 'age': 50,\n 'sex': 'male'\n}\nwhile True:\n key = input('Nhập key: ')\n if key in a:\n del a[key]\n break\n else:\n print('Key {} không tồn tại. Mời nhập lại.'.format(key))\n\nprint(a)\n\n","sub_path":"session10/dictD/deleteWithKeyFromInput.py","file_name":"deleteWithKeyFromInput.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575803081","text":"\n\n#calss header\nclass _JOLLY():\n\tdef __init__(self,): \n\t\tself.name = \"JOLLY\"\n\t\tself.definitions = [u'to encourage someone to do something by putting that person in a good mood and persuading them gently: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_jolly.py","file_name":"_jolly.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118230543","text":"## SY 14/10/18\n## Plots auto-correlations of kappa power spectra for noisy maps with R_t max. Clips off outliers which were creating odd results.\n\nfrom astropy.io import fits\nimport healpy as hp\nimport numpy as np\nimport pylab as P\nimport kappa_lya\nfrom kappa_lya import *\nimport sys\nimport os\n\ndef read_kappa_input(nside=256):\n kappa_input = fits.open('kappa_input_gaussian.fits')[1].data.I.ravel()\n #kappa_input = fits.open('kappa_input_noiseless.fits')[1].data.I.ravel()\n alm_input = hp.map2alm(kappa_input, lmax=3*nside-1)\n kappa_input = hp.alm2map(alm_input, nside=nside)\n return kappa_input\n\ndef rebin_cl(Cls):\n '''Smooth curves by rebinning Cls'''\n binwidth = 20\n l_bin = []\n Cl_bin = []\n cl_temp = 0.\n cl_weight = 0.\n for i,Cl in enumerate(Cls):\n l = i + 1\n cl_temp += Cl*l*(l+1)\n cl_weight += l*(l+1)\n if i % binwidth == 0:\n l_bin.append(l)\n Cl_bin.append(cl_temp / cl_weight)\n cl_temp = 0.\n cl_weight = 0.\n l_bin = np.array(l_bin)\n Cl_bin = np.array(Cl_bin)\n return l_bin, Cl_bin\n\n# Open kappa fits files\nnside=256\nlw=0.5\nkappa_input = read_kappa_input(nside=nside)\nell = np.arange(3*nside)\n\nP.ion()\nfig = P.figure(figsize=(10,8))\nax = fig.add_subplot(1, 1, 1)\n\ndata = fits.open('kappa-noiseless-70-40.fits.gz')[1].data\n#data = fits.open('kappa-noiseless-70-100.fits.gz')[1].data\nkappa = data.kappa\nmask = data.wkappa!=0\nmask &= (data.kappa>np.percentile(data.kappa[mask], 0.5)) & \\\n (data.kappa 0 and board[x - 1][y] == 'O':\n self.helper(board, x - 1, y )\n if y < len(board[x]) - 1 and board[x][y + 1] == 'O':\n self.helper(board, x, y + 1)\n if y > 0 and board[x][y - 1] == 'O':\n self.helper(board, x, y - 1)\n \n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n #start with boarder, run helper to modify appropriate O to $\n for i in range(len(board)):\n for j in range(len(board[i])):\n if (i == 0 or j == 0 or i == len(board) - 1 or j == len(board[i]) - 1) and board[i][j] == 'O':\n self.helper(board, i, j)\n \n #run through board\n for i in range(len(board)):\n for j in range(len(board[i])):\n #flip O to X\n if board[i][j] == 'O':\n board[i][j] = 'X'\n #flip $ to O\n if board[i][j] == '$':\n board[i][j] = 'O'\n \n return board\n ","sub_path":"codes/Nancy/LC130.py","file_name":"LC130.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"269423046","text":"import sys as sys\nsys.path.append('/Users/bruker/Documents/UiO/Bachelor/Semester 6/AST3310/Project0')\n\n\"\"\"\nThe sys path should be replaced with the directionary containing the file SanProject0.py\n\n\"\"\"\n\n\nfrom ProjectC import EnergyProduction\nfrom scipy import interpolate\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass CoreModel(EnergyProduction):\n\n\t\"\"\"\n\tClass that models the stellar core of a star by solving a set of differential equations which\n\tlets us study how the different features of the core changes as we move through the star.\n\tThe class inherits the EnergyProduction class used in project 0. \n\n\t\"\"\"\n\n\n\tdef __init__(self):\n\n\t\t#inheriting init from core\n\t\tEnergyProduction.__init__(self)\n\n\n\t\t#initial conditions given for our star\n\t\tself.L0 = self.L_sol\t\t\t\t\t\t\t\t\t#luminosity, \t\t\t\t\tJ/s or W\n\t\tself.R0 = 0.72*self.R_sol\t\t\t\t\t\t\t\t#radius, \t\t\t\t\t\tm\n\t\tself.M0 = 0.8*self.M_sol\t\t\t\t\t\t\t\t#mass, \t\t\t\t\t\t\tkg\n\t\tself.rho0 = 5.1*self.avgrho_sol\t\t\t\t\t\t\t#density, \t\t\t\t\t\tkg/m^3\n\t\tself.T0 = 5.7e6\t\t\t\t\t\t\t\t\t\t\t#temperature, \t\t\t\t\tK\n\n\t\t#constants\n\t\tself.c = 299792458\t\t\t\t\t\t\t\t\t\t#speed of light, \t\t\t\tm/s\n\t\tself.k_B = 1.38064852e-23\t\t\t\t\t\t\t\t#Boltzmann constant, \t\t\tm^2*kg/(s^2*K) \n\t\tself.G = 6.674e-11\t\t\t\t\t\t\t\t\t\t#Gravitational constant, \t\tm^3/(kg*s^2)\n\t\tself.sigma = 5.67e-8\t\t\t\t\t\t\t\t\t#Stefan-Boltzmann constant, \tW/(m^2 * K^4)\n\n\n\n\tdef ReadFile(self):\n\n\t\t\"\"\"\n\t\tSubroutine that extracts logT, logR and Kappa from the table found in opacity.txt.\n\n\t\t\"\"\"\n\n\t\tfile = open('opacity.txt','r')\t\t\t\t\n\t\tlines = file.read().splitlines()\t\t\t\t\n\n\t\ttable = []\n\t\tfor item in lines[2:]:\n\t\t\ttable.append(item.split())\n\n\t\tself.logR = np.array(lines[0].split()[1:]).astype(float)\n\t\tself.logT = np.array(table)[:,0].astype(float)\n\t\tself.logKappa = np.array(table)[:,1:].astype(float)\n\n\t\tfile.close()\n\n\n\n\tdef Kappa(self,rho,T):\n\n\t\t\"\"\"\n\t\tSubsection that takes in a density and a temperature and interpolate/extrapolates within the \n\t\ttable in opacity.txt to find the best fit Kappa values.\n\t\n\t\t\"\"\"\n\n\t\t#extracting values from table\n\t\tself.ReadFile()\n\n\t\t#converting rho to log10R , T to log10T and so they are comparable with the values in the table\n\t\tR = np.log10(rho/(((T/1e6)**3)*1e3))\t\t\t\t\t\t\t\t#converting from SI to CGS\t\t\t\n\t\tT = np.log10(T)\n\n\t\tif self.logR[0] <= R <= self.logR[-1] and self.logT[0] <= T <= self.logT[-1]:\n\n\t\t\t\"\"\"\n\t\t\tCheking if the given density and temperature is within the bounds of the table. If they are,\n\t\t\tinterpolation is used to find a best fit values.\n\n\t\t\t\"\"\"\n\n\t\t\tf = interpolate.interp2d(self.logR, self.logT, self.logKappa)\n\t\t\t\n\t\t\tkappa = f(R,T)\n\t\t\t\n\t\t\t#returning kappa in SI\n\t\t\treturn (10**kappa)/10\t\t\t\t\t\t\t\n\n\n\n\t\telse:\n\n\t\t\t\"\"\"\n\t\t\tIf the density and temperature is out of bounds, an error message is printed, and we proceed with\n\t\t\textrapolating a best fit value. *script currently only gives a constant*\n\n\t\t\t\"\"\"\t\n\t\t\ti = 0\n\n\t\t\tif R > self.logR[-1] and i==0:\n\t\t\t\t# print(\"R out of bounds: too high.\")\n\t\t\t\t# print(\"Proceeding with constant extrapolation\")\n\t\t\t\ti += 1\n\n\t\t\tif R < self.logR[0] and i==0:\t\n\t\t\t\t# print(\"R out of bounds: too low.\")\n\t\t\t\t# print(\"Proceeding with constant extrapolation\")\n\t\t\t\ti += 1\n\n\t\t\tif T > self.logT[-1] and i==0:\t\n\t\t\t\t# print(\"T out of bounds: too high.\")\n\t\t\t\t# print(\"Proceeding with constant extrapolation\")\n\t\t\t\ti += 1\n\n\t\t\tif T < self.logT[0] and i==0:\t\n\t\t\t\t# print(\"T out of bounds: too low.\")\n\t\t\t\t# print(\"Proceeding with constant extrapolation\")\n\t\t\t\ti += 1\n\n\n\n\t\t\tf = interpolate.interp2d(self.logR, self.logT, self.logKappa)\n\t\t\tkappa = f(R,T)\n\n\t\t\t#returning kappa in SI\n\t\t\treturn (10**kappa)/10\t\t\n\n\n\n\n\tdef KappaSanity(self):\n\n\t\t\"\"\"\n\t\tSanity check for certian given values of logT and logR to check if Kappa function works properly\n\n\t\t\"\"\"\n\n\t\t#extracting values from table\n\t\tself.ReadFile()\n\n\n\t\tlogT_test = [3.750, 3.755, 3.755, 3.755, 3.755, 3.770, 3.780, 3.795, 3.770, 3.775, 3.780, 3.795, 3.800]\n\t\tlogR_test = [-6.00, -5.95, -5.80, -5.70, -5.55, -5.95, -5.95, -5.95, -5.80, -5.75, -5.70, -5.55, -5.50]\n\t\tKappa_test = np.zeros(len(logR_test))\n\n\t\tf = interpolate.interp2d(self.logR, self.logT, self.logKappa)\n\n\n\t\t#calculating the interpolated kappa values for the given test logT and logR\n\t\tfor i in range(len(logR_test)):\t\n\n\t\t\tKappa_test[i] = f(logR_test[i],logT_test[i])\n\t\t\n\n\t\t#printing the interpolated values which can be compared with the sanity check\n\t\tprint((10**Kappa_test)/10)\t\t\t\t\t\t\n\n\n\n\n\n\t\"\"\"\n\tThe following subroutines will solve some non linear differential equations which will be used to\n\tmodell the stellar core. They are to be used in the coming integration proccess.\n\n\t\"\"\"\n\n\n\tdef Density(self,P,T):\n\n\t\t\"\"\"\n\t\tThis subroutine takes in pressure and temperature and computes the density. \n\n\t\t\"\"\"\n\n\t\treturn ((P*self.mu*self.mu_u)/(self.k_B*T)) - \\\n\t\t((4*self.sigma*T**3*self.mu*self.mu_u)/(3*self.c*self.k_B))\n\n\n\n\tdef Pressure(self,rho,T):\n\n\t\t\"\"\"\n\t\tSubroutine that takes in density and temperature and computes the total pressure.\n\n\t\t\"\"\"\n\n\t\tP_rad = (4*self.sigma * T**4) / (3*self.c)\t\t\t\t\t#radiation pressure\n\t\tP_gas = (rho*self.k_B * T) / (self.mu * self.mu_u)\t\t\t#gas pressure\n\n\t\treturn P_rad + P_gas\t\t\t\t\t\t\t\t\t\t#returning the sum of the pressure\n\n\n\n\tdef drdm(self,rho,r):\n\n\t\t\"\"\"\n\t\tSubroutine that takes in density and radius, and computes the change in radius \n\t\twith respect to mass.\n\n\t\t\"\"\"\n\n\t\treturn 1 / (4 * np.pi * (r**2) * rho)\n\n\n\n\tdef dPdm(self, r, m):\n\n\t\t\"\"\"\n\t\tSubroutine that takes in radius and mass and computes the change in pressure \n\t\twith respect to mass.\n\n\t\t\"\"\"\n\n\t\treturn - (self.G * m) / (4 * np.pi * r**4)\n\n\n\n\tdef dLdm(self,rho,T):\n\n\t\t\"\"\"\n\t\tSubroutine that takes in density and temperature, and returns the change in \n\t\tluminosity with respect to mass.\n\n\t\t\"\"\"\n\n\t\treturn self.eps(rho,T)\n\n\n\n\tdef dTdm(self,kappa,L,r,T):\n\n\t\t\"\"\"\n\t\tSubroutine that takes in kappa, luminosity, radius and temperature, and returns \n\t\tthe change in Temperature with respect to mass.\n\n\t\t\"\"\"\n\n\t\treturn -((3*kappa*L)/(256 * np.pi**2 * self.sigma * r**4 * T**3))\n\n\n\n\tdef dm_Var(self,r,P,L,T,rho,kappa,m):\n\n\t\t\"\"\"\n\t\tSubroutine that returns a variable steplength dm. This is implemented so that we can find \n\t\thow big the steplength can be without ruining our calculations.\n\n\t\t\"\"\"\n\n\t\tp = 1e-3\t\t\t\t\t\t\t\t\t\t\t\t#fraction of the variable of interest\n\n\t\tdm_r = p*r/self.drdm(rho,r)\t\t\t\t\t\t\t\t#dm for the variable radius\n\t\tdm_P = p*P/self.dPdm(r,m)\t\t\t\t\t\t\t\t#dm for the variable pressure\n\t\tdm_L = p*L/self.dLdm(rho,T)\t\t\t\t\t\t\t\t#dm for the variable luminosity\n\t\tdm_T = p*T/self.dTdm(kappa,L,r,T)\t\t\t\t\t\t#dm for the variable temperature\n\n\t\tdm_list = [abs(dm_r), abs(dm_P), abs(dm_L), abs(dm_T)]\t#list of all dm_var values\n\n\t\t#returning the smallest value in the dm_list which is the dm to be used.\n\t\treturn -np.min(dm_list)\t\t\t\t\t\n\n\n\n\tdef Integration(self,n, R0, rho0, T0, dm):\n\n\t\t\"\"\"\n\t\tThis subroutine uses Eulers method to solve the differential equations above.\n\n\t\t\"\"\"\n\n\t\t#creating empty arrays for each parameter\n\t\tr = np.zeros(n)\t\t\t\t\t\t\t\t\t\t\t\t\n\t\trho = np.zeros(n)\t\n\t\tP = np.zeros(n)\n\t\tL = np.zeros(n)\n\t\tT = np.zeros(n)\n\t\tm = np.zeros(n)\t\n\t\tKappas = np.zeros(n)\t\t\t\t\t\t\t\t\t\t \t\t\n\t\n\t \t#setting the initial conditions\n\t\tr[0] = R0\t\t\t\t\t\t\t\t\t\t\n\t\trho[0] = rho0\t\t\n\t\tP[0] = self.Pressure(self.rho0, self.T0)\n\t\tL[0] = self.L0\n\t\tT[0] = T0\n\t\tm[0] = self.M0\n\t\tKappas[0] = self.Kappa(self.rho0, self.T0)\t\n\n\t\t#Using the Forward Euler integration method, as it is sufficient for our analysis.\n\t\tfor i in range(0, n-1):\n\n\n\t\t\tr[i+1] = r[i] + self.drdm(rho[i], r[i]) * dm\n\n\t\t\tP[i+1] = P[i] + self.dPdm(r[i], m[i]) * dm\n\n\t\t\tT[i+1] = T[i] + self.dTdm(Kappas[i] , L[i], r[i], T[i]) * dm\n\n\t\t\tL[i+1] = L[i] + self.dLdm(rho[i], T[i]) * dm\n\n\t\t\trho[i+1] = self.Density(P[i+1], T[i+1])\n\n\t\t\tKappas[i+1] = self.Kappa(rho[i+1], T[i+1])\n\n\t\t\tm[i+1] = m[i] + dm\n\n\n\t\t#returning the desired paramteres which are to be studied\n\t\treturn r, P, T, L, rho, m \n\n\n\n\tdef Var_Integration(self, n, R0, rho0, P0, T0):\n\n\t\t\"\"\"\n\t\tSubroutine which is identical to Integration(), except that it uses the variable steplength\n\t\tfunction instead of a constant dm. This section also allows for varying initial values.\n\n\t\t\"\"\"\n\n\t\t#creating empty arrays for each parameter\n\t\tr = np.zeros(n)\t\t\t\t\t\t\t\t\t\t\t\t\n\t\trho = np.zeros(n)\t\n\t\tP = np.zeros(n)\n\t\tL = np.zeros(n)\n\t\tT = np.zeros(n)\n\t\tm = np.zeros(n)\t\n\t\tKappas = np.zeros(n)\n\t\tepsilon = np.zeros(n)\t\t\t\t\t\t\t\t\t\t \t\t\n\t \t\n\t \t#setting the initial conditions\n\t\tr[0] = R0\t\t\t\t\t\t\t\t\t\t\n\t\trho[0] = rho0\t\n\t\tP[0] = P0\n\t\tL[0] = self.L0\n\t\tT[0] = T0\n\t\tm[0] = self.M0\n\t\tKappas[0] = self.Kappa(rho0, self.T0)\t\n\n\t\t#Using the Forward Euler integration method, as it is sufficient for our analysis.\n\t\tfor i in range(0, n-1):\n\n\t\t\t#calculating a new dm for each iteration to improve the steplength\n\t\t\tdm = self.dm_Var(r[i],P[i],L[i],T[i],rho[i],Kappas[i],m[i])\t\n\n\n\t\t\tr[i+1] = r[i] + self.drdm(rho[i], r[i]) * dm\n\n\t\t\tP[i+1] = P[i] + self.dPdm(r[i], m[i]) * dm\n\n\t\t\tT[i+1] = T[i] + self.dTdm(Kappas[i] , L[i], r[i], T[i]) * dm\n\n\t\t\tL[i+1] = L[i] + self.dLdm(rho[i], T[i]) * dm\n\n\t\t\trho[i+1] = self.Density(P[i+1], T[i+1])\n\n\t\t\tKappas[i+1] = self.Kappa(rho[i+1], T[i+1])\n\n\t\t\tepsilon[i] = self.eps(rho[i],T[i])\n\n\t\t\tm[i+1] = m[i] + dm\n\n\n\t\t\t#finding what the index for which iteration the variable passes through zero\n\t\t\tif m[i] <= 0:\n\t\t\t\tzero_it = i\n\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\tzero_it = n\n\n\n\t\t#returning the desired paramteres which are to be studied\n\t\treturn r, P, T, L, rho, epsilon, m , zero_it\n\n\n\n\tdef SanityPlots(self):\n\n\t\t\"\"\"\n\t\tSanity check for program with the initial parameters and a step length of -10^(-4)M_sol.\n\t\tPlotting my instance of the sanity check figure found in Appendix D, page 107.\n\n\t\t\"\"\"\n\n\t\tn = int(8e3)\t\t\t\t\t\t\t\t#set to 8e3 in order to stop at m=0\n\t\tdm = -self.M_sol/(int(1e4))\t\t\t\t\t#constant dm to compare the sanity figures\n\n\t\t#Solving the differential equations\n\t\tr, P, T, L, rho, m = self.Integration(n,self.R0, self.rho0, self.T0, dm)\t\n\n\t\t#plotts for each parameter used in hand-in document.\n\t\tplt.figure(1)\n\t\tplt.plot(m/self.M_sol, r/self.R_sol, color=\"royalblue\")\n\t\tplt.title(\"Radius vs. mass\")\n\t\tplt.xlabel(\"$M/M_{sun}$\")\n\t\tplt.ylabel(\"R/$R_{sun}$\")\n\t\t# plt.savefig(\"sanity_rho.pdf\")\n\n\t\tplt.figure(2)\n\t\tplt.plot(m/self.M_sol, L/self.L_sol, color=\"royalblue\")\n\t\tplt.title(\"Density vs. mass\")\n\t\tplt.xlabel(\"$M/M_{sun}$\")\n\t\tplt.ylabel(\"L/$L_{sun}$\")\n\t\t# plt.savefig(\"sanity_rho.pdf\")\n\n\t\tplt.figure(3)\n\t\tplt.plot(m/self.M_sol, T/1e6, color=\"royalblue\")\n\t\tplt.title(\"Temperature vs. mass\")\n\t\tplt.xlabel(\"$M/M_{sun}$\")\n\t\tplt.ylabel(\"T[MK]\")\n\t\t# plt.savefig(\"sanity_rho.pdf\")\n\n\t\tplt.figure(4)\n\t\tplt.semilogy(m/self.M_sol, rho/self.avgrho_sol, color=\"royalblue\")\n\t\tplt.title(\"Density vs. mass\")\n\t\tplt.xlabel(\"$M/M_{sun}$\")\n\t\tplt.ylabel(r\"$\\rho/\\rho_{sun}$\")\n\t\tplt.ylim([1,10])\n\t\t# plt.savefig(\"sanity_rho.pdf\")\n\n\t\tplt.show()\n\n\n\n\n\tdef VaryingInitParams(self):\n\n\t\t\"\"\"\n\t\tThis subsection solves the differential equations with varying steplength for a set of \n\t\tdifferent initial parameters and plots the different results. The plotting function has been\n\t\trepeated for all variables of interest. The plotting is not vectorized, and in order to save\n\t\tspace, i only attached the plotting for a single variable.\n\n\t\t\"\"\"\n\n\t\tn = int(1e4)\t\t\t\t\t\t\t\t\t\t\t\t\t#number of iterations\n\n\n\t\t#different intital conditions to be tested\t\t\t\t\t\t\t\t\t\n\t\tR0 = [self.R0/5.2, self.R0/5, self.R0/4.5, self.R0/4, self.R0/3, self.R0/2, \\\n\t\tself.R0, 2*self.R0, 3*self.R0, 4*self.R0]\t\t\n\n\t\tT0 = [self.T0/5.2, self.T0/5, self.T0/4.5, self.T0/4, self.T0/3, self.T0/2, \\\n\t\tself.T0, 2*self.T0, 3*self.T0, 4*self.T0]\t\t\n\n\t\trho0 = [self.rho0/5.2, self.rho0/5, self.rho0/4.5, self.rho0/4, self.rho0/3, self.rho0/2, \\\n\t\tself.rho0, 2*self.rho0, 3*self.rho0, 4*self.rho0]\t\n\n\t\tp0 = self.Pressure(self.rho0, self.T0)\n\t\tP0 = [p0/5.2, p0/5, p0/4.5, p0/4, p0/3, p0/2, p0, 2*p0, 3*p0, 4*p0]\t\t\t\n\n\n\t\t#The scaling constants to be included in the legend\n\t\tlabels = [\"1/5.2\", \"1/5\", \"1/4.5\", \"1/4\", \"1/3\", \"1/2\", \"1\", \"2\", \"3\", \"4\"]\n\n\n\t\t#Solving the differential equation for different initial conditions\n\t\tfor i in range(len(rho0)):\n\n\t\t\t#Varying radius, all other parameters are constant\n\t\t\t# r, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, R0[i], self.rho0, \\\n\t\t\t# \tself.Pressure(self.rho0, self.T0), self.T0)\t\n\n\t\t\t# Varying temperature, all other parameters are constant\n\t\t\t# r, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, self.R0, self.rho0, \\\n\t\t\t# \tself.Pressure(self.rho0, T0[i]), T0[i]) \n\n\t\t\t#Varying density, all other parameters are constant\n\t\t\t# r, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, self.R0, rho0[i], \\\n\t\t\t# \tself.Pressure(rho0[i], self.T0), self.T0)\t\n \t\t\t\n \t\t\t# Varyin pressure, all other parameters are constant\n\t\t\tr, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, self.R0, self.rho0, \\\n\t\t\t\tP0[i], self.T0)\t\n\n\n\t\t\t#Plotting the figures with varying parameters\n\t\t\tplt.figure(1)\n\t\t\tplt.plot(m[:zero_it]/self.M0, r[:zero_it]/self.R0, label=r\"%s $T_0$\"%labels[i])\n\t\t\tplt.title(r\"Radius vs. mass for varying $T_0$\")\n\t\t\tplt.legend()\n\t\t\tplt.xlabel(\"$M/M_0$\")\n\t\t\tplt.ylabel(\"R/$R_0$\")\n\t\t\tplt.grid(linewidth=0.5)\n\t\t\t# plt.savefig(\"R_var_T0.pdf\")\n\n\t\t\tplt.figure(2)\n\t\t\tplt.plot(m[:zero_it]/self.M0, L[:zero_it]/self.L0, label=r\"%s $T_0$\"%labels[i])\n\t\t\tplt.title(r\"Luminosity vs. mass for varying $T_0$\")\n\t\t\tplt.legend()\n\t\t\tplt.xlabel(\"$M/M_0$\")\n\t\t\tplt.ylabel(\"L/$L_0$\")\n\t\t\tplt.grid(linewidth=0.5)\n\t\t\t# plt.savefig(\"L_var_T0.pdf\")\n\n\t\t\tplt.figure(3)\n\t\t\tplt.plot(m[:zero_it]/self.M0, T[:zero_it]/1e6, label=r\"%s $T_0$\"%labels[i])\n\t\t\tplt.title(r\"Temperature vs. mass for varying $T_0$\")\n\t\t\tplt.legend()\n\t\t\tplt.xlabel(\"$M/M_0$\")\n\t\t\tplt.ylabel(\"T[MK]\")\n\t\t\tplt.grid(linewidth=0.5)\n\t\t\t# plt.savefig(\"T_var_T0.pdf\")\n\n\t\t\tplt.figure(4)\n\t\t\tplt.semilogy(m[:zero_it]/self.M0, rho[:zero_it]/self.avgrho_sol, label=r\"%s $T_0$\"%labels[i])\n\t\t\tplt.title(r\"Density vs. mass for varying $T_0$\")\n\t\t\tplt.legend(loc=\"upper right\")\n\t\t\tplt.xlabel(\"$M/M_0$\")\n\t\t\tplt.ylabel(r\"$\\rho/\\rho_0$\")\n\t\t\t# plt.ylim([1,10])\n\t\t\tplt.grid(linewidth=0.5)\n\t\t\t# plt.savefig(\"rho_var_T0.pdf\")\n\n\t\tplt.show()\n\n\n\n\tdef BestParameters(self):\n\n\t\t\"\"\"\n\t\tRedefining our initial parameters to be the newly found optimal onces.\n\n\t\t\"\"\"\n\n\t\t#scaling values for parameter the best fit parameters\n\n\t\tR0_scale = 0.537\n\t\tT0_scale = 0.895\n\t\trho0_scale = 0.479\n\n\n\t\t#alternative values also leading to a solution with the goal\n\t\t# R0_scale = 0.56\n\t\t# T0_scale = 0.35\n\t\t# rho0_scale = 0.8 \n\n\t\tself.R0_new = R0_scale*self.R0\n\t\tself.T0_new = T0_scale*self.T0\n\t\tself.rho0_new = rho0_scale*self.rho0\n\n\t\treturn R0_scale , rho0_scale, T0_scale\n\n\n\n\tdef BestParameter_Plots(self):\n\n\t\t\"\"\"\n\t\tSolving the differential equation for the best fit parameters aquired. The parameters are scaled\n\t\tin order to produce a most physical model of a star. The different variables are then plotted against\n\t\tthe mass. \n\n\t\t\"\"\"\n\n\t\t#number of iterations when solving the differential equations\n\t\tn = int(1e4)\n\n\t\t#Using the new initial parameters\n\t\tR0_scale,rho0_scale,T0_scale = self.BestParameters()\n\n\t\t#solving the differential equations with the new parameters\n\t\tr, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, self.R0_new, self.rho0_new, \\\n\t\t\t\tself.Pressure(self.rho0_new, self.T0_new), self.T0_new)\n\n\n\t\t#checking for different scale values to find the smallest error\n\t\tprint(\"R:\", r[-1]/self.R0)\n\t\tprint(\"L:\", L[-1]/self.L0)\n\t\tprint(\"M:\", m[-1]/self.M0)\n\n\n\t\t# plotting the results of the best parameters\n\t\tplt.figure(1)\n\t\tplt.plot(m/self.M0, r/self.R0, label = \"R(M)\", color = \"royalblue\")\n\t\tplt.title(r\"Parameters: $R = %gR_0$, $\\rho = %g\\rho_0$, $T = %gT_0$\" %(R0_scale,rho0_scale,T0_scale))\n\t\tplt.xlabel(\"$M/M_0$\")\n\t\tplt.ylabel(\"R/$R_0$\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"final_r.pdf\")\n\n\t\tplt.figure(2)\n\t\tplt.plot(m/self.M0, L/self.L0, label = \"L(M)\", color = \"royalblue\")\n\t\tplt.title(r\"Parameters: $R = %gR_0$, $\\rho = %g\\rho_0$, $T = %gT_0$\" %(R0_scale,rho0_scale,T0_scale))\n\t\tplt.xlabel(\"$M/M_0$\")\n\t\tplt.ylabel(\"L/$L_0$\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"final_l.pdf\")\n\n\t\tplt.figure(3)\n\t\tplt.plot(m/self.M0, T/1e6, label = \"T(M)\", color = \"royalblue\")\n\t\tplt.title(r\"Parameters: $R = %gR_0$, $\\rho = %g\\rho_0$, $T = %gT_0$\" %(R0_scale,rho0_scale,T0_scale))\n\t\tplt.xlabel(\"$M/M_0$\")\n\t\tplt.ylabel(\"T[MK]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"final_T.pdf\")\n\n\t\tplt.figure(4)\n\t\tplt.plot(m/self.M0, rho/self.avgrho_sol, label = r\"$\\rho(M)$\", color = \"royalblue\")\n\t\tplt.title(r\"Parameters: $R = %gR_0$, $\\rho = %g\\rho_0$, $T = %gT_0$\" %(R0_scale,rho0_scale,T0_scale))\n\t\tplt.xlabel(\"$M/M_0$\")\n\t\tplt.ylabel(r\"$\\rho/\\rho_0$\")\n\t\tplt.legend()\n\t\t# plt.ylim([1,10])\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"final_rho.pdf\")\n\n\n\n\n\t\t#ploting all variables as a function of radius instead of mass\n\t\tplt.figure(5)\n\t\tplt.plot(r, T, label = \"$T(R)$\", color = \"royalblue\")\n\t\tplt.title(\"Temperature vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(\"Temperature [K]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"rT_alternative.pdf\")\n\n\t\tplt.figure(6)\n\t\tplt.plot(r, L, label = \"$L(R)$\", color = \"royalblue\")\n\t\tplt.title(\"Luminosity vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(\"Luminosity [J]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"rL.pdf\")\n\n\t\tplt.figure(7)\n\t\tplt.semilogy(r, epsilon, label = \"$\\epsilon (R)$\", color = \"royalblue\")\n\t\tplt.title(\"$\\epsilon$ vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(\"$\\epsilon [J/kg]$\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"reps.pdf\")\n\n\t\tplt.figure(8)\n\t\tplt.semilogy(r, rho, label = r\"$\\rho (R)$\", color = \"royalblue\")\n\t\tplt.title(\"$Density$ vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(r\"$\\rho$ [kg/m^3]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"rrho.pdf\")\n\n\t\tplt.figure(9)\n\t\tplt.semilogy(r, P, label = \"$P(R)$\", color = \"royalblue\")\n\t\tplt.title(\"$Pressure$ vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(\"Pressure [Pa]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"rP.pdf\")\n\n\t\tplt.figure(10)\n\t\tplt.plot(r, m, label = \"$M(R)$\", color = \"royalblue\")\n\t\tplt.title(\"$Mass$ vs. radius\")\n\t\tplt.xlabel(\"Radius [m]\")\n\t\tplt.ylabel(\"Mass [kg]\")\n\t\tplt.legend()\n\t\tplt.grid(linewidth=0.5)\n\t\t# plt.savefig(\"rm.pdf\")\n\n\t\tplt.show()\n\n\n\n\tdef ParamEstimation(self):\n\n\t\t\"\"\"\n\t\tTrying to estimate the best fit parameters\n\n\t\t\"\"\"\n\n\t\tn = int(1e4)\n\t\tn_param = 5\t\t\t\t\t\t\t\t\t\t\t#How many different params we check\n\n\n\t\tR_param = np.linspace(0.5*self.R0, 0.6*self.R0, n_param)\n\t\trho_param = np.linspace(0.75*self.rho0, 0.85*self.rho0, n_param)\n\t\tT_param = np.linspace(0.3*self.T0, 0.4*self.T0, n_param)\n\n\t\tprev_r = 1e3\n\t\tprev_L = 1e3\n\t\tprev_sum = 1e3\n\n\t\tfor Ri in R_param:\t\t\t\t\t\t\t#checking different radi\n\n\t\t\tfor rhoi in rho_param:\t\t\t\t\t#checking different densities\n\n\t\t\t\tfor Ti in T_param:\t\t\t\t\t#checking different temperatures\n\n\t\t\t\t#solving the equations for a combination of the parameters\n\t\t\t\t\tr, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(n, Ri, rhoi, \\\n\t\t\t\tself.Pressure(rhoi, Ti), Ti)\n\n\t\t\t\t\t#condition with the lowest sum of errors\n\t\t\t\t\tif prev_r > (r[-1])/(self.R0) and prev_L > (L[-1])/(self.L0):\n\n\t\t\t\t\t\tprev_r = (r[-1])/(self.R0)\n\n\t\t\t\t\t\tprev_L = (L[-1])/(self.L0)\n\n\n\t\t\t\t\t\t#returning the best fit parameters\n\n\t\t\t\t\t\tr_best_scale = Ri/self.R0\n\n\t\t\t\t\t\trho_best_scale = rhoi/self.rho0\n\n\t\t\t\t\t\tT_best_scale = Ti/self.T0\n\n\n\t\treturn r_best_scale, rho_best_scale, T_best_scale\n\n\n\n\tdef dmTests(self):\n\n\t\t\"\"\"\n\t\tIn this subsection, varius dm values are tested to study how the different features of the \n\t\tstar behaves differently. This is also to motive the use of variable steplength.\n\n\t\t\"\"\"\n\n\t\t#defining the different dm values that are to be tested, and corresponding number of iterations\n\t\tn_list = [(int(1e4)), (int(1e3)), 250, 100, 50, 25, 12]\n\t\tdm_list = [-self.M0/n_list[0], -self.M0/n_list[1], -self.M0/n_list[2], -self.M0/n_list[3],\\\n\t\t -self.M0/n_list[4], -self.M0/n_list[5], -self.M0/n_list[6]]\n\n\t\t#activating the new parameters\n\t\tself.BestParameters()\n\n\t\t# print(dm_list)\n\t\t#Solving the differential equations for different dm and n\n\t\tfor i in range(len(dm_list)):\n\n\t\t\tr, P, T, L, rho, m = self.Integration(n_list[i],self.R0_new, self.rho0_new, self.T0_new, dm_list[i])\t\n\n\t\t\t#plotting seperate figures for each dm\n\t\t\tplt.figure(1)\n\t\t\tplt.plot(m/self.M0, r/self.R0, label=\"$\\partial m$ = %.2g\"%dm_list[i])\n\t\t\tplt.title(\"Radius vs. mass for varying $\\partial m$ \")\n\t\t\tplt.xlabel(\"$M/M_0$\")\n\t\t\tplt.ylabel(\"R/$R_0$\")\n\t\t\tplt.legend()\n\t\t\tplt.grid(linewidth=0.5)\n\n\t\t\n\t\t# plt.savefig(\"dmtest.pdf\")\n\t\tplt.show()\n\n\n\n\tdef Phyiscal(self):\n\n\t\t\"\"\"\n\t\tTesting to what extend our model of the core behaves as a true star\n\n\t\t\"\"\"\n\n\n\t\t#Using the best fit initial parameters\n\t\tR0_scale,rho0_scale,T0_scale = self.BestParameters()\n\n\t\t#solving the differential equations with the new parameters\n\t\tr, P, T, L, rho, epsilon, m, zero_it = self.Var_Integration(int(1e4), self.R0_new, self.rho0_new, \\\n\t\t\t\tself.Pressure(self.rho0_new, self.T0_new), self.T0_new)\n\n\n\t\t#theoretical central temperature of a star\n\t\tT_core_theoretical = (1.5*10**7)*(self.M0/self.M_sol)**(1/3)\t#K\n\n\t\t#theoretical radius of a star\n\t\tR_teo = 10**11 * (self.M0/self.M_sol)**(2/3)/100\t\t\t\t#m\n\n\t\tprint(R_teo/self.R0_new,self.R0,self.R0_new)\n\n\n\n\t\t\"\"\"\n\t\tFinding the radius of our core\n\n\t\t\"\"\"\n\n\t\t#finding which iteration satisfies our luminosity < 0.995 goal\n\t\tit = (np.where(L>= 0.995*np.max(L)))[-1][-1]\n\n\t\t#the core radius is simply the radius at this iteration\n\t\tcore_radius = r[it]\n\n\t\t#finding the average core temperature of our star\n\t\tT_core = np.average(T[it:-1])# print(np.average(T[2242:-1]))\n\n\t\t#printing the core radius along with what percentage of our new R0 value our core reaches out to\n\t\t# print(core_radius, core_radius/self.R0_new)\n\n\t\t#priting temperature values\n\t\t# print(T_core_theoretical, T_core)\n\n\n\n\nif __name__ == \"__main__\":\n\n\t\"\"\"\n\tTesting the program. Stuff written here will not be imported along with the class into other files.\n\n\t\"\"\"\n\n\tStellar = CoreModel()\n\t# Stellar.ReadFile()\n\t# Stellar.KappaSanity()\n\t# Stellar.SanityPlots()\n\t# Stellar.dmTests() \n\t# Stellar.VaryingInitParams()\n\t# Stellar.BestParameter_Plots()\n\t# Stellar.Phyiscal()\n\t# r_best, rho_best, T_best = Stellar.ParamEstimation()\n\n\n\n\n\n\n\n\n\n","sub_path":"Project1/Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":21971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"255157868","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 ('mensajes', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='mensaje',\n name='message',\n field=models.TextField(default=''),\n preserve_default=False,\n ),\n ]\n","sub_path":"mensajes/migrations/0002_mensaje_message.py","file_name":"0002_mensaje_message.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"313563720","text":"# Copyright 2010 Jacob Kaplan-Moss\n# Copyright 2011 OpenStack Foundation\n# Copyright 2011 Piston Cloud Computing, Inc.\n\n# All Rights Reserved.\n\"\"\"\nOpenStack Client interface. Handles the REST calls and responses.\n\"\"\"\n\nimport logging\nimport os\nimport sys\nimport time\nimport urlparse\n\nimport pkg_resources\nimport requests\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n# Python 2.5 compat fix\nif not hasattr(urlparse, 'parse_qsl'):\n import cgi\n urlparse.parse_qsl = cgi.parse_qsl\n\n\nclass HTTPClient(object):\n\n USER_AGENT = 'python-client'\n\n def __init__(self, server_ip=None, server_port=None):\n\n self.management_url = 'http://%s:%s' % (server_ip, server_port)\n\n def set_management_url(self, url):\n self.management_url = url\n\n def request(self, url, method, **kwargs):\n kwargs.setdefault('headers', kwargs.get('headers', {}))\n #kwargs['headers']['User-Agent'] = self.USER_AGENT\n #kwargs['headers']['Accept'] = 'application/json'\n #kwargs['headers']['X-Auth-Project-Id'] = 'admin'\n kwargs['headers']['Accept-Encoding'] = 'identity'\n kwargs['headers']['Content-Type'] = 'application/json'\n kwargs['headers']['X-Auth-Token'] = '3d16e2a3d0df445aa425b9a49429431b'\n \n if 'body' in kwargs:\n kwargs['headers']['Content-Type'] = 'application/json'\n kwargs['data'] = json.dumps(kwargs['body'])\n del kwargs['body']\n\n resp = requests.request(\n method,\n url,\n **kwargs)\n\n if resp.text:\n if resp.status_code == 400:\n if ('Connection refused' in resp.text or\n 'actively refused' in resp.text):\n raise \"connection refused!\"\n try:\n body = json.loads(resp.text)\n except ValueError:\n pass\n body = None\n else:\n body = None\n\n #if resp.status_code >= 400:\n # raise \"response >= 400\" \n\n return resp, body\n\n def _cs_request(self, url, method, **kwargs):\n resp, body = self.request(self.management_url + url, method,\n **kwargs)\n return resp, body\n\n def get(self, url, **kwargs):\n return self._cs_request(url, 'GET', **kwargs)\n\n def post(self, url, **kwargs):\n return self._cs_request(url, 'POST', **kwargs)\n\n def put(self, url, **kwargs):\n return self._cs_request(url, 'PUT', **kwargs)\n\n def delete(self, url, **kwargs):\n return self._cs_request(url, 'DELETE', **kwargs)\n","sub_path":"tests/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"619320562","text":"from uuid import uuid4\nfrom django.db import models\nfrom .application import Application\n\nclass Reference(models.Model):\n \"\"\"\n Model for REFERENCE table\n \"\"\"\n reference_id = models.UUIDField(primary_key=True, default=uuid4)\n application_id = models.ForeignKey(Application, on_delete=models.CASCADE, db_column='application_id')\n reference = models.IntegerField(blank=True)\n first_name = models.CharField(max_length=100, blank=True)\n last_name = models.CharField(max_length=100, blank=True)\n title = models.CharField(max_length=100, blank=True)\n other_title = models.CharField(max_length=100, blank=True, null=True)\n relationship = models.CharField(max_length=100, blank=True)\n years_known = models.IntegerField(blank=True)\n months_known = models.IntegerField(blank=True)\n street_line1 = models.CharField(max_length=100, blank=True)\n street_line2 = models.CharField(max_length=100, blank=True)\n town = models.CharField(max_length=100, blank=True)\n county = models.CharField(max_length=100, blank=True)\n country = models.CharField(max_length=100, blank=True)\n postcode = models.CharField(max_length=8, blank=True)\n phone_number = models.CharField(max_length=50, blank=True)\n email = models.CharField(max_length=100, blank=True)\n\n @property\n def timelog_fields(self):\n \"\"\"\n Specify which fields to track in this model once application is returned.\n\n Used for signals only. Check base.py for available signals.\n This is used for logging fields which gonna be updated by applicant\n once application status changed to \"FURTHER_INFORMATION\" on the arc side\n\n Returns:\n tuple of fields which needs update tracking when application is returned\n \"\"\"\n\n return (\n 'reference',\n 'first_name',\n 'last_name',\n 'relationship',\n 'years_known',\n 'months_known',\n 'street_line1',\n 'street_line2',\n 'town',\n 'county',\n 'country',\n 'postcode',\n 'phone_number',\n 'email'\n )\n\n @classmethod\n def get_id(cls, app_id):\n return cls.objects.get(application_id=app_id)\n\n def get_address(self):\n return self.street_line1 + ', ' + self.street_line2 + ', ' + self.town + ', ' + self.postcode\n\n def get_time_known(self):\n months = self.months_known\n months_str = str(months) + ' Months' if months != 1 else str(months) + ' Month'\n years = self.years_known\n years_str = str(years) + ' Years, ' if years != 1 else str(years) + ' Year, '\n return years_str + months_str\n \n def get_ref_as_string(self):\n return 'First' if self.reference == 1 else 'Second'\n\n def get_summary_table(self):\n if self.title is not None:\n return [\n {\"title\": self.get_ref_as_string() + \" reference\", \"id\": self.pk},\n {\"name\": \"Title\", \"value\": self.title},\n {\"name\": \"Name\", \"value\": self.first_name + ' ' + self.last_name},\n {\"name\": \"How they know you\", \"value\": self.relationship},\n {\"name\": \"Known for\", \"value\": self.get_time_known()},\n {\"name\": \"Address\", \"value\": self.get_address()},\n {\"name\": \"Phone number\", \"value\": self.phone_number},\n {\"name\": \"Email address\", \"value\": self.email}\n ]\n else:\n return [\n {\"title\": self.get_ref_as_string() + \" reference\", \"id\": self.pk},\n {\"name\": \"Name\", \"value\": self.first_name + ' ' + self.last_name},\n {\"name\": \"How they know you\", \"value\": self.relationship},\n {\"name\": \"Known for\", \"value\": self.get_time_known()},\n {\"name\": \"Address\", \"value\": self.get_address()},\n {\"name\": \"Phone number\", \"value\": self.phone_number},\n {\"name\": \"Email address\", \"value\": self.email}\n ]\n\n\n class Meta:\n db_table = 'REFERENCE'\n ordering = ['reference']\n","sub_path":"arc_application/models/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"477021683","text":"#!/usr/bin/env python\n\n# Add personal packages directory to path\nimport sys\nsys.path.append('/home/jaime/Documents/Python Code')\n\n# Import other modules\nimport os\nimport pickle\nimport xml.etree.ElementTree as et\n\n# Import custom modules\nimport iclrt_tools.data_sets.waveforms as wvf\n\nparent = '/home/jaime/Documents/Python Code/Data Sets'\ndata_files = '/home/jaime/Documents/Python Code/Data Sets/DataFiles'\n\nlst = os.listdir(data_files)\nfiles = [data_files + '/' + l for l in lst if '.p' in l]\n\nfor f in files:\n old_data = pickle.load(open(f, 'rb'))\n print('Opened file: {0}'.format(f))\n\n data = {}\n e = f[-24:-18]\n rs = f[-3:-2]\n\n xml_file = parent + '/XML/{e}.xml'.format(e=e)\n\n root = et.parse(xml_file)\n\n day = root.find('date').find('day').text\n month = root.find('date').find('month').text\n year = root.find('date').find('year').text[-2:]\n\n eventDate = '%s%s%s' % (month, day, year)\n eventName = root.find('name').text\n\n for rss in root.iter('return_stroke'):\n r_s = int(rss.find('number').text)\n\n if r_s != int(rs):\n continue\n\n print(' Processing RS: {0}'.format(r_s))\n\n for scope in rss.find('data').iter('scope'):\n scope_data = {}\n scope_name = scope.find('name').text\n scope_type = scope.find('type').text\n scope_path = scope.find('path').text\n\n print(' Processing scope: {0}'.format(scope_name))\n\n for meas in scope.iter('measurement'):\n measurement_name = meas.find('name').text\n\n if measurement_name not in old_data.keys():\n continue\n\n measurement_file = meas.find('file').text\n file_name = '{0}/{1}'.format(scope_path,\n measurement_file)\n trace_number = int(meas.find('trace').text)\n cal_factor = float(meas.find('cal_factor').text)\n units = meas.find('units').text\n distance = float(meas.find('distance').text)\n t_start = float(meas.find('t_start').text)\n t_end = float(meas.find('t_end').text)\n\n print(\" Processing '{0}'\".format(measurement_name))\n\n measurement = wvf.Waveform(flash_name=eventName,\n event_date=eventDate,\n return_stroke=r_s,\n measurement_name=measurement_name,\n scope_name=scope_name,\n scope_type=scope_type,\n file_name=file_name,\n trace_number=trace_number,\n cal_factor=cal_factor,\n units=units, distance=distance,\n t_start=t_start, t_end=t_end)\n\n scope_data[measurement_name] = measurement\n\n data.update(scope_data)\n\n for key in data:\n print(\" Getting data for '{0}'\".format(key))\n data[key].set_data(old_data[key]['data'])\n data[key].set_time(old_data[key]['time'])\n # data[key].set_plot()\n\n new_file = '{0}_oo{1}'.format(f[:-2], f[-2:])\n print('Saving the data to: {0}'.format(new_file))\n pickle.dump(data, open(new_file, 'wb'))\n\nsys.exit(1)\n\n# Remove the plots that were added to the Waveform objects\nevents ={'UF0920-3': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0920_data_061809_rs3.p',\n 'UF0925-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0925_data_062909_rs1.p',\n 'UF0925-6': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0925_data_062909_rs6.p',\n 'UF0929-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0929_data_063009_rs1.p',\n 'UF0929-5': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0929_data_063009_rs5.p',\n 'UF0932-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF0932_data_070709_rs1.p',\n 'UF1309-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF1309_data_060913_rs1.p',\n 'UF1333-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF1333_data_081713_rs1.p',\n 'UF1426-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF1426_data_071414_rs1.p',\n 'UF1442-1': '/home/jaime/Documents/Python Code/Data Sets/DataFiles/UF1442_data_080214_rs1.p'}\n\nfor key in sorted(events.keys()):\n print(\"Converting {}\".format(key))\n out_file = events[key] #[:-5] + events[key][-2:]\n out = {}\n data = pickle.load(open(events[key], 'rb'))\n\n for k in sorted(data.keys()):\n print(\" {}\".format(k))\n flash_name = data[k].flash_name\n date = data[k].date\n return_stroke = data[k].return_stroke\n if return_stroke == 0:\n return_stroke = 1\n\n measurement_name = data[k].measurement_name\n scope_name = data[k].scope_name\n scope_type = data[k].scope_type\n file_name = data[k].file_name\n trace_number = data[k].trace_number\n cal_factor = data[k].cal_factor\n units = data[k].units\n distance = data[k].distance\n t_start = data[k].t_start\n t_end = data[k].t_end\n ddata = data[k].data\n dataTime = data[k].dataTime\n\n w = wave.Waveform(flash_name, date, return_stroke,\n measurement_name, scope_name, scope_type,\n file_name, trace_number, cal_factor, units,\n distance, t_start, t_end)\n w.set_data(ddata)\n\n if np.diff(data[k].dataTime)[0] < 1e-6:\n w.set_dataTime(dataTime)\n else:\n w.set_dataTime(dataTime*1e-6)\n\n out[k] = w\n\n pickle.dump(out, open(out_file,'wb'))\n\nsys.exit(1)\n","sub_path":"iclrt_tools/data_sets/convert_to_oo.py","file_name":"convert_to_oo.py","file_ext":"py","file_size_in_byte":5944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"435931770","text":"# coding=utf-8\n# author=XingLong Pan\n# date=2016-12-05\n\n# 你可以理解为scrapy框架中的item\nmovie = {\n 'douban_id': 0,\n 'title': '',\n 'directors': '',\n 'scriptwriters': '',\n 'actors': '',\n 'types': '',\n 'release_region': '',\n 'release_date': '',\n 'alias': '',\n 'languages': '',\n 'duration': 0,\n 'score': 0.0,\n 'description': '',\n 'tags': '',\n 'link': '',\n 'posters': '',\n 'recommendations': '',\n 'comments': '',\n 'want_to_watch': 0,\n 'title_short': '',\n 'box_office': '',\n}\ncomment = {\n 'votes': 0,\n 'rating': '',\n 'description': ''\n}\nactor = {\n 'douban_id': '',\n 'name': '',\n 'sex': '',\n 'constellation': '',\n 'birthday': '',\n 'profession': '',\n 'nickname': '',\n 'family_members': '',\n 'imdb_number': '',\n 'introduction': '',\n 'popular_movies': ''\n}\n","sub_path":"page_parser/Entity.py","file_name":"Entity.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"40820412","text":"def solution(n, results):\n win = {}\n lost = {}\n for i in range(1, n + 1):\n win[i] = set()\n lost[i] = set()\n for r in results:\n x, y = r[0], r[1]\n if x not in win:\n win[x] = []\n if y not in lost:\n lost[y] = []\n win[x].add(y)\n lost[y].add(x)\n\n for i in range(n):\n for y in lost[i + 1]:\n win[y].update(win[i + 1])\n for x in win[i + 1]:\n lost[x].update(lost[i + 1])\n\n answer = 0\n for i in range(1, n + 1):\n if len(win[i].union(lost[i])) == n - 1:\n answer += 1\n return answer","sub_path":"Programmers/순위.py","file_name":"순위.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"240899455","text":"#!/bin/bash/env python\nimport sys\nimport pyodbc\nimport requests\nimport json\nimport socket\nimport time\n\nfrom bs4 import BeautifulSoup as bs\n\n\ndef remove_client_from_workflow(account_ID, workflow_remove):\n # Remove a client from a workflow\n url = 'http://ctg-vm-dbus01:7121/Resonance.Databus.Workflow.WCF/ws/WorkflowAccountRemove?accountID='+account_ID+'&workflowName='+workflow_remove\n\n response = requests.get(url)\n soup = bs(response.content, 'html.parser')\n print(soup.find('success'))\n print(\"Removed client {0} from workflow: {1}\" .format(account_ID, workflow_remove))\n\ndef add_client_to_workflow(account_ID, workflow_add):\n url = 'http://ctg-vm-dbus01:7121/Resonance.Databus.Workflow.WCF/ws/WorkflowAccountAdd?accountID='+account_ID+'&workflowName='+workflow_add+'&disassociateAccountWithPreviousWorkflowRabbitExchanges=true&setupSubjectManagerBridge=true&updateWSCLAppSetting=true'\n response = requests.get(url)\n soup = bs(response.content, 'html.parser')\n\n print(soup.find('success'))\n print(\"Added client {0} to workflow: {1}\" .format(account_ID, workflow_add))\n\n\nif __name__ == '__main__':\n remove, add = map(str, input(\"Enter name of workflow to remove client and name of workflow to add client:\\n\").split())\n account = 'ActiveLife'\n remove_client_from_workflow(account, remove)\n time.sleep(3)\n add_client_to_workflow(account, add)\n time.sleep(3)\n client_to_standard_workflow, standard_workflow = map(str, input(\"Enter client name and standard workflow: \\n\").split())\n\n add_client_to_workflow(client_to_standard_workflow, standard_workflow)\n\n\n","sub_path":"migration_automation_sql_python/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"194925342","text":"\n\ndef get_back(href, title):\n return {\n 'href' : href,\n 'title' : title,\n }\n \ndef build_table(model, fields, fields_for_filter, filter, href_header):\n '''\n ***\n '''\n filter_for_context = [field for name, field in model.to_fields().items() if name in fields]\n for field in filter:\n if field['name'] in fields_for_filter:\n field['is_filter'] = True\n \n rows = [value for name, value in model.objects.get(**filter) if name in fields]\n \n return {\n 'header' : {'href' : href_header, 'fields' : filter_for_context},\n 'rows' : rows,\n \n }\n\n\n","sub_path":"eva/context_builder.py","file_name":"context_builder.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"640467799","text":"from django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('court/', include('court.urls')),\n path('partner/', include('partner.urls')),\n path('bounty/', include('bounty.urls')),\n path('', include('common.urls')),\n]\n","sub_path":"oathprotocol/oathprotocol/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"193531982","text":"from nltk.corpus import stopwords\nfrom nltk import stem\nimport re\nimport unidecode\n\nimport language\n\nSTOP_WORDS = {\n\tshortStr : stopwords.words(language.FULL_LANGUAGE_STRINGS[shortStr]) for\n\tshortStr in language.SUPPORTED_LANGUAGES\n}\nSTEMMERS = {\n\tshortStr : stem.SnowballStemmer(language.FULL_LANGUAGE_STRINGS[shortStr]) for\n\tshortStr in language.SUPPORTED_LANGUAGES\n}\n\ndef word_tokenize(text):\n\t\"\"\"\n\tA simple word tokenizer. Unicode strings are converted to ascii\n\tusing unidecode, to normalize the text (e.g., remove accents)\n\tand make sure that tokenization is done properly.\n\t\"\"\"\n\treturn filter(len, re.split(\"[^A-Za-z]\", unidecode.unidecode(text)))\n\ndef normalize(tokens):\n\t\"\"\"\n\tA simple normalizer. The only treatment performed is lower-casing.\n\t\"\"\"\n\treturn map(str.lower, tokens)\n \ndef simple_preprocessing(text, textLanguage, removeStopWords=True, stem=True):\n\t\"\"\"\n\tPreprocessing function: tokenizes the text into words, \n\tlower-case all words and optionally,\n\tperforms stop words removal and stemming\n\n\ttext: the string to preprocess\n\tremoveStopWords: boolean indicating whether to filter stop words (default True)\n\tstem: boolean indicating whether to stem words (default True)\n\n\treturns: a list of tokens (words or stems)\n\t\"\"\"\n\tif textLanguage not in language.SUPPORTED_LANGUAGES:\n\t\traise ValueError(\"Unknown language.\")\n\n\tif removeStopWords:\n\t\tkeepWordFn = lambda word: word not in STOP_WORDS[textLanguage]\n\telse:\n\t\tkeepWordFn = lambda word: True\n\n\tif stem:\n\t\twordProcessingFn = lambda word: STEMMERS[textLanguage].stem(word)\n\telse:\n\t\twordProcessingFn = lambda word: word\n\n\treturn [\n\t\twordProcessingFn(word) for word in normalize(word_tokenize(text)) if\n\t\tkeepWordFn(word)\n \t]\n","sub_path":"src/analysis/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6935901","text":"#coding:utf-8\n\nfile_name = '../dataset2/paper_title_venue.txt'\n\nvenues = set()\nword_df = {}\n\nwith open(file_name) as file:\n for line in file:\n paper_id, title, venue = line.strip().split()\n words = title.split('-')\n for word in words:\n if word not in word_df:\n word_df[word] = set()\n word_df[word].add(venue)\n venues.add(venue)\n\nvenues.remove('none')\n\nfor word, venue in word_df.items():\n if 'none' in venue:\n venue.remove('none')\n\nvenues = list(venues)\nvenues.sort()\n\nwith open('../dataset2/venues.txt', 'w') as file:\n for venue in venues:\n file.write('{}\\n'.format(venue))\n\nwords = list(word_df.keys())\nwords.sort()\nwith open('../dataset2/word_df.txt', 'w') as file:\n for word in words:\n if len(word)==1 or len(word_df[word])<3:\n continue\n df = len(word_df[word])/len(venues)\n file.write('{} {:.4f}\\n'.format(word, df))\n","sub_path":"data_tools/walker/src-cikm/build_graph2/preprocess_venue_word.py","file_name":"preprocess_venue_word.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363625923","text":"#Uma escola precisa montar o cadastro geral de seus alunos. Este cadastro deverá conter as seguintes informações por aluno: nome completo, data de nascimento, telefone, \n#endereço e série atual. Levando em conta que esta escola possui no máximo 500 alunos, como você faria para estruturar estas informações num sistema de gerenciamento \n#para a escola? Implemente utilizando estrutura. Também use a criação de funções para cada operação.\n\nclass Tipo_Aluno:\n nome = ''\n datan = ''\n telefone = ''\n endereco = ''\n serie = 0\n\ndef cadastrar():\n vet_aluno = []\n for i in range(3):\n aluno = Tipo_Aluno()\n aluno.nome = input('Cadastre o nome: ')\n aluno.datan = input('Cadastre a data de nascimento: ')\n aluno.telefone = input('Cadastre o telefone: ')\n aluno.endereco = input('Cadastre o endereço: ')\n aluno.serie = input('Cadastre a série atual: ')\n vet_aluno.append(aluno)\n return vet_aluno\n\ndef consultar(va):\n nome_a_consultar = input('Qual nome deseja pesquisar? ')\n achei = False\n for i in range(len(va)):\n if nome_a_consultar in va[i].nome:\n achei = True\n if achei:\n print('Aluno encontrado')\n else:\n print('Aluno não encontrado')\n\ndef visualizar(va):\n for i in range(len(va)):\n print('Nome:',va[i].nome,'\\tData de nascimento:',va[i].datan,'\\tTelefone:',va[i].telefone,'\\tEndereço:',va[i].endereco,'\\tSérie atual:',va[i].serie) \n\ndef menu():\n print('\\n * Menu de opções *')\n print('1. Cadastrar alunos')\n print('2. Consultar por nome')\n print('3. Visualizar todos os dados')\n print('4. Sair')\n op = int(input('Digite a opção desejada: '))\n return op\n\ndef main():\n opcao = menu()\n while opcao >= 1 and opcao <= 3:\n if opcao == 1:\n vet_a = cadastrar()\n elif opcao == 2:\n consultar(vet_a)\n elif opcao == 3:\n visualizar(vet_a)\n opcao = menu()\n\nmain()\n","sub_path":"Estrutura - Dados - Ex4.py","file_name":"Estrutura - Dados - Ex4.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"616461293","text":"# Definition for a binary tree node.\nfrom ds import TreeNode\n\nclass Solution:\n # @param {TreeNode} root\n # @return {TreeNode}\n def invertTree(self, root):\n if root:\n self.invertRecursive(root) \n return root\n \n def invertRecursive(self, root):\n if root is None:\n return\n root.right, root.left = root.left, root.right\n self.invertRecursive(root.right)\n self.invertRecursive(root.left )\n\n\nif __name__ == '__main__':\n s = Solution()\n \n test = TreeNode(4)\n test.right = TreeNode(7)\n test.left = TreeNode(2)\n test.right.right = TreeNode(9)\n test.right.left = TreeNode(6)\n test.left.right = TreeNode(3)\n test.left.left = TreeNode(1)\n\n\n\n\n\n\n\n","sub_path":"Python/226-InvertBinaryTree.py","file_name":"226-InvertBinaryTree.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"492963051","text":"from flask import Flask,request\nimport requests\nimport json\nimport time\n\napp = Flask(__name__)\n\ndef convert(args):\n# Load the json data\n with open('./data.json') as jsondata:\n countrycodes = json.load(jsondata)\n \n # Get country codes\n list = args.split(',')\n\n # Output country name based on country codes\n country = ''\n newline = '\\n'\n\n for val in list:\n #print (\"Country code: %s\" % val)\n if val in countrycodes['data']:\n if 'name' in countrycodes['data'][val]:\n country = country + val + \", is country code for: \" + countrycodes['data'][val]['name']\n country += newline\n else:\n country += val + \", is invalid country code\"\n country += newline\n return country\n\n@app.route('/diag')\ndef diag():\n url = 'https://www.travel-advisory.info/api'\n y = requests.get(url)\n obj = y.json()\n return(obj['api_status'])\n\n@app.route(\"/convert\", methods=['GET'])\ndef get_query():\n # return request.query_string\n req = request.query_string\n\n check_string = 'countycode='\n\n if (not req):\n return \"Missing argument - enter this format /convert?countrycode=AL,AK\"\n else:\n args1 = request.args['countrycode']\n if (not args1):\n return 'Enter country code(s) seperated by commas'\n else:\n return convert(args1)\n\n@app.route('/health')\ndef health():\n time.sleep(1)\n return \"Status: OK\"\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"40011259","text":"import math\nimport numpy as np\n\nimport cv2 as cv\n\ndef binarizacia():\n img = cv.imread('start.jpg', cv.IMREAD_GRAYSCALE)\n ret, th = cv.threshold(img, 170, 255, cv.THRESH_BINARY)\n\n cv.imshow('img', img)\n cv.imshow('th', th)\n cv.waitKey()\n cv.destroyAllWindows()\n cv.imwrite('img-bin.jpg', th)\n\n\n#Построение скелета изображение\ndef skelet_img(img):\n # img = cv.imread(file_name, 0)\n size = np.size(img)\n skel = np.zeros(img.shape, np.uint8)\n\n ret, img = cv.threshold(img, 127, 255, 0)\n element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))\n done = False\n\n while (not done):\n eroded = cv.erode(img, element)\n temp = cv.dilate(eroded, element)\n temp = cv.subtract(img, temp)\n skel = cv.bitwise_or(skel, temp)\n img = eroded.copy()\n\n zeros = size - cv.countNonZero(img)\n if zeros == size:\n done = True\n return skel\n\n#Расширение с матрицей 5х5\ndef dilation(src):\n kernel = np.ones((5, 5), np.uint8) # 5x5\n dilation = cv.dilate(src, kernel, iterations=1)\n return dilation\n\n#Расширение с матрицей 3х3\ndef dilation_3(src):\n kernel = np.ones((3, 3), np.uint8) # 3x3\n dilation = cv.dilate(src, kernel, iterations=1)\n return dilation\n\n#Эрозия\ndef erosion(img):\n kernel = np.ones((3, 3), np.uint8)\n eros = cv.erode(img, kernel, iterations=1)\n return eros\n\n#Комбинация морфологических операций\ndef morf(img):\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n #gray = dilation(gray)\n #gray = erosion(gray)\n gray = skelet_img(gray)\n gray = dilation_3(gray)\n #gray = dilation(gray)\n\n\n\n img = cv.cvtColor(gray, cv.IMREAD_COLOR)\n\n return img\n\n#Комбинация морфологических операций\ndef morf_sk(img):\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n gray = skelet_img(gray)\n\n img = cv.cvtColor(gray, cv.IMREAD_COLOR)\n\n return img\n\n#Алгоритм поиска узловых точек\ndef method_circl(img, x, y, R, l, j):\n # l - смещение пикселей по радиусу\n\n dlt_al = (l * 360) / (2 * math.pi * R) # Шаг смещения по грани\n\n h, w, _ = img.shape\n\n i = 0 #Шаг радиуса\n k = 0 #Колличество пересечений радиуса с белым пикселем\n\n while (not (((dlt_al * i) >= 330) or (k >= 3))): #Проверяем прошел радиут 330 градусов или были ли найдены 3 пересечения\n al = math.radians(dlt_al * i)\n\n #Находим координаты\n x1 = int(R * math.cos(al) + x)\n y1 = int(R * math.sin(al) + y)\n\n i += 1\n\n #Проверка на выход за границы снимка\n if (x1 >= w) or (y1 >= h) or (x1 <= 0) or (y1 <= 0):\n continue\n\n #Если радиус попал в белую точку\n if all(img[y1, x1] > [180, 180, 180]):\n\n i = i + j #добавляем к шагу радиуса прыжок\n k = k + 1 #Добавляем пересечение\n\n if k >= 3:\n return True\n return False\n\n#Проверка значений пикселей на грани\ndef chek_matrix(img, x, y):\n img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # cv.circle(img,(x,y),5,(255,0,0))\n\n # img[y-1,x] = 255\n\n try:\n # ******************************************************\n l1 = [0, 0, 0]\n if img[y - 1, x - 1] >= 180:\n l1[0] = 1\n else:\n l1[0] = 0\n\n if img[y - 1, x] >= 180:\n l1[1] = 1\n else:\n l1[1] = 0\n\n if img[y - 1, x + 1] >= 180:\n l1[2] = 1\n else:\n l1[2] = 0\n # ******************************************************\n l2 = [0, 0, 0]\n if img[y, x - 1] >= 180:\n l2[0] = 1\n else:\n l2[0] = 0\n\n if img[y, x] >= 180:\n l2[1] = 1\n else:\n l2[1] = 0\n\n if img[y, x + 1] >= 180:\n l2[2] = 1\n else:\n l2[2] = 0\n # ******************************************************\n l3 = [0, 0, 0]\n if img[y + 1, x - 1] >= 180:\n l3[0] = 1\n else:\n l3[0] = 0\n\n if img[y + 1, x] >= 180:\n l3[1] = 1\n else:\n l3[1] = 0\n\n if img[y + 1, x + 1] >= 180:\n l3[2] = 1\n else:\n l3[2] = 0\n\n arr = np.array([l1, l2, l3])\n arr_one = np.zeros((3, 3), np.int)\n\n matrix = np.array_equal(arr, arr_one)\n print('matrix', matrix)\n\n if matrix:\n return False\n else:\n return True\n # ******************************************************\n except IndexError:\n return False\n\n\ndef anti_nois(img):\n\n hsv_min = np.array((0, 0, 49), np.uint8)\n hsv_max = np.array((255, 255, 255), np.uint8)\n\n hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n thresh = cv.inRange(hsv, hsv_min, hsv_max)\n\n contours0, hierarchy = cv.findContours(thresh.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\n img_black = img.copy()\n\n # Получаем черное изображение\n img_black1 = cv.bitwise_not(img_black)\n\n img_black = cv.bitwise_and(img, img_black1)\n\n #Создаем маску\n h, w = img.shape[:2]\n mask = np.zeros((h + 2, w + 2), np.uint8)\n\n print(h,w)\n\n\n for cnt in contours0:\n point = [0, 0]\n if len(cnt) >5 and len(cnt) <50: # 10\n ellipse = cv.fitEllipse(cnt)\n\n x = int(ellipse[0][0])\n y = int(ellipse[0][1])\n\n\n\n print(x,y)\n\n\n if (0 < x < w) and (0 < y < h):\n\n\n if len(cnt) >8:\n cv.ellipse(img_black, ellipse, (255, 255, 255), 1)\n cv.floodFill(img_black, mask, (x, y), (255, 255, 255))\n else:\n cv.ellipse(img_black, ellipse, (255, 255, 255), 2)\n\n img_black_inv = cv.bitwise_not(img_black)\n\n res = cv.bitwise_and(img,img_black_inv)\n\n #cv.imshow(\"img_black_cop\", img_black)\n #cv.imshow(\"img_black_inv\", img_black_inv)\n #cv.imshow(\"img_blackel \", img_black)\n #cv.imshow(\"img_black\", img_black)\n #cv.imshow(\"res\", res)\n #cv.waitKey(0)\n #cv.imshow(\"Inverted Floodfilled Image\", im_floodfill_inv)\n #cv.imshow(\"Foreground\", im_out)\n #cv.waitKey(0)\n #cv.destroyAllWindows()\n\n return res\n\n\ndef translation_koordinate(img, one_mm, points):\n\n h,w,_ = img.shape\n\n x_cent = int(w/2)\n y_cent = int(h/2)\n\n\n koordinates = []\n for p in points:\n k = []\n x = p[0] - x_cent\n y = y_cent - p[1]\n\n x_m = round(x/one_mm,2)\n y_m = round(y/one_mm,2)\n\n k.append(x_m)\n k.append(y_m)\n\n koordinates.append(k)\n\n return koordinates\n\n\n\n\n\n\n\n\n\n#filename = './foto_cam/start-bin.bmp'\n#img = cv.imread(filename, cv.IMREAD_COLOR)\n\n#h, w, _ = img.shape # Получаем высоту и ширину изображения\n\n#img_th =morf(img) # Проводим морфологию (эрозия + скелетолизация + расширение)\n\n#anti_nois(img_th)","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"469264380","text":"#!/usr/bin/python\n# GoogleMapDownloader.py \n# Created by Hayden Eskriett [http://eskriett.com]\n#\n# A script which when given a longitude, latitude and zoom level downloads a\n# high resolution google map\n# Find the associated blog post at: http://blog.eskriett.com/2013/07/19/downloading-google-maps/\n# https://gis.stackexchange.com/questions/7430/what-ratio-scales-do-google-maps-zoom-levels-correspond-to\n\"\"\"\ndecimal places\tdecimal degrees\tN/S or E/W at equator\n2\t0.01\t1.1132 km\n3\t0.001\t111.32 m\n4\t0.0001\t11.132 m\n5\t0.00001\t1.1132 m\n\n\"\"\"\nimport urllib\nfrom PIL import Image\nimport os\nimport math\nimport numpy as np\n\n\nclass GoogleMapDownloader:\n \"\"\"\n A class which generates high resolution google maps images given\n a longitude, latitude and zoom level\n \"\"\"\n\n def __init__(self, lat, lng, zoom=12):\n \"\"\"\n GoogleMapDownloader Constructor\n\n Args:\n lat: The latitude of the location required\n lng: The longitude of the location required\n zoom: The zoom level of the location required, ranges from 0 - 23\n defaults to 12\n \"\"\"\n self._lat = lat\n self._lng = lng\n self._zoom = zoom\n\n def getXY(self):\n \"\"\"\n Generates an X,Y tile coordinate based on the latitude, longitude\n and zoom level\n\n Returns: An X,Y tile coordinate\n \"\"\"\n\n tile_size = 256\n\n # Use a left shift to get the power of 2\n # i.e. a zoom level of 2 will have 2^2 = 4 tiles\n numTiles = 1 << self._zoom\n\n # Find the x_point given the longitude\n point_x = (tile_size / 2 + self._lng * tile_size / 360.0) * numTiles // tile_size\n\n # Convert the latitude to radians and take the sine\n sin_y = math.sin(self._lat * (math.pi / 180.0))\n\n # Calulate the y coorindate\n point_y = ((tile_size / 2) + 0.5 * math.log((1 + sin_y) / (1 - sin_y)) * -(\n tile_size / (2 * math.pi))) * numTiles // tile_size\n\n return int(point_x), int(point_y)\n\n def generateImage(self, **kwargs):\n \"\"\"\n Generates an image by stitching a number of google map tiles together.\n\n Args:\n start_x: The top-left x-tile coordinate\n start_y: The top-left y-tile coordinate\n tile_width: The number of tiles wide the image should be -\n defaults to 5\n tile_height: The number of tiles high the image should be -\n defaults to 5\n Returns:\n A high-resolution Goole Map image.\n \"\"\"\n\n start_x = kwargs.get('start_x', None)\n start_y = kwargs.get('start_y', None)\n tile_width = kwargs.get('tile_width', 5)\n tile_height = kwargs.get('tile_height', 5)\n\n # Check that we have x and y tile coordinates\n if start_x == None or start_y == None:\n start_x, start_y = self.getXY()\n\n # Determine the size of the image\n width, height = 256 * tile_width, 256 * tile_height\n\n # Create a new image of the size require\n map_img = Image.new('RGB', (width, height))\n print (tile_width, tile_height)\n for x in range(0, tile_width):\n for y in range(0, tile_height):\n # url = 'https://mt0.google.com/vt/lyrs=y&hl=en&x=' + str(start_x + x) + '&y=' + str(\n # start_y + y) + '&z=' + str(self._zoom)\n url = 'https://mt0.google.com/vt?x='+str(start_x+x)+'&y='+str(start_y+y)+'&z='+str(\n self._zoom)\n print (x, y, url)\n current_tile = str(x) + '-' + str(y)\n urllib.urlretrieve(url, current_tile)\n\n im = Image.open(current_tile)\n map_img.paste(im, (x * 256, y * 256))\n\n os.remove(current_tile)\n\n return map_img\n\n\nclass ImageWgsHandler:\n def __init__(self, img_size, reference_points):\n self.reference_points = reference_points\n\n self.density_points = self.wgs_pixel_transform_matrix(img_size, reference_points)\n\n def wgs_pixel_transform_matrix(self, img_size, reference_points):\n \"\"\"\n Calculate WGS coordinate for each pixels according to a weighted average of reference points\n :param img_size: (width, height) in pixels\n :param reference_points: Lis[ ( (row, col), (easting*, northing*) ), ....] *WGS84 format\n :return:\n \"\"\"\n img_width, img_height = img_size\n max_distance = float(img_width ** 2 + img_height ** 2)\n\n density_points = [] # list of (col, row), (easting, northing), pixel_wgs_factor\n d_points = dict({})\n for i in range(len(reference_points)-1):\n for j in range(i+1, len(reference_points)):\n (c1, r1), (e1, n1) = reference_points[i]\n (c2, r2), (e2, n2) = reference_points[j]\n rm = (r1+r2) / 2.\n cm = (c1+c2) / 2.\n em = (e1+e2) / 2.\n nm = (n1+n2) / 2.\n # pixels dist / wgs dist\n f = np.sqrt( ((r1-r2)**2 + (c1-c2)**2) / ((e1-e2)**2 + (n1-n2)**2) )\n f_x = (r2-r1)/(e2-e1)\n f_y = (c2-c1)/(n2-n1)\n d_info = ((i, j), (rm, cm), (em, nm), (f_x, f_y), f)\n density_points.append(d_info)\n if i not in d_points.keys():\n d_points[i] = dict()\n d_points[i][j] = d_info\n\n return density_points\n\n # max_points = 3\n # r, c, e, n = [], [], [], []\n # for (r1, c1), (e1, n1) in reference_points:\n # r.append(r1)\n # c.append(c1)\n # e.append(e1)\n # n.append(n1)\n #\n # r = np.array(r)\n # c = np.array(c)\n # e = np.array(e)\n # n = np.array(n)\n\n # # wgs 2 pixel\n # lat_, long_ = 44.436336, 26.046967\n # easting, northing, zone_no, zone_letter = utm.from_latlon(lat_, long_)\n #\n #\n # de = e - easting\n # se = np.argsort(de)\n # left_closest = se[de<0][-max_points:]\n # right_closest = se[de>0][:max_points]\n #\n # e[right_closest]\n #\n #\n # # wgs 2 pixel\n # lat_, long_ = 44.435716, 26.045121\n # easting, northing, zone_no, zone_letter = utm.from_latlon(lat_, long_)\n\n def get_pixel(self, easting, northing):\n reference_points = self.reference_points\n density_points = self.density_points\n\n w_r = 0\n w_c = 0\n p_r = 0\n p_c = 0\n cnt = 5\n\n for (i, j), (ref_r, ref_c), (ref_e, ref_n), (p_w_x, p_w_y), p_w in density_points:\n (c1, r1), (e1, n1) = reference_points[i]\n (c2, r2), (e2, n2) = reference_points[j]\n\n r = p_w_x * (easting - ref_e) + ref_r\n c = p_w_y * (northing - ref_n) + ref_c\n\n dist = (easting - ref_e) ** 2 + (northing - ref_n) ** 2\n\n # Must calculate if between points or not -> depends how we weigh dif in points\n d_e = abs(e1-e2)\n if np.sign(easting - e1) == np.sign(easting - e2):\n # same side\n w_r_ = 1/dist * d_e\n else:\n w_r_ = 1/dist * (1/d_e)\n w_r += w_r_\n p_r += r * w_r_\n\n d_n = abs(n1-n2)\n if np.sign(northing - n1) == np.sign(northing - n2):\n # same side\n w_c_ = 1/(northing - ref_n) * d_n\n else:\n w_c_ = 1/(northing - ref_n) * (1/d_n)\n w_c += w_c_\n p_c += c * w_c_\n\n\n cnt += 1\n\n new_r = p_r / w_r\n new_c = p_c / w_c\n return new_r, new_c\n\n # lat_, long_ = 44.435716, 26.045121\n # easting, northing, zone_no, zone_letter = utm.from_latlon(lat_, long_)\n\n\ndef main():\n import utm\n\n # Create a new instance of GoogleMap Downloader\n\n lat = 44.437774\n long = 26.044453\n scale = 22\n gmd = GoogleMapDownloader(lat, long, scale)\n\n print(\"The tile coorindates are {}\".format(gmd.getXY()))\n\n try:\n # Get the high resolution image\n img = gmd.generateImage(tile_width=70, tile_height=60)\n except IOError:\n print(\n \"Could not generate the image - try adjusting the zoom level and checking your coordinates\")\n else:\n # Save the image to disk\n img.save(\"/media/andrei/CE04D7C504D7AF291/nemodrive/data_collect/high_resolution_image_full\"\n \".png\")\n print(\"The map has successfully been created\")\n\n\n # calculate pixel size\n equator_zoom_24 = 0.009330692\n scale_size = equator_zoom_24 * (2 ** (24-scale))\n pixel_size = np.cos(lat) * scale_size\n\n\n # WGS84 conversion from lat_lon GPS\n easting, northing, zone_no, zone_letter = utm.from_latlon(lat, long)\n easting, northing, zone_no, zone_letter = utm.from_latlon(lat, long)\n\n easting += 2125 * pixel_size\n northing += 8853 * pixel_size\n new_lat, new_long = utm.to_latlon(easting, northing, zone_no, zone_letter)\n\n #\n orig_img_size = (15360, 17920)\n match_coord = [\n # ( (col, row), (lat, long) )\n ((482, 1560), (44.437456, 26.044567)),\n ((14658, 867), (44.437615, 26.049345)),\n ((2238, 12552), (44.434819, 26.045173)),\n ((15380, 13912), (44.434490, 26.049591)),\n ((9724, 6808), (44.436219, 26.047681)),\n ]\n\n scale = 1.0\n img_size = (orig_img_size[0]*scale, orig_img_size[1]*scale)\n row_scale = img_size[0] / float(orig_img_size[0])\n col_scale = img_size[1] / float(orig_img_size[1])\n match_coord_wgs = []\n for (col, row), (lat, long) in match_coord:\n row_n = img_size[1] - row * row_scale\n col_n = col * col_scale\n easting, northing, zone_no, zone_letter = utm.from_latlon(lat, long)\n match_coord_wgs.append(((row_n, col_n), (easting, northing)))\n\n reference_points = match_coord_wgs\n\n import matplotlib.pyplot as plt\n x = [r1 for (c1, r1), (e1, n1) in reference_points]\n y = [c1 for (c1, r1), (e1, n1) in reference_points]\n n = range(len(x))\n fig, ax = plt.subplots()\n ax.scatter(x, y)\n\n for i, txt in enumerate(n):\n ax.annotate(txt, (x[i], y[i]))\n plt.show()\n\n x = [e1 for (r1, c1), (e1, n1) in reference_points]\n y = [n1 for (r1, c1), (e1, n1) in reference_points]\n n = range(len(x))\n fig, ax = plt.subplots()\n ax.scatter(x, y)\n for i, txt in enumerate(n):\n ax.annotate(txt, (x[i], y[i]))\n\n plt.show()\n\n pixels_to_wgs = wgs_pixel_transform_matrix(img_size, match_coord_wgs)\n\n\n\n","sub_path":"stree_view.py","file_name":"stree_view.py","file_ext":"py","file_size_in_byte":10598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"404314871","text":"#Actividad Evaluable - Programas que utilizan funciones\n#Rosa Vanessa Palacios Beltran\n#A01652612\n\n#Ejercicio \n\n'''\nINSTRUCCIONES:\nDefine una función que reciba los coeficientes a, b y c de una ecuación cuadrática \nde la forma ax^2+bx+c=0 y deberá regresar las soluciones x1yx2. \n\n**(NOTA: si la ecuación tiene soluciones complejas, x1yx2\ndeberán regresar el valor NaN (not a number), representado en Python como math.nan.)**\n\nUtiliza esa función para calcular la solución de dos ecuaciones cuadráticas distintas \n(los coeficientes de ambas ecuaciones son proporcionadas por el usuario).\n'''\nimport math\n\nprint('\\nIngresa valores para los coeficientes de a, b y c\\n \\nPara una ecuación cuadrática de la forma:\\n ax^2 + bx + c = 0\\n')\n\ndef ecuacionCuadratica(a, b, c):\n\n if b**2 - 4 *(a*c) < 0:\n x1 = math.nan\n x2 = math.nan\n else: \n x1 = (-b + math.sqrt (b**2 - 4 * a*c)) / (2*a)\n x2 = (-b - math.sqrt (b**2 - 4 * a*c)) / (2*a)\n \n return x1, x2\n\na = int(input('Digite valor de a: '))\nb = int(input('Digite valor de b: '))\nc = int(input('Digite valor de c: '))\nprint(f'\\n{a}x^2 + {b}x + {c} = 0\\n')\n\nx1, x2 = ecuacionCuadratica(a, b, c)\n\nprint(f'Las soluciones para\\n x1={x1} | x2={x2} ')","sub_path":"semana-3/class-11/A01652612-funciones03.py","file_name":"A01652612-funciones03.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"397908072","text":"import numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras import regularizers\nimport keras\n\nclass ModelRegression2:\n\n def __init__(self):\n self.model = Sequential()\n\n\n def Create(self):\n \n #Simple Model\n \n '''\n \n toto = [[-1,-1,-1],\n [-1, 8,-1],\n [-1,-1,-1]]\n #self.model.add(LocallyConnected2D(16, kernel_size=4, activation='relu', input_shape=(20, 20, 3)))\n #self.model.add(Dropout(0.5))\n #self.model.add(Conv2D(4, kernel_size=4, activation='relu', input_shape=(20, 20, 3)))\n #self.model.add(Flatten())\n #self.model.add(Dense(50, activation='tanh')) #, kernel_regularizer=keras.regularizers.l2(0.01)\n #self.model.add(MaxPooling2D(pool_size=(2, 2)))\n self.model.add(Flatten())\n self.model.add(Dense(400, activation='relu'))\n self.model.add(Dense(500, activation='tanh'))\n self.model.add(Dropout(0.4))\n self.model.add(Dense(20, activation='sigmoid'))\n #self.model.add(Dense(10, activation='tanh'))\n self.model.add(Dense(1, activation='sigmoid'))'''\n\n #Complexe Model\n #self.model.add(SeparableConv2D(1, kernel_size=2, activation='relu', input_shape=(20, 20, 1),))\n self.model.add(Conv2D(2, kernel_size=4, padding='same', activation='relu', #input_shape=(20, 20, 1),\n use_bias=True, bias_initializer='Zeros', bias_regularizer=keras.regularizers.l2(0.01)\n ))\n self.model.add(Conv2D(32, kernel_size=64, padding='same', activation='relu', #input_shape=(20, 20, 1),\n use_bias=True, bias_initializer='Zeros', bias_regularizer=keras.regularizers.l2(0.01)\n ))\n #self.model.add(Dropout(0.5))\n #self.model.add(MaxPooling2D(pool_size=(10, 10)))\n #self.model.add(Conv2D(64, kernel_size=5, activation='tanh'))\n #self.model.add(MaxPooling2D(pool_size=(2, 2)))\n self.model.add(Flatten())\n self.model.add(Dense(200, activation='tanh'))\n self.model.add(Dense(100, activation='tanh'))\n #self.model.add(Dropout(0.5))\n self.model.add(Dense(100, activation='softmax'))\n \n def Train(self, set, optimizer, epochs, verbose = 0):\n #Compile\n if optimizer == 'sgd':\n self.model.compile(loss='categorical_crossentropy',\n optimizer=keras.optimizers.SGD(learning_rate=0.001, momentum=0.4, nesterov=False),\n metrics=['accuracy'])\n if optimizer == 'adam':\n self.model.compile(loss='categorical_crossentropy',\n optimizer='adadelta',\n metrics=['accuracy'])\n data = set[0]\n #print(data.shape)\n labels = set[1]\n history = self.model.fit(data, labels, batch_size=16, epochs=epochs, verbose=verbose)\n return history\n \n #Train\n #self.model.train_on_batch(labels, datalabels, batch_size=1)\n\n\n def Evaluate(self, set) :\n #Evaluate\n data = set[0]\n labels = set[1]\n score = self.model.evaluate(data, labels, verbose=0, use_multiprocessing=False)\n return score\n\n\n def Predict(self, x):\n return self.model.predict(x)\n","sub_path":"ModelRegression2.py","file_name":"ModelRegression2.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"247943468","text":"from django.urls import path\r\nfrom . import views\r\n\r\napp_name = 'city'\r\n\r\nurlpatterns = [\r\n path('',views.HomeView.as_view(),name='home'),\r\n path('allcities/',views.allcities,name='allcities'),\r\n ]\r\n\r\nimport random\r\n\r\ndef create_lottery_numbers():\r\n values = set() #initializing an empty setself.\r\n while len(values) < 6: #will run until you achieve 6 numbers in the set.\r\n values.add(random.randint(1,20))\r\n return values\r\n\r\nprint(create_lottery_numbers())\r\n","sub_path":"palms/city/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"170329632","text":"from Text.ex8_realtime_quotes.forms import InputForm\nfrom Text.ex8_realtime_quotes.quotes import Quotes\nfrom flask import Flask, redirect, url_for, render_template, session\n\napp = Flask(__name__)\napp.secret_key = 'guojiaqi'\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n form = InputForm()\n if form.is_submitted():\n session['type'] = form.type.data\n session['id'] = form.id.data\n session['refresh'] = form.refresh.data\n # session['name'], session['price'], session['increase'] = get_price(session.get('type'), session.get('id'))\n return redirect(url_for('index'))\n session['name'], session['price'], session['increase'] = get_price(session.get('type'), session.get('id'))\n return render_template('index.html', form=form, name=session.get('name'), price=session.get('price'), increase=session.get('increase'), refresh=session.get('refresh'))\n\n\ndef get_price(s_type=None, s_id=None):\n if s_type is None and s_id is None:\n return None, None, None\n q = Quotes()\n result = q.query(s_type, s_id)\n stock = result.get('retData').get('stockinfo')[0]\n if stock.get('name') != '':\n return stock.get('name'), stock.get('currentPrice'), stock.get('increase')\n else:\n return None, None, None\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Text/ex8_realtime_quotes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"378184005","text":"import pandas as pd\nimport streamlit as st\nfrom pycaret.classification import *\nfrom catboost import CatBoostClassifier\n\n\n# loading the trained model.\nmodel = load_model('modelo-final')\n#model = pickle.load('model/modelo-final')\n\n# carregando uma amostra dos dados.\ndataset = pd.read_csv('WA_Fn-UseC_-Telco-Customer-Churn.csv') \n#classifier = pickle.load(pickle_in)\n\n\n# título\nst.title(\"Data App - Churn prediction\")\n\nst.markdown('Churn designates the percentage of customers the company has lost over a given time period')\n\n# subtítulo\nst.markdown(\"This is a Data App used to display the Machine Learning solution for the customer churn prediction problem. \")\n\n\nst.image('churn.jpg', caption=None, width=None, use_column_width=None, clamp=False, channels='RGB', output_format='auto')\n\n#cabeçalho barra lateral\nst.sidebar.subheader(\"Set customer attributes to predict if he or she will churn of not\")\n\n\n# mapeando dados do usuário para cada atributo\ngender = st.sidebar.selectbox(\"Gender\", ('male', 'female'))\nSeniorCitizen = st.sidebar.selectbox(\"Senior citizen\", ('yes', 'no'))\nPartner = st.sidebar.selectbox(\"Partner\", ('yes', 'no'))\nDependents = st.sidebar.selectbox(\"Dependents\", ('yes', 'no'))\ntenure = st.sidebar.number_input('Months in the company', value=0)\nPhoneService = st.sidebar.selectbox('Phone service', ('yes', 'no'))\nTotalCharges = st.sidebar.number_input('Total charges', value=0)\nMonthlyCharges = st.sidebar.number_input('Monthly charges', value=0)\n\n\n# inserindo um botão na tela\nbtn_predict = st.sidebar.button(\"Realizar Predição\")\n\n# verifica se o botão foi acionado\nif btn_predict:\n data_teste = pd.DataFrame()\n\n data_teste[\"gender\"] = [gender]\n data_teste[\"SeniorCitizen\"] = [SeniorCitizen]\n data_teste[\"Partner\"] = [Partner] \n data_teste[\"Dependents\"] = [Dependents]\n data_teste[\"tenure\"] = [tenure]\t\n data_teste[\"PhoneService\"] = [PhoneService]\n data_teste[\"TotalCharges\"] = [TotalCharges]\n data_teste[\"MonthlyCharges\"] = [MonthlyCharges]\n \n #imprime os dados de teste \n print(data_teste)\n\n #realiza a predição\n result = predict_model( model, data = data_teste)[\"Label\"]\n\n st.subheader(\"Will the client churn?\")\n \n result = str(result[0])\n\n st.write(result)","sub_path":"churn_app.py","file_name":"churn_app.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"14753541","text":"import numpy as np\nfrom PIL import Image\nimport os\nimport argparse\nimport sys\nimport shutil\nimport itertools\nimport re\n\n\nnp.random.seed(4)\n\n\n# Command line inputs\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--outputdir\", help='Name of the output directory', type=str, default='train_augmented')\nparser.add_argument(\"--inputdir\", help='Name of the input directory', type=str, default='train_reduced')\n\nargs = parser.parse_args()\n\noutputdir = os.path.join(os.path.curdir,args.outputdir)\ninputdir = os.path.join(os.path.curdir,args.inputdir)\n#print(inputdir)\n\nif not os.path.exists(outputdir):\n os.makedirs(outputdir)\n\nfiles = os.listdir(inputdir)\n#print(files)\n\n\n# create image paths list\nimage_paths = list(map(lambda x: os.path.join(inputdir,x), files))\n#print(image_paths)\n\n\n\ndef four_crop_and_rescale_images(img):\n w, h = img.size\n left1, top1, right1, bottom1 = 0, 0, w/2, h/2\n left2, top2, right2, bottom2 = w/2, h/2, w, h\n left3, top3, right3, bottom3 = w/2, 0, w, h/2\n left4, top4, right4, bottom4 = 0, h/2, w/2, h\n rescale_width, rescale_height = 64, 64 #224, 224\n first_cropped_image = img.crop((left1, top1, right1, bottom1))\n second_cropped_image = img.crop((left2, top2, right2, bottom2))\n third_cropped_image = img.crop((left3, top3, right3, bottom3))\n fourth_cropped_image = img.crop((left4, top4, right4, bottom4))\n first_rescaled_image = first_cropped_image.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n second_rescaled_image = second_cropped_image.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n third_rescaled_image = third_cropped_image.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n fourth_rescaled_image = fourth_cropped_image.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n return [first_rescaled_image,second_rescaled_image,third_rescaled_image,fourth_rescaled_image]\n\ndef flip_and_rescale_image(img):\n rescale_width, rescale_height = 64, 64 #224, 224 \n flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)\n rescaled_flipped_image = flipped_img.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n return rescaled_flipped_image \n\ndef rescale_image(img):\n rescale_width, rescale_height = 64, 64 #224, 224\n rescaled_image = img.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n return rescaled_image\n\ndef random_cropped_image(img):\n height, width = img.size\n crop_width, crop_height = 224, 224\n rescale_width, rescale_height = 64, 64 #224, 224\n i = int(np.random.uniform(0,int(width-crop_width)))\n j = int(np.random.uniform(0,int(height-crop_height)))\n left, top, right, bottom = i, j, i+crop_width, j+crop_height\n cropped_img = img.crop((left, top, right, bottom))\n resized_img = cropped_img.resize((rescale_width, rescale_height), Image.ANTIALIAS)\n return resized_img\n\ndef apply_transforms(image_path):\n img = Image.open( image_path )\n height, width = img.size\n data = four_crop_and_rescale_images(img)\n data.append(flip_and_rescale_image(img))\n data.append(rescale_image(img))\n if min(height,width) >=224:\n data.append(random_cropped_image(img))\n return(data)\n\n\nfor f in image_paths:\n image_name = os.path.splitext(os.path.basename(f))[0]\n for idx, i in enumerate(apply_transforms(f)):\n i.save(os.path.join(outputdir,'tmp_%s_%d.jpg') % (image_name, idx))\n\n\n\n\n\n\n","sub_path":"DCGAN_and_Resnet18/classical_data_augmentation.py","file_name":"classical_data_augmentation.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"538959914","text":"import pandas as pd\nimport os, shutil\nfrom copy import deepcopy\n\ndef build_integer_cut_from_slvars(slv_text):\n slvs = slv_text.split(', ')\n\n cut_text = []\n for slv in slvs:\n x,_ = slv.split(':')\n met,imb = x.split('.')\n cut_text.append(yvar_conv[imb] + \"('M__\" + met + \"')\")\n\n size = len(cut_text)\n cut_text = ' + '.join(cut_text)\n cut_text += ' =l= ' + str(size-0.5) + ';'\n return cut_text\n\n# Set metabolite and imbalance\nmet0 = '2ddara_c'\nimb0 = 'bpos'\n\n# Conv dictionaries\nimb_conv = {'slL': 'bneg', 'slU': 'bpos'}\nimb_conv_rev = {v:k for k,v in imb_conv.items()}\nyvar_conv = {'bneg': 'yL', 'bpos': 'yU'}\n\n# Initiate\nshutil.copy('../GAMS/cmpfind.gms', './cmpfind.gms');\nshutil.copy('../GAMS/cplex.opt', './cplex.opt');\n\n# Initiate file\nwith open('./cmpfind.gms') as f:\n gms = f.read().split('\\n')\n \nif imb0 == 'bpos':\n gms[68] = \"slL.fx('M__\" + met0 + \"') = 0;\"\n gms[69] = \"slU.fx('M__\" + met0 + \"') = 0.01;\"\n gms[70] = \"yL.fx('M__\" + met0 + \"') = 0;\"\n gms[71] = \"yU.fx('M__\" + met0 + \"') = 1;\"\nelif imb0 == 'bneg':\n gms[68] = \"slL.fx('M__\" + met0 + \"') = 0.01;\"\n gms[69] = \"slU.fx('M__\" + met0 + \"') = 0;\"\n gms[70] = \"yL.fx('M__\" + met0 + \"') = 1;\"\n gms[71] = \"yU.fx('M__\" + met0 + \"') = 0;\"\n \nwith open('./cmpfind.gms', 'w') as f:\n f.write('\\n'.join(gms))\n \n# Run GAMS first time no integer cut\nos.system('module load gams\\n' + 'gams cmpfind.gms o=/dev/null')\n#os.system('module load gams\\n' + 'gams cmpfind.gms')\n\nwith open('./cmpfind.modelStat.txt') as f:\n modelStat = f.read()\nmodelStat = modelStat.replace('\\n', '')\nmodelStat = modelStat.replace(' ', '')\nmodelStat = int(float(modelStat))\n\nif modelStat in [4,10,11,12,13,14,19]:\n with open('./cmpfind_msgOut.txt', 'w') as f:\n f.write('Terminate due to modelStat of ' + str(modelStat))\n quit()\n \ncols = ['id', 'modelStat', 'sl_vars', 'cut_text']\ndf_solns = pd.DataFrame(columns=cols)\n\ncount = 0\ndf_solns.loc[count, ['id', 'modelStat']] = [count, modelStat]\n\nwith open('./cmpfind_coupling_imbal.txt') as f:\n coup_imbal = f.read().split('\\n')\ncoup_imbal = [i for i in coup_imbal if i != '']\n\ntext = []\nfor entry in coup_imbal:\n met,imb,v = entry.split('\\t')\n v = float(v)\n text.append(met[3:] + '.' + imb_conv[imb] + ':' + str(v))\ntext = ', '.join(text)\n\ndf_solns.loc[count, 'sl_vars'] = text\ndf_solns.loc[count, 'cut_text'] = build_integer_cut_from_slvars(text)\n\n# Output\nwith open('./cmpfind_solns.txt', 'w') as f:\n text = [str(i) for i in df_solns.loc[count,:]]\n f.write('\\t'.join(text) + '\\n')\n \n# Run cmpfind, per iteration implemented more and more integer cuts\n# Enable integer cuts in GAMS\ngms[77] = '$include \"cmpfind_integerCuts_declare.txt\"'\ngms[86] = '$include \"cmpfind_integerCuts_eqns.txt\"'\ngms[92] = '$include \"cmpfind_integerCuts_declare.txt\"'\nwith open('./cmpfind.gms', 'w') as f:\n f.write('\\n'.join(gms))\n \nrunning = True\nslvs_str = df_solns.sl_vars.to_list()[-1]\nmets_prev = set([slv.split('.')[0] for slv in slvs_str.split(', ')])\n\n#while running and count < 2:\nwhile running:\n # Write integer cuts to text files\n with open('./cmpfind_integerCuts_declare.txt', 'w') as f:\n f.write('\\n'.join(['cut' + str(i) for i in df_solns.index]))\n\n text = []\n for i in df_solns.index:\n text.append('cut'+str(i) + '.. ' + df_solns.cut_text[i])\n with open('./cmpfind_integerCuts_eqns.txt', 'w') as f:\n f.write('\\n'.join(text))\n\n # Run GAMS\n os.system('module load gams\\n' + 'gams cmpfind.gms o=/dev/null')\n #os.system('module load gams\\n' + 'gams cmpfind.gms')\n \n # Record\n count += 1\n df_solns.loc[count, 'id'] = count\n \n with open('./cmpfind.modelStat.txt') as f:\n modelStat = f.read()\n modelStat = modelStat.replace('\\n', '')\n modelStat = modelStat.replace(' ', '')\n modelStat = int(float(modelStat))\n df_solns.loc[count, 'modelStat'] = modelStat\n \n with open('./cmpfind_coupling_imbal.txt') as f:\n coup_imbal = f.read().split('\\n')\n coup_imbal = [i for i in coup_imbal if i != '']\n\n text = []\n for entry in coup_imbal:\n met,imb,v = entry.split('\\t')\n v = float(v)\n text.append(met[3:] + '.' + imb_conv[imb] + ':' + str(v))\n text = ', '.join(text)\n\n df_solns.loc[count, 'sl_vars'] = text\n df_solns.loc[count, 'cut_text'] = build_integer_cut_from_slvars(text)\n \n # Output\n with open('./cmpfind_solns.txt', 'a') as f:\n text = [str(i) for i in df_solns.loc[count,:]]\n f.write('\\t'.join(text) + '\\n')\n \n # Check for termination\n if modelStat in [4,10,11,12,13,14,19]:\n with open('./cmpfind_msgOut.txt', 'w') as f:\n f.write('Terminate due to modelStat of ' + str(modelStat))\n running = False\n \n # Check if the run stuck, behave with duplicate solutions being found\n # continuously, probably due to solver tolerance\n slvs_str = df_solns.sl_vars.to_list()[-1]\n mets_now = set([slv.split('.')[0] for slv in slvs_str.split(', ')])\n if mets_now == mets_prev:\n running = False\n else:\n mets_prev = deepcopy(mets_now)\n","sub_path":"uncRHS/cmpfind/2ddara_c.bpos/cmpfind.py","file_name":"cmpfind.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"24543647","text":"\"\"\"The openwbmqtt component for controlling the openWB wallbox via home assistant / MQTT\"\"\"\nimport logging\n\nimport homeassistant.helpers.config_validation as cv\nimport voluptuous as vol\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\n\n# Import global values.\nfrom .const import CHARGE_POINTS, DOMAIN, MQTT_ROOT_TOPIC\n\n_LOGGER = logging.getLogger(__name__)\nPLATFORMS = [\"sensor\"]\n\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Setup openWB sensors (--> display current data in home assistant) and services (--> change openWB settings).\"\"\"\n\n # Provide data obtained in the configuration flow so that it can be used when setting up the entries.\n hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {\n MQTT_ROOT_TOPIC: entry.data[MQTT_ROOT_TOPIC],\n CHARGE_POINTS: entry.data[CHARGE_POINTS],\n }\n\n # Trigger the creation of sensors.\n for platform in PLATFORMS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(entry, platform)\n )\n\n \"\"\"Define services that publish data to MQTT. The published data is subscribed by openWB\n and the respective settings are changed.\"\"\"\n\n def fun_enable_disable_cp(call):\n \"\"\"Enable or disable charge point # --> set/lp#/ChargePointEnabled [0,1].\"\"\"\n topic = f\"{call.data.get('mqtt_prefix')}/set/lp{call.data.get('charge_point_id')}/ChargePointEnabled\"\n _LOGGER.debug(\"topic (enable_disable_cp): %s\", topic)\n\n if call.data.get(\"selected_status\") == \"On\":\n hass.components.mqtt.publish(topic, \"1\")\n else:\n hass.components.mqtt.publish(topic, \"0\")\n\n def fun_change_global_charge_mode(call):\n \"\"\"Change the wallbox global charge mode --> set/ChargeMode [0, .., 3].\"\"\"\n topic = f\"{call.data.get('mqtt_prefix')}/set/ChargeMode\"\n _LOGGER.debug(\"topic (change_global_charge_mode): %s\", topic)\n\n if call.data.get(\"global_charge_mode\") == \"Sofortladen\":\n payload = str(0)\n elif call.data.get(\"global_charge_mode\") == \"Min+PV-Laden\":\n payload = str(1)\n elif call.data.get(\"global_charge_mode\") == \"Nur PV-Laden\":\n payload = str(2)\n elif call.data.get(\"global_charge_mode\") == \"Stop\":\n payload = str(3)\n else:\n payload = str(4)\n hass.components.mqtt.publish(topic, payload)\n\n def fun_change_charge_limitation_per_cp(call):\n \"\"\"If box is in state 'Sofortladen', the charge limitation can be finetuned.\n --> config/set/sofort/lp/#/chargeLimitation [0, 1, 2].\n If the wallbox shall charge only a limited amount of energy [1] or to a certain SOC [2]\n --> config/set/sofort/lp/#/energyToCharge [value in kWh]\n --> config/set/sofort/lp/#/socToChargeTo [value in %]\n \"\"\"\n topic = f\"{call.data.get('mqtt_prefix')}/config/set/sofort/lp/{call.data.get('charge_point_id')}/chargeLimitation\"\n _LOGGER.debug(\"topic (change_charge_limitation_per_cp): %s\", topic)\n\n if call.data.get(\"charge_limitation\") == \"Not limited\":\n payload = str(0)\n hass.components.mqtt.publish(topic, payload)\n elif call.data.get(\"charge_limitation\") == \"kWh\":\n payload = str(1)\n topic2 = f\"{call.data.get('mqtt_prefix')}/config/set/sofort/lp/{call.data.get('charge_point_id')}/energyToCharge\"\n payload2 = str(call.data.get(\"energy_to_charge\"))\n hass.components.mqtt.publish(topic, payload)\n hass.components.mqtt.publish(topic2, payload2)\n elif call.data.get(\"charge_limitation\") == \"SOC\":\n payload = str(2)\n topic2 = f\"{call.data.get('mqtt_prefix')}/config/set/sofort/lp/{call.data.get('charge_point_id')}/socToChargeTo\"\n payload2 = str(call.data.get(\"required_soc\"))\n hass.components.mqtt.publish(topic, payload)\n hass.components.mqtt.publish(topic2, payload2)\n\n def fun_change_charge_current_per_cp(call):\n \"\"\"Set the charge current per loading point --> config/set/sofort/lp/#/current [value in A].\"\"\"\n topic = f\"{call.data.get('mqtt_prefix')}/config/set/sofort/lp/{call.data.get('charge_point_id')}/current\"\n _LOGGER.debug(\"topic (fun_change_charge_current_per_cp): %s\", topic)\n\n payload = str(call.data.get(\"target_current\"))\n hass.components.mqtt.publish(topic, payload)\n\n # Register our services with Home Assistant.\n hass.services.async_register(DOMAIN, \"enable_disable_cp\", fun_enable_disable_cp)\n hass.services.async_register(\n DOMAIN, \"change_global_charge_mode\", fun_change_global_charge_mode\n )\n hass.services.async_register(\n DOMAIN, \"change_charge_limitation_per_cp\", fun_change_charge_limitation_per_cp\n )\n hass.services.async_register(\n DOMAIN, \"change_charge_current_per_cp\", fun_change_charge_current_per_cp\n )\n\n # Return boolean to indicate that initialization was successfully.\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Unload all sensor entities and services if integration is removed via UI.\n No restart of home assistant is required.\"\"\"\n hass.services.async_remove(DOMAIN, \"enable_disable_cp\")\n hass.services.async_remove(DOMAIN, \"change_global_charge_mode\")\n hass.services.async_remove(DOMAIN, \"change_charge_limitation_per_cp\")\n hass.services.async_remove(DOMAIN, \"change_charge_current_per_cp\")\n unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)\n\n return unload_ok\n","sub_path":"custom_components/openwbmqtt/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483261282","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Odoo, Open Source Management Solution\n# Copyright (C) 2015-TODAY Anton Chepurov (anton.chepurov@gmail.com).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nimport itertools\nimport logging\n\nfrom openerp import api\nfrom openerp.osv import fields\nfrom openerp.osv.orm import BaseModel, except_orm, MAGIC_COLUMNS\nfrom openerp.tools.translate import _\n\n_logger = logging.getLogger(__name__)\n\n\ndef sel_val(self, field):\n assert len(self._ids) == 1, 'sel_val should be called for 1 record at a time'\n return dict(self._all_columns[field].column.selection)[getattr(self, field)]\n\nBaseModel.sel_val = sel_val\n\n\n@api.model\ndef is_portal(self):\n return self.env['res.users'].has_group('base.group_portal')\n\nBaseModel.is_portal = is_portal\n\n\n@api.model\n@api.returns('self', lambda value: list(value._ids))\ndef create_bulk(self, vals_bulk):\n self.check_access_rights('create')\n\n num_vals = len(vals_bulk)\n if not num_vals:\n return self.browse()\n\n # add missing defaults, and drop fields that may not be set by user\n allDefaults = self._add_missing_default_values({})\n newValsBulk = []\n for vals in vals_bulk:\n newVals = allDefaults.copy()\n newVals.update(vals)\n for field in itertools.chain(MAGIC_COLUMNS, ('parent_left', 'parent_right')):\n newVals.pop(field, None)\n newValsBulk.append(newVals)\n del vals_bulk\n vals_bulk = newValsBulk\n\n vals_0 = vals_bulk[0]\n num_fields, keys = len(vals_0), vals_0.viewkeys()\n if any(len(v) != num_fields for v in vals_bulk):\n raise except_orm(_('ValidateError'), 'Different number of fields in vals of the bulk')\n if any(v.viewkeys() != keys for v in vals_bulk):\n raise except_orm(_('ValidateError'), 'Different fields in the bulk')\n\n # split up fields into old-style and pure new-style ones\n old_vals_bulk, new_vals_bulk, unknown = [], [], []\n for idx in xrange(num_vals):\n old_vals_bulk.append({})\n new_vals_bulk.append({})\n for key in keys:\n field = self._fields.get(key)\n if field:\n if field.column or field.inherited:\n for idx, old_vals in enumerate(old_vals_bulk):\n old_vals[key] = vals_bulk[idx][key]\n if field.inverse and not field.inherited:\n for idx, new_vals in enumerate(new_vals_bulk):\n new_vals[key] = vals_bulk[idx][key]\n else:\n unknown.append(key)\n\n if unknown:\n _logger.warning(\"%s.create_bulk() with unknown fields: %s\", self._name, ', '.join(sorted(unknown)))\n\n # create record with old-style fields\n records = self.browse(self._create_bulk(old_vals_bulk))\n\n # put the values of pure new-style fields into cache, and inverse them\n if new_vals_bulk[0]:\n # todo\n raise except_orm('ImplementationError', 'Not implemented: debug normal create() method to get a clue on what should happen here')\n # record._cache.update(record._convert_to_cache(new_vals))\n # for key in new_vals:\n # self._fields[key].determine_inverse(record)\n\n return records\n\n\ndef _create_bulk(self, vals_bulk):\n # low-level implementation of create_bulk()\n cr, user, context = self.env.args\n if not context:\n context = {}\n\n if self.is_transient():\n self._model._transient_vacuum(cr, user)\n\n num_vals = len(vals_bulk)\n if not num_vals:\n return self.browse()\n\n cr.execute(\"SELECT nextval('%s') FROM generate_series(1,%s)\" % (self._sequence, num_vals))\n ids_new = cr.fetchall()\n ids_new = [t[0] for t in ids_new]\n\n vals_0 = vals_bulk[0]\n tocreate = {}\n for v in self._inherits:\n if self._inherits[v] not in vals_0:\n tocreate[v] = [{} for i in ids_new]\n else:\n tocreate[v] = [{'id': vals[self._inherits[v]]} for vals in vals_bulk]\n\n # list of column assignments defined as tuples like:\n # (column_name, format_string, column_value)\n # (column_name, sql_formula)\n # Those tuples will be used by the string formatting for the INSERT\n # statement below.\n ids_gen = iter(ids_new)\n updates = [[('id', str(ids_gen.next()))] for i in ids_new]\n\n upd_todo = []\n unknown_fields = []\n for v in vals_0.keys():\n if v in self._inherit_fields and v not in self._columns:\n (table, col, col_detail, original_parent) = self._inherit_fields[v]\n for idx, tocreate_vals in enumerate(tocreate[table]):\n tocreate_vals[v] = vals_bulk[idx][v]\n del vals_bulk[idx][v]\n else:\n if (v not in self._inherit_fields) and (v not in self._columns):\n for vals in vals_bulk:\n del vals[v]\n unknown_fields.append(v)\n if unknown_fields:\n _logger.warning('No such field(s) in model %s: %s.', self._name, ', '.join(unknown_fields))\n\n for table in tocreate:\n for vals in vals_bulk:\n if self._inherits[table] in vals:\n del vals[self._inherits[table]]\n\n record_id_bulk = [tocreate_vals.pop('id', None) for tocreate_vals in tocreate[table]]\n\n tocreate_vals, tocreate_idxs = [], []\n for idx, record_id in enumerate(record_id_bulk):\n if record_id is None or not record_id:\n tocreate_idxs.append(idx)\n tocreate_vals.append(tocreate[table][idx])\n else:\n self.pool[table].write(cr, user, [record_id], tocreate[table][idx], context=dict(context, recompute=True))\n updates[idx].append((self._inherits[table], '%s', record_id))\n\n record_ids = self.pool[table].create_bulk(cr, user, tocreate_vals, context=dict(context, recompute=True))\n assert len(record_ids) == len(tocreate_idxs), \\\n 'Less parent records created than needed. Expected: %s. Actual: %s' % (len(tocreate_idxs), len(record_ids))\n\n for i, record_id in enumerate(record_ids):\n idx = tocreate_idxs[i]\n updates[idx].append((self._inherits[table], '%s', record_id))\n del tocreate_vals, tocreate_idxs, record_id_bulk, record_ids\n del tocreate\n\n #Start : Set bool fields to be False if they are not touched(to make search more powerful)\n bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']\n\n for bool_field in bool_fields:\n if bool_field not in vals_0:\n for vals in vals_bulk:\n vals[bool_field] = False\n #End\n # todo: todo\n # for field in vals.keys():\n # fobj = None\n # if field in self._columns:\n # fobj = self._columns[field]\n # else:\n # fobj = self._inherit_fields[field][2]\n # if not fobj:\n # continue\n # groups = fobj.write\n # if groups:\n # edit = False\n # for group in groups:\n # module = group.split(\".\")[0]\n # grp = group.split(\".\")[1]\n # cr.execute(\"select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name='%s' and module='%s' and model='%s') and uid=%s\" % \\\n # (grp, module, 'res.groups', user))\n # readonly = cr.fetchall()\n # if readonly[0][0] >= 1:\n # edit = True\n # break\n # elif readonly[0][0] == 0:\n # edit = False\n # else:\n # edit = False\n #\n # if not edit:\n # vals.pop(field)\n for field in vals_0:\n current_field = self._columns[field]\n if current_field._classic_write:\n for idx, vals in enumerate(vals_bulk):\n updates[idx].append((field, '%s', current_field._symbol_set[1](vals[field])))\n\n #for the function fields that receive a value, we set them directly in the database\n #(they may be required), but we also need to trigger the _fct_inv()\n if (hasattr(current_field, '_fnct_inv')) and not isinstance(current_field, fields.related):\n #TODO: this way to special case the related fields is really creepy but it shouldn't be changed at\n #one week of the release candidate. It seems the only good way to handle correctly this is to add an\n #attribute to make a field `really readonly´ and thus totally ignored by the create()... otherwise\n #if, for example, the related has a default value (for usability) then the fct_inv is called and it\n #may raise some access rights error. Changing this is a too big change for now, and is thus postponed\n #after the release but, definitively, the behavior shouldn't be different for related and function\n #fields.\n upd_todo.append(field)\n else:\n #TODO: this `if´ statement should be removed because there is no good reason to special case the fields\n #related. See the above TODO comment for further explanations.\n if not isinstance(current_field, fields.related):\n upd_todo.append(field)\n if field in self._columns and hasattr(current_field, 'selection'):\n for vals in vals_bulk:\n if vals[field]:\n self._check_selection_field_value(field, vals[field])\n if self._log_access:\n for update in updates:\n update.append(('create_uid', '%s', user))\n update.append(('write_uid', '%s', user))\n update.append(('create_date', \"(now() at time zone 'UTC')\"))\n update.append(('write_date', \"(now() at time zone 'UTC')\"))\n\n # the list of tuples used in this formatting corresponds to\n # tuple(field_name, format, value)\n # In some case, for example (id, create_date, write_date) we does not\n # need to read the third value of the tuple, because the real value is\n # encoded in the second value (the format).\n cr.execute(\n \"\"\"INSERT INTO \"%s\" (%s) VALUES %s\"\"\" % (\n self._table,\n ', '.join('\"%s\"' % u[0] for u in updates[0]),\n ', '.join('(' + ','.join(u[1] for u in upd) + ')' for upd in updates)\n ),\n tuple(u[2] for upd in updates for u in upd if len(u) > 2)\n )\n del updates\n\n recs = self.browse(ids_new)\n\n if self._parent_store and not context.get('defer_parent_store_computation'):\n # todo\n raise except_orm('ImplementationError', 'Not implemented')\n # if self.pool._init:\n # self.pool._init_parent[self._name] = True\n # else:\n # parent = vals.get(self._parent_name, False)\n # if parent:\n # cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))\n # pleft_old = None\n # result_p = cr.fetchall()\n # for (pleft,) in result_p:\n # if not pleft:\n # break\n # pleft_old = pleft\n # if not pleft_old:\n # cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))\n # pleft_old = cr.fetchone()[0]\n # pleft = pleft_old\n # else:\n # cr.execute('select max(parent_right) from '+self._table)\n # pleft = cr.fetchone()[0] or 0\n # cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))\n # cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))\n # cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))\n # recs.invalidate_cache(['parent_left', 'parent_right'])\n\n # invalidate and mark new-style fields to recompute; do this before\n # setting other fields, because it can require the value of computed\n # fields, e.g., a one2many checking constraints on records\n recs.modified(self._fields)\n\n # call the 'set' method of fields which are not classic_write\n upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)\n\n # default element in context must be remove when call a one2many or many2many\n rel_context = context.copy()\n for c in context.items():\n if c[0].startswith('default_'):\n del rel_context[c[0]]\n\n result = []\n bulk_setters = ('property', 'many2many')\n for field in upd_todo:\n if type(self._columns[field]).__name__ in bulk_setters:\n v_bulk = [vals[field] for vals in vals_bulk]\n result += self._columns[field].set_bulk(self, cr, user, ids_new, field, v_bulk, rel_context) or []\n elif type(self._columns[field]).__name__ == 'function' and not getattr(self._columns[field], '_fnct_inv', None):\n pass\n else:\n raise except_orm('ImplementationError', 'Not implemented: set_bulk() for field %s' % (self._columns[field],))\n\n # for recomputing new-style fields\n recs.modified(upd_todo)\n\n # check Python constraints\n recs.with_context(prefetch_fields=False)._validate_fields(vals_0)\n\n if recs.env.recompute and context.get('recompute', True):\n result += recs._store_get_values(list(set(vals_0.keys() + self._inherits.values())))\n result.sort()\n ctx = dict(context, prefetch_fields=False)\n done = []\n for order, model_name, ids, fields2 in result:\n if not (model_name, ids, fields2) in done:\n self.pool[model_name]._store_set_values(cr, user, ids, fields2, ctx)\n done.append((model_name, ids, fields2))\n # recompute new-style fields\n recs.recompute()\n\n recs.check_access_rule('create')\n recs.create_workflow()\n return ids_new\n\nBaseModel._create_bulk = _create_bulk\nBaseModel.create_bulk = create_bulk\n\n\ndef _read_act_window(self, view_xml_id):\n view_fields = ['name', 'view_mode', 'view_id', 'view_type', 'res_model', 'type', 'target', 'context']\n return self.env.ref(view_xml_id).read(view_fields)[0]\n\nBaseModel._read_act_window = _read_act_window\n","sub_path":"models/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":15053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"648290303","text":"from bs4 import BeautifulSoup\nimport requests\nimport PIL.ImageChops as ImageChops\nfrom PIL import Image\nimport mysql.connector\nimport sys\n \nconn = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"ScooterSlider46$\", database=\"parionsamateur\")\ncursor = conn.cursor()\n\nequipe = []\nsoup = BeautifulSoup(open(\"./\"+sys.argv[1]), 'html.parser')\nnews_links = soup(\"td\",{'class':'blackBold'})\nfor elt in news_links:\n if (elt.a != None):\n req = \"SELECT idEquipes FROM equipes WHERE libelle='\"+elt.a.text.strip()+\"';\"\n cursor.execute(req)\n rows = cursor.fetchall()\n if (len(rows) == 0):\n newEquipe = (None, elt.a.text.strip())\n cursor.execute(\"INSERT INTO equipes (idEquipes, libelle) VALUES (Null, '\"+elt.a.text.strip()+\"')\")\n conn.commit() \n equipe.append(elt.a.text.strip())\nprint(equipe)","sub_path":"fichier/crawler_equipe.py","file_name":"crawler_equipe.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"549483819","text":"import numpy as np\nimport pandas as pd\nimport random\n\ndf= pd.read_csv(\"Heart_data_labels.csv\")\nfor i in [2,3,4]:\n df['Out'].replace(i,1,inplace = True)\ndf[\"Age\"] = (df[\"Age\"] - df[\"Age\"].min()) / (df[\"Age\"].max() - df[\"Age\"].min())\ndf[\"Trestbps\"] = (df[\"Trestbps\"] - df[\"Trestbps\"].min()) / (df[\"Trestbps\"].max() - df[\"Trestbps\"].min())\ndf[\"Chol\"] = (df[\"Chol\"] - df[\"Chol\"].min()) / (df[\"Chol\"].max() - df[\"Chol\"].min())\ndf[\"thalach\"] = (df[\"thalach\"] - df[\"thalach\"].min()) / (df[\"thalach\"].max() - df[\"thalach\"].min())\ndf.insert(14,\"Bias\",1)\nX = np.array(df.drop(\"Out\",axis = 1))\ny = np.transpose(np.array([df[\"Out\"]]))\nneta_o = 0.1\n\n\ndef non_linear(X,derivative = False):#sigmoidal activation function\n if derivative == True:\n return X*(1-X)\n else:\n return 1/(1+np.exp(-X))\n\n\ndef non_linear_relu(X,derivative = False):#relu activation function\n if derivative == True:\n X[X<=0] = 0\n X[X>0] = 1\n return X\n else:\n X[X<0]=0\n return X\n\n#Initialising the weights\nw = [0,0,0,0]\nw[0] = np.random.random((X.shape[1],12))\nw[1] = np.random.random((12,8))\nw[2] = np.random.random((8,6))\nw[3] = np.random.random((6,1))\n\n\n\nfor j in range(90000):\n np.random.shuffle(X)\n neta = neta_o/(1 + (j/10000))\n #Forward Propogation\n l0 = X\n l1 = non_linear(np.dot(l0,w[0]))\n l2 = non_linear(np.dot(l1,w[1]))\n l3 = non_linear(np.dot(l2,w[2]))\n l4 = non_linear(np.dot(l3,w[3]))\n l4_error = y - l4 \n if (j % 10000) == 0:\n print(\"Error : \" ,(1/len(X))*(np.sum(np.square(l4_error)))) #Error calculation for every 10000th iteration\n #Back Propogation\n l4_delta = l4_error * non_linear(l4,derivative = True)\n l3_error = l4_delta.dot(w[3].T) \n l3_delta = l3_error * non_linear(l3,derivative = True)\n l2_error = l3_delta.dot(w[2].T)\n l2_delta = l2_error * non_linear(l2,derivative = True) \n l1_error = l2_delta.dot(w[1].T) \n l1_delta = l1_error * non_linear(l1,derivative = True) \n #Updation of weights\n w[3] += neta*l3.T.dot(l4_delta)\n w[2] += neta*l2.T.dot(l3_delta)\n w[1] += neta*l1.T.dot(l2_delta)\n w[0] += neta*l0.T.dot(l1_delta)\n \n#These Weights can be used for Predicting the test set of data\n","sub_path":"Basic_MLP.py","file_name":"Basic_MLP.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"139050693","text":"from __future__ import absolute_import, unicode_literals\n\nimport datetime\nimport re\n\nfrom bs4 import BeautifulSoup, NavigableString, Tag as bsTag\n\nfrom luoo.models import Volume, VolumeAuthor, Tag\nfrom . import db, celery\nfrom .http import get\n\nvolume_url_pattern = re.compile(\"vol/index/(\\d+)$\")\nvolume_cover_pattern = re.compile(\"pics/vol/(.+?)!/fwfh/640x452$\")\nauthor_pattern = re.compile(\"author/(\\d+)$\")\nauthor_avatar_pattern = re.compile(\"pics/avatars/(.+?)!/fwfh/128x128$\")\nvolume_tag_pattern = re.compile(\"music/(\\w+?)$\")\n\n\ndef parse_volume_id(url):\n result = volume_url_pattern.search(url)\n return int(result.groups()[0])\n\n\ndef parse_volume_cover_name(url):\n result = volume_cover_pattern.search(url)\n return result.groups()[0]\n\n\ndef parse_author_id(url):\n result = author_pattern.search(url)\n return result.groups()[0]\n\n\ndef parse_tag_name(url):\n result = volume_tag_pattern.search(url)\n if result is not None:\n return result.groups()[0]\n return \"\"\n\n\ndef parse_author_avatar(url):\n result = author_avatar_pattern.search(url)\n return result.groups()[0]\n\n\ndef parse_paragraph(item):\n if isinstance(item, bsTag):\n if item.name == \"br\":\n return\n text = item.text.strip()\n if item.name == \"p\" and len(text) == 0:\n return\n return text\n\n if isinstance(item, NavigableString):\n text = item.strip()\n if len(text) > 0:\n return text\n return\n\n\ndef parse_volume_description_paragraphs(children):\n paragraphs = []\n for child in children:\n paragraph = parse_paragraph(child)\n if paragraph:\n paragraphs.append(paragraph)\n return paragraphs\n\n\nclass VolumePage:\n author = None\n volume = None\n tags = None\n\n def __init__(self, volume_url):\n self.volume_url = volume_url\n resp = get(volume_url)\n self.soup = BeautifulSoup(resp.content, \"lxml\")\n self.meta_element = self.soup.select_one(\".vol-meta\")\n\n def start_crawl(self):\n self.author = self.parse_author()\n self.volume = self.parse_volume()\n self.tags = self.parse_tags()\n\n def parse_volume(self):\n volume_id = parse_volume_id(self.volume_url)\n vol_name = self.soup.select_one(\".vol-name\")\n volume_number = vol_name.select_one(\".vol-number\").text\n volume_title = vol_name.select_one(\".vol-title\").text\n\n volume_prev = parse_volume_id(\n self.soup.select_one(\"#volCoverWrapper .nav-prev\").attrs[\"href\"]\n )\n volume_next = parse_volume_id(\n self.soup.select_one(\"#volCoverWrapper .nav-next\").attrs[\"href\"]\n )\n cover_url = self.soup.select_one(\"#volCoverWrapper img\").attrs[\"src\"]\n volume_cover = parse_volume_cover_name(cover_url)\n\n volume_created_at = self.meta_element.select_one(\".vol-date\").text\n\n children = self.soup.select_one(\".vol-desc\").children\n paragraphs = parse_volume_description_paragraphs(children)\n\n return {\n \"id\": volume_id,\n \"vol_number\": volume_number,\n \"name\": volume_title,\n \"description\": paragraphs,\n \"author_id\": self.author[\"id\"],\n \"prev\": volume_prev,\n \"next\": volume_next,\n \"cover\": volume_cover,\n \"created_at\": datetime.datetime.strptime(volume_created_at, \"%Y-%m-%d\"),\n }\n\n def parse_author(self):\n author_element = self.meta_element.select_one(\".vol-author\")\n author_name = author_element.text\n author_id = parse_author_id(author_element.attrs[\"href\"])\n author_avatar = parse_author_avatar(\n self.meta_element.select_one(\".author-avatar\").attrs[\"src\"]\n )\n return {\"id\": author_id, \"name\": author_name, \"avatar\": author_avatar}\n\n def parse_tags(self):\n tags = []\n for ele in self.soup.select(\".vol-tags .vol-tag-item\"):\n if isinstance(ele, bsTag) and ele.name == \"a\":\n if ele.text.startswith(\"#\"):\n alias = ele.text[1:]\n else:\n alias = ele.text\n tag = {\"name\": parse_tag_name(ele.attrs[\"href\"]), \"alias\": alias}\n tags.append(tag)\n return tags\n\n\n@celery.task\ndef crawl_volume_songs(volume_url):\n volume_page = VolumePage(volume_url)\n volume_page.start_crawl()\n\n author = VolumeAuthor.query.get(volume_page.author[\"id\"])\n if author is None:\n author = VolumeAuthor(**volume_page.author)\n db.session.add(author)\n db.session.add(author)\n volume = Volume(**volume_page.volume)\n db.session.add(volume)\n for item in volume_page.tags:\n tag = Tag.query.filter_by(alias=item[\"alias\"]).first()\n if tag is None:\n tag = Tag(**item)\n volume.tags.append(tag)\n\n db.session.commit()\n","sub_path":"luoo/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"75297827","text":"#!/usr/bin/env python\n\"\"\"\nThis scripts represents pipeline which do the following:\n1. reads data from sdf file and converts it to fingerprint,\nand saves it to table with solubility information\n2. The results are processed with xgboost and trained model is saved somewhere.\n3. given the results from p.1 and p.2, trained model tries to predict solubility\nfor structures in test dataset\n\nAll parts are independent and might be implemented as a separate scripts.\n\"\"\"\nimport argparse, os\nimport rdkit\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\n\nsdf_file_name = \"solubility_2007.sdf\"\n\n\ndef get_fingerprint(molecule, sep=\",\"):\n \"\"\"\n This is moved to separate function to change in 1 place when necessary\n returns string (probably ready for saving to .csv)\n warning!!! don't use GetMorganFingerprint(...)\n \"\"\"\n return sep.join([str(x) for x in AllChem.GetMorganFingerprintAsBitVect(molecule, 2)])\n \n \ndef load_database(filename, sep=\",\"):\n if not os.path.exists(filename):\n print(\"sdf database couldn't be found at '%s'\" % filename)\n exit(1)\n suppl = Chem.SDMolSupplier(filename)\n for mol in suppl:\n yield sep.join([mol.GetProp('EXPT'), get_fingerprint(mol, sep=sep)])\n \n \nif __name__==\"__main__\":\n with open('logS_data.csv', 'w') as f:\n for x in load_database(sdf_file_name):\n f.write(\"%s\\n\" % x)\n","sub_path":"solubility.py","file_name":"solubility.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"40154715","text":"__author__ = 'sei'\n\nimport os\nimport re\n\nimport numpy as np\nfrom scipy.optimize import minimize, curve_fit\nfrom scipy.signal import savgol_filter\n\nfrom plotsettings import *\n\nimport matplotlib.pyplot as plt\nfrom gauss_detect import *\nfrom gridfit import fit_grid\nfrom make_plotmap_darkfield import make_plotmap\n\npath = '/home/sei/Spektren/8/'\n\nsamples = ['8_C3_horzpol','8_C4_horzpol','8_D2_horzpol','8_D3_horzpol']\nnmpx = 2.63271 # nm/px\n\n\n# grid dimensions\nnx = 5\nny = 5\nmaxwl = 900\nminwl = 450\n\nfor sample in samples:\n print(sample)\n\n savedir = path + sample + '/'\n\n try:\n os.mkdir(savedir + \"plots/\")\n except:\n pass\n try:\n os.mkdir(savedir + \"specs/\")\n except:\n pass\n\n wl, lamp = np.loadtxt(open(savedir + \"lamp.csv\", \"rb\"), delimiter=\",\", skiprows=8, unpack=True)\n wl, dark = np.loadtxt(open(savedir + \"dark.csv\", \"rb\"), delimiter=\",\", skiprows=8, unpack=True)\n #bg = dark\n wl, bg = np.loadtxt(open(savedir + \"background.csv\", \"rb\"), delimiter=\",\", skiprows=8, unpack=True)\n\n mask = (wl >= minwl) & (wl <= maxwl)\n\n plt.plot(wl, lamp-dark)\n plt.savefig(savedir + \"plots/lamp.png\")\n plt.close()\n plt.plot(wl[mask], bg[mask])\n plt.savefig(savedir + \"plots/bg.png\")\n plt.close()\n plt.plot(wl[mask], dark[mask])\n plt.savefig(savedir + \"plots/dark.png\")\n plt.close()\n\n #print(\"-> fitting grid\")\n #inds, nxy, ids, a, b = fit_grid(xy, nx, ny)\n files, ids, xy = make_plotmap(savedir, nx, ny, minwl, maxwl,switch_xy=False)\n\n fig = newfig(0.9)\n cmap = sns.cubehelix_palette(light=1, as_cmap=True, reverse=True)\n colors = cmap(np.linspace(0.1, 1, len(files)))\n\n meanspec = np.zeros(lamp.shape)\n\n for i in range(len(files)):\n file = files[i]\n wl, counts = np.loadtxt(open(savedir + file, \"rb\"), delimiter=\",\", skiprows=12, unpack=True)\n #wl = wl[mask]\n counts = (counts - bg) / (lamp - dark)\n # counts = (counts-dark)/(lamp-dark)\n meanspec += counts\n #counts = counts[mask]\n # plt.plot(wl, counts,color=colors[i],linewidth=0.6)\n plt.plot(wl[mask], counts[mask], linewidth=0.6)\n\n meanspec /= len(files)\n plt.plot(wl[mask], meanspec[mask], color=\"black\", linewidth=1)\n plt.xlim((minwl, maxwl))\n plt.ylabel(r'$I_{df} [a.u.]$')\n plt.xlabel(r'$\\lambda [nm]$')\n plt.tight_layout()\n plt.savefig(savedir + 'Overview' + \".png\", dpi=200)\n plt.close()\n\n n = xy.shape[0]\n\n class Resonances():\n def __init__(self, id, amp, x0, sigma):\n self.id = id\n self.amp = amp\n self.x0 = x0\n self.sigma = sigma\n\n int532 = np.zeros(n)\n int581 = np.zeros(n)\n peak_wl = np.zeros(n)\n max_wl = np.zeros(n)\n resonances = np.array(np.repeat(None,n),dtype=object)\n searchmask = (wl >= 500) & (wl <= 900)\n\n #nxy = [[round(x,6),round(y,6)] for x,y in xy]\n for i in range(n):\n x = xy[i, 0]\n y = xy[i, 1]\n file = files[i]\n print(ids[i]+\" \"+file)\n wl, counts = np.loadtxt(open(savedir + file, \"rb\"), delimiter=\",\", skiprows=12, unpack=True)\n counts = (counts - bg) / (lamp - dark)\n\n counts[np.where(counts == np.inf)] = 0.0\n ind = np.argmax(counts)\n max_wl[i] = wl[ind]\n #counts = (counts - bg)\n #counts = counts - np.mean(counts[950:1023])\n #l = lamp - dark\n #l = l - np.mean(l[0:50])\n #counts = counts/l\n #counts = counts / lamp\n filtered = savgol_filter(counts, 27, 1, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0)\n\n #plt.figure(figsize=(8, 6))\n newfig(0.9)\n plt.plot(wl[mask], counts[mask],linewidth=1)\n #plt.plot(wl[mask], filtered[mask],color=\"black\",linewidth=0.6)\n plt.ylabel(r'$I_{df}\\, /\\, a.u.$')\n plt.xlabel(r'$\\lambda\\, /\\, nm$')\n plt.xlim((minwl, maxwl))\n #plt.plot(wl, counts)\n plt.tight_layout()\n #plt.savefig(savedir + \"plots/\" + ids[i] + \".png\",dpi=300)\n plt.savefig(savedir + \"plots/\" + ids[i] + \".eps\",dpi=1200)\n plt.close()\n #xx = wl[330:700]\n #yy = counts[330:700]\n #wl = wl[300:900]\n #counts = counts[300:900]\n xx = wl[searchmask][::5]\n #yy = counts[searchmask]\n yy = filtered[searchmask][::5]\n wl = wl[mask]\n counts = counts[mask]\n filtered = filtered[mask]\n #min_height = max(counts)*0.1#np.mean(counts[20:40])\n min_height = 0.01#0.006#0.015\n #----amp, x0, sigma = findGausses(xx,yy,min_height,30)\n #plotGausses(savedir + \"plots/\" + ids[i] + \"_gauss.png\",wl, filtered, amp, x0, sigma)\n #amp, x0, sigma = fitLorentzes(xx, yy, amp, x0, sigma,min_height*5,2,200)\n #def fitLorentzes_iter(x, y, min_heigth, min_sigma, max_sigma, iter):\n #amp, x0, sigma = fitLorentzes_iter(xx,yy,min_height,2,100,5)\n #amp, x0, sigma = fitLorentzes2(xx, yy, min_height,5,180,max_iter=len(amp)+1)\n\n\n # #----amp, x0, sigma = fitLorentzes3(xx, yy, amp, x0, sigma,min_height,2,200)\n #\n # amp, x0, sigma = fitLorentzes_iter(xx, yy, min_height,5,200, 2)\n #\n #\n # #amp, x0, sigma = findLorentzes(xx,yy,min_height,100)\n #\n #\n # ###plotLorentzes(savedir + \"plots/\" + ids[i] + \"_lorentz_test.png\",wl, counts, amp, x0, sigma)\n # #amp, x0, sigma = fitLorentzes(xx, yy, amp, x0, sigma,min_height,20,500)\n #\n # #plotLorentzes(savedir + \"plots/\" + ids[i] + \"_lorentz.png\",wl, counts, amp, x0, sigma)\n # plotLorentzes(savedir + \"plots/\" + ids[i] + \"_lorentz.png\", wl, filtered, amp, x0, sigma)\n #\n #print(sigma)\n f = open(savedir + \"specs/\" + ids[i] + \"_corr.csv\", 'w')\n f.write(\"x\" + \"\\r\\n\")\n f.write(str(x) + \"\\r\\n\")\n f.write(\"y\" + \"\\r\\n\")\n f.write(str(y) + \"\\r\\n\")\n f.write(\"\\r\\n\")\n f.write(\"wavelength,intensity\" + \"\\r\\n\")\n for z in range(len(counts)):\n f.write(str(wl[z]) + \",\" + str(counts[z]) + \"\\r\\n\")\n f.close()\n # ind = np.min(np.where(wl >= 531.5))\n # int532[i] = counts[ind]\n # ind = np.min(np.where(wl >= 580.5))\n # int581[i] = counts[ind]\n # ###resonances[i] = Resonances(ids[i],amp,x0,sigma)\n # ###if len(x0) > 0:\n # ### peak_wl[i] = x0[0]\n # ###else:\n # ### #peak_wl[i] = 0\n # ### peak_wl[i] = wl[np.argmax(filtered)]\n #\n #\n # f = open(savedir+\"peaks_532nm.csv\", 'w')\n # f.write(\"x,y,id,max\"+\"\\r\\n\")\n # for i in range(len(ids)):\n # f.write(str(xy[i,0])+\",\"+str(xy[i,1])+\",\"+str(ids[i])+\",\"+str(int532[i])+\"\\r\\n\")\n # f.close()\n #\n # f = open(savedir+\"peaks_581nm.csv\", 'w')\n # f.write(\"x,y,id,max\"+\"\\r\\n\")\n # for i in range(len(ids)):\n # f.write(str(xy[i,0])+\",\"+str(xy[i,1])+\",\"+str(ids[i])+\",\"+str(int581[i])+\"\\r\\n\")\n # f.close()\n #\n # f = open(savedir+\"peak_wl.csv\", 'w')\n # f.write(\"x,y,id,peak_wl\"+\"\\r\\n\")\n # for i in range(len(ids)):\n # f.write(str(xy[i,0])+\",\"+str(xy[i,1])+\",\"+str(ids[i])+\",\"+str(peak_wl[i])+\"\\r\\n\")\n # f.close()\n #\n # import pickle\n #\n # with open(savedir+r\"resonances.pickle\", \"wb\") as output_file:\n # pickle.dump(resonances, output_file)\n #\n # # newfig(0.9)\n # # plt.hist(peak_wl,50)\n # # plt.xlabel(r'$\\lambda_{max}\\, /\\, nm$')\n # # plt.ylabel('Häufigkeit')\n # # # plt.plot(wl, counts)\n # # plt.tight_layout()\n # # plt.savefig(savedir + \"hist.png\", dpi=300)\n # # plt.close()","sub_path":"detectparticles_darkfield_2_sample8.py","file_name":"detectparticles_darkfield_2_sample8.py","file_ext":"py","file_size_in_byte":7515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220530643","text":"from __future__ import absolute_import\n\nimport re\nimport weakref\nfrom uuid import uuid4\nfrom xml.etree import cElementTree as ElementTree\nfrom collections import defaultdict\n\nfrom couchdbkit.exceptions import BulkSaveError\n\nfrom casexml.apps.case.mock import CaseBlock, CaseFactory, CaseStructure\nfrom casexml.apps.case.xml import V1, V2, V2_NAMESPACE\nfrom casexml.apps.phone.exceptions import CouldNotPruneSyncLogs\nfrom casexml.apps.phone.models import get_properly_wrapped_sync_log\nfrom casexml.apps.phone.restore_caching import RestorePayloadPathCache\nfrom casexml.apps.phone.xml import SYNC_XMLNS\nfrom casexml.apps.stock.const import COMMTRACK_REPORT_XMLNS\nfrom casexml.apps.stock.mock import Balance\nfrom memoized import memoized\nfrom six.moves import range\n\n\ndef delete_sync_logs(before_date, limit=1000, num_tries=10):\n # Todo: convert to SQL including get_synclog_ids_before_date\n from casexml.apps.phone.dbaccessors.sync_logs_by_user import get_synclog_ids_before_date\n from casexml.apps.phone.models import SyncLog\n from dimagi.utils.couch.database import iter_bulk_delete_with_doc_type_verification\n\n for i in range(num_tries):\n try:\n sync_log_ids = get_synclog_ids_before_date(before_date, limit)\n return iter_bulk_delete_with_doc_type_verification(\n SyncLog.get_db(), sync_log_ids, 'SyncLog', chunksize=25)\n except BulkSaveError:\n pass\n\n raise CouldNotPruneSyncLogs()\n\n\nITEMS_COMMENT_PREFIX = b')')\n\n\ndef get_cached_items_with_count(cached_bytes):\n \"\"\"Get the number of items encoded in cached XML elements byte string\n\n The string, if it contains an item count, should be prefixed with\n b'', and finally the cached XML elements.\n\n Example: b'...'\n\n If the string does not start with b' %d\") % (fro, to))\r\n\r\n\r\ndef towersOfHanoi(N, fro, to, spare, indent) :\r\n\r\n if N == 1:\r\n moveOne(fro, to, indent)\r\n else:\r\n towersOfHanoi(N-1, fro, spare, to, indent+1)\r\n moveOne(fro, to, indent+1)\r\n towersOfHanoi(N-1, spare, to, fro, indent+1)\r\n\t\r\n\t\r\n\t\r\n##------------------- main ---------------------------##\r\ntowersOfHanoi(2, 1, 3, 2, 0)\r\nprint()\r\ntowersOfHanoi(3, 1, 3, 2, 0)\r\nprint()\r\ntowersOfHanoi(4, 1, 3, 2, 0)","sub_path":"class/Sample Code/Recursion/towers_of_hanoi2.py","file_name":"towers_of_hanoi2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"344930969","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 9 18:25:54 2020\r\n\r\n@author: Bharti Arora\r\n\"\"\"\r\n\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import scoped_session,sessionmaker\r\nengine = create_engine(\"postgres://boaqtdatmuhusp:568946665bde49b4c20c29ab15259a2c9029462c4d92a29fe9aa37c44dcfe580@ec2-50-17-90-177.compute-1.amazonaws.com:5432/dd4t41ubcfugk1\")\r\ndb = scoped_session(sessionmaker(bind=engine))\r\n\r\ndef main():\r\n #db.execute(\"CREATE TABLE books(isbn VARCHAR(255) PRIMARY KEY,author VARCHAR(255) NOT NULL,title VARCHAR(255) NOT NULL,year INTEGER NOT NULL);\");\r\n #db.execute(\"CREATE TABLE login(Id SERIAL PRIMARY KEY ,username VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL );\");\r\n #db.execute(\"CREATE TABLE users(Id SERIAL PRIMARY KEY,login_Id INTEGER NOT NULL,email VARCHAR(255) NOT NULL,name VARCHAR(255) NOT NULL,FOREIGN KEY (login_Id) REFERENCES login (Id) );\");\r\n #db.execute(\"CREATE TABLE reviews(Id SERIAL PRIMARY KEY,isbn VARCHAR(255) NOT NULL,comment VARCHAR(1000),user_Id INTEGER NOT NULL,rating INTEGER NOT NULL,FOREIGN KEY(user_Id) REFERENCES users(Id),FOREIGN KEY(isbn) REFERENCES books(isbn) );\");\r\n #db.execute(\"CREATE TABLE collection(Id SERIAL PRIMARY KEY,isbn VARCHAR(255) NOT NULL,catagory VARCHAR(255) NOT NULL,user_Id INTEGER NOT NULL,FOREIGN KEY(user_Id) REFERENCES users(Id),FOREIGN KEY(isbn) REFERENCES books(isbn));\")\r\n #db.execute(\"CREATE TABLE author_score(Id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL,score FLOAT DEFAULT (0) );\")\r\n #db.execute(\"CREATE TABLE book_score(Id SERIAL PRIMARY KEY,isbn VARCHAR(255) NOT NULL,score FLOAT DEFAULT (0) );\")\r\n login_id = (int)(db.execute(\"SELECT id FROM login WHERE username = :username ;\",{\"username\":username}).fetchone())\r\n print(login_id)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"creator.py","file_name":"creator.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104634797","text":"from math import *\n\nh_a = int(input(\"Numero de habitantes de uma cidade A: \"))\nh_b = int(input(\"Numero de habitantes de uma cidade B: \"))\nc_a = float(input(\"Percentual de crescimento populacional da cidade A: \"))\nc_b = float(input(\"Percentual de crescimento populacional da cidade B: \"))\n\ni = 1\nsoma_a = h_a\nsoma_b = h_b\n\nwhile (soma_a <= soma_b):\n\ta = soma_a * (c_a/100)\n\tsoma_a = a + soma_a\n\tb = soma_b * (c_b/100)\n\tsoma_b = b + soma_b\n\ti = i + 1\nprint(ceil(i))","sub_path":"exs/1493-1136.py","file_name":"1493-1136.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575486931","text":"import Live\nfrom LividConstants import *\n\nfrom RGBButtonElement import RGBButtonElement\nfrom _Framework.EncoderElement import EncoderElement\nfrom _Framework.ButtonElement import ButtonElement\n\n# NOTES\n# In theory, we can strip this back and intercept the Button calls\n# And we can force-map colors to greyscale as needed\n# Also, flashing as needed\n\nclass Elementary(object):\n \"\"\" This mixin provides shared methods to allow modular control of the encoder and button classes, as well as some boilerplate \"\"\"\n \n # We default to these classes\n # BUT any class using Elementary as a mixin can have these overriden on __init__\n def __init__(self, \n button_class = RGBButtonElement, \n color_mappings = None,\n encoder_class = EncoderElement, channel = 0):\n # We allow the initializer of this class to manually set which Element abstractions to use!\n self.channel = channel\n self.encoder_class = encoder_class\n self.button_class = button_class\n self.color_mappings = color_mappings\n self.cached_callbacks = [] # Cache callbacks so we can tear them down on disconnect\n\n\n def encoder(self, cc, map_mode = Live.MidiMap.MapMode.absolute):\n \"\"\" Build an encoder using parameters stored in the class\"\"\"\n return self.encoder_class(MIDI_CC_TYPE, self.channel, cc, map_mode) \n\n def button(self, note, **kwargs):\n \"\"\" Create a button of the cached class, and attach event callbacks for blinking \"\"\"\n # If we've set a color map for this class, splice it into the args\n # For each button\n # This will FAIL if using buttons that don't support color mappings\n if self.color_mappings is not None:\n kwargs[\"color_mappings\"] = self.color_mappings\n\n\n if isinstance(note, dict): # We can pass a dict with explicit options\n kwargs = dict(kwargs.items() + note.items())\n channel = note.get('channel', self.channel)\n button = self.button_class(True, MIDI_NOTE_TYPE, channel, kwargs.pop(\"note\"), **kwargs)\n\n else: # Or just a note\n button = self.button_class(True, MIDI_NOTE_TYPE, self.channel, note, **kwargs)\n\n if button.blink_on:\n self._register_timer_callback(button.blink)\n self.cached_callbacks.append(button.blink)\n return button\n\n def disconnect(self):\n for callback in self.cached_callbacks:\n self._unregister_timer_callback(callback)\n\n\n","sub_path":"_Livid_Framework/Elementary.py","file_name":"Elementary.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"597213304","text":"'''\nPython Workshop\n'''\n\n'''\nMulti-line comments go between 3 quotation marks\nYou can use single or double quotes\n'''\n\n# One-line comments are preceded by the pound symbol\n\n# BASIC DATA TYPES\n\nx = 5 # creates an object\nprint(type(x)) # check the type: int (not declared explicitly)\ntype(x) \ntype(5) # assigning it to a variable is not required\n\nprint(type(5.0)) # float\nprint(type('five')) # str\nprint(type(True)) # bool\n\n\n# LISTS\n\nnums = [5, 5.0, 'five'] # multiple data types\nprint(nums) # prints the list\nprint(type(nums)) # check the type: list\nprint(len(nums)) # check the length: 3\nprint(nums[0]) # print the first element\nnums[0] = 6 # replaces a list element\n\nnums.append(7) # list 'method' that modifies the list\nhelp(nums.append) # help on this method\nhelp(nums) # help on a list object\nnums.remove('five') # another list method\nprint(nums)\n\nprint(sorted(nums)) # 'function' that does not modify the list\nprint(nums) # it was not affected\nnums = sorted(nums) # overwrite the original list\nprint(nums)\nprint(sorted(nums, reverse = True)) # optional argument\n\n\n# FUNCTIONS\n\ndef give_me_five(): # function definition ends with colon\n return 5 # indentation required for function body\n \nprint(give_me_five()) # prints the return value (5)\nnum = give_me_five # assigns return value to a variable, doesn't print it\nprint(num)\n\ndef calc(x, y, op): # three parameters (without any defaults)\n if op == 'add':\n return x + y\n elif op == 'subtract':\n return x - y\n else:\n print('Valid operations: add, subtract')\n\nprint(calc(5 ,3 ,'add'))\nprint(calc(5 ,3 ,'subtract'))\nprint(calc(5, 3 ,'multiply'))\n#print(calc(5, 3)) # error\n\n# EXERCISE: Write a function that takes two parameters (hours and rate), and\n# returns the total pay\n\ndef pay(hours, rate):\n return hours * rate\n \nprint(pay(40, 10.50))\n\n\n# FOR LOOPS\n\n# prints each list element in uppercase\nfruits = ['apple', 'banana', 'cherry']\nfor fruit in fruits:\n print(fruit.upper())\n\n\n# LISTS\n\n# creating\na = [1, 2, 3, 4, 5] # create lists using brackets\n\n# slicing\nprint(a[0]) # returns 1 (Python is zero indexed)\nprint(a[1:3]) # returns [2, 3] (inclusive of the first index but exclusive of second)\nprint(a[-1]) # returns 5 (last element)\n\n# appending\n#a[5] = 6 # error because you can't assign outside the existing range\na.append(6) # list method that appends 6 to the end\na = a + [0] # use plus sign to combine lists\nprint(a)\n\n# checking length\nprint(len(a)) # returns 7\n\n# checking type\nprint(type(a)) # returns list\nprint(type(a[0])) # returns int\n\n# sorting\nprint(sorted(a)) # sorts the list\nprint(sorted(a, reverse = True)) # reverse = True is an 'optional argument'\n#sorted(a, True) # error because optional arguments must be named\n\n\n# STRINGS\n\n# creating\na = 'hello' # can use single or double quotes\n\n# slicing\nprint(a[0]) # returns 'h' (works like list slicing)\nprint(a[1:3]) # returns 'el'\nprint(a[-1]) # returns 'o'\n\n# concatenating\nprint(a + ' there') # use plus sign to combine strings\n#5 + ' there' # error because they are different types\nprint(str(5) + ' there') # cast 5 to a string in order for this to work\n\n# uppercasing\n#a[0] = 'H' # error because strings are immutable (can't overwrite char)\nprint(a.upper()) # string method (this method does not exist for lists)\n\n# checking length\nprint(len(a)) # returns 5 (number of characters)\n\n'''\nEXERCISE:\n1. Create a list of the first names of your family members\n2. Print the name of the last person in the list\n3. Print the length of the name of the first person in the list\n4. Change one of the names from their real name to their nickname\n5. Append a new person to the list\n6. Change the name of the new person to lowercase using the string method 'lower'\n7. Sort the list in reverse alphabetical order\nBonus: Sort the list by the length of the names (shortest to longest)\n'''\n\nnames = ['Ley', 'Moi', 'Pei', 'Jia']\nnames\nnames[-1]\nlen(names)\nnames[3] = 'Shoody'\nnames.append('Gunter')\nnames[-1] = names[-1].lower() # str.lower() method returns a copy of the string in which all case based characters are lowercased\nnames = sorted(names, reverse = True)\nnames = sorted(names, key = len) # value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes\n\n\n# FOR LOOPS AND LIST COMPREHENSIONS\n\n# for loop to print 1 through 5 \nnums = range(1, 6) # create a list of 1 through 5\nfor num in nums:\n print(num) # num 'becomes' each list element for one loop\n \n# for loop to print 1, 3, 5\nother = [1, 3, 5]\nfor x in other:\n print(x)\n \n# for loop to create a list of 2, 4, 6, 8, 10\ndoubled = []\nfor num in nums:\n doubled.append(num*2)\ndoubled\n \n# equivalent list comprehension\ndoubled = [num * 2 for num in nums] # expression goes first, brackets indicate we are storing results in a list\ndoubled\n\n'''\nEXERCISE 1:\nGiven that: letters = ['a', 'b', 'c']\nWrite a list comprehension that returns: ['A', 'B', 'C']\n\nEXERCISE 2:\nGiven that: word = 'abc'\nWrite a list comprehension that returns: ['A', 'B', 'C']\n\nEXERCISE 3:\nGiven that: fruits = ['Apple', 'Banana', 'Cherry']\nWrite a list comprehension that returns: ['A', 'B', 'C']\n'''\n\nletters = ['a', 'b', 'c']\nl_up = [letter.upper() for letter in letters]\nprint(l_up)\n\nword = 'abc'\nword_up = [w.upper() for w in word]\nprint(word_up)\n\nfruits = ['Apple', 'Banana', 'Cherry']\nfruits_up = [fruit[0] for fruit in fruits]\nprint(fruits_up)\n\n\n# DICTIONARIES\n\n# dictionaries are made of key-value pairs (like a real dictionary)\nfamily = {'dad': 'Homer', 'mom': 'Marge', 'size': 2}\n\n# check the length\nlen(family) # returns 3 (number of key-value pairs)\n\n# use the key to look up a value (fast operation regardless of dictionary size)\nfamily['dad'] # returns 'Homer'\n\n# can't use a value to look up a key\n#family['Homer'] # error\n\n# dictionaries are unordered\n#family[0] # error\n\n# add a new entry\nfamily['cat'] = 'snowball ii'\n\n# delete an entry\ndel family['cat']\n\n# keys can be strings or numbers or tuples, values can be any type\nfamily['kids'] = ['bart', 'lisa']\n\n# accessing a list element within a dictionary\nfamily['kids'][0] # returns 'bart'\n\n# useful methods\nfamily.keys() # returns list: ['dad', 'kids', 'mom', 'size']\nfamily.values() # returns list: ['Homer', ['bart', 'lisa'], 'Marge', 2]\nfamily.items() # returns list of tuples\n # [('dad', 'Homer'), ('kids', ['bart', 'lisa']), ('mom', 'Marge'), ('size', 2)]\n \n'''\nEXERCISE:\n1. Print the name of the mom\n2. Change the size to 5\n3. Add 'Maggie' to the list of kids\n4. Fix 'bart' and 'lisa' so that the first letter is capitalized\nBonus: Do this last step using a list comprehension\n'''\n\nfamily['mom'] # returns 'Marge'\nfamily['size'] = 5 # replaces existing value for 'size'\nfamily['kids'].append('Maggie') # access a list, then append 'Maggie' to it\nfor i in range(0,2):\n family['kids'][i] = family['kids'][i][0].upper() + family['kids'][i][1:]\n\nfor kid in family['kids']:\n kid = kid[0].upper() + kid[1: ]\nfamily\n\nfamily['kids'] = [family['kids'][i][0].upper() + family['kids'][i][1:] for i in range(0,3)]\nfamily\n\nfamily['kids'] = [kid[0].upper() + kid[1:] for kid in family['kids']]\nfamily\n\n\n# REQUESTS\n\n# import module (make its functions available)\nimport requests\n\n# use requests to talk yo the web\nr = requests.get('http://www.google.com')\ntype(r) # special 'response' object\nr.text # HTML of web page stored as string\ntype(r.text) # string is encoded as unicode\nr.text[0] # string can be sliced like any string\n\n\n'''\nAPIs\n\nWhat is an API?\n- Application Programming Interface\n- Structured way to expose specific functionality and data access to users\n- Web APIs usually follow the 'REST' standard\n\nHow to interact with a REST API:\n- Make a 'request' to a specific URL (an 'endpoint') and get the data back in a response\n- Most relevant request method is GET (other methods: POST, PUT, DELETE)\n- Response is often JSON format\n- Web console is sometimes available (allows you to explore an API)\n'''\n\nr = requests.get(\"https://api.spotify.com/v1/albums/4aawyAB9vmqN3uQ7FjRGTy/tracks?market=ES&format=json\")\ntype(r)\nr.text\ntype(r.text)\nr.json()\ntype(r.json)\nalbum = r.json()\n\nsongs = album['items']\n\nnames = [song['name'] for song in songs]\n\n","sub_path":"0_python_workshop.py","file_name":"0_python_workshop.py","file_ext":"py","file_size_in_byte":9183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"114850843","text":"\n\nfrom ..utils import Object\n\n\nclass SetSupergroupDescription(Object):\n \"\"\"\n Changes information about a supergroup or channel; requires appropriate administrator rights \n\n Attributes:\n ID (:obj:`str`): ``SetSupergroupDescription``\n\n Args:\n supergroup_id (:obj:`int`):\n Identifier of the supergroup or channel \n description (:obj:`str`):\n New supergroup or channel description; 0-255 characters\n\n Returns:\n Ok\n\n Raises:\n :class:`telegram.Error`\n \"\"\"\n ID = \"setSupergroupDescription\"\n\n def __init__(self, supergroup_id, description, extra=None, **kwargs):\n self.extra = extra\n self.supergroup_id = supergroup_id # int\n self.description = description # str\n\n @staticmethod\n def read(q: dict, *args) -> \"SetSupergroupDescription\":\n supergroup_id = q.get('supergroup_id')\n description = q.get('description')\n return SetSupergroupDescription(supergroup_id, description)\n","sub_path":"pytglib/api/functions/set_supergroup_description.py","file_name":"set_supergroup_description.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"150336888","text":"\"\"\"\nDescription:\nA web scraper that downloads all hackles.org comics. I love this comic! \n\nLicense:\nThe MIT License (MIT). Please see MIT-License.txt for more information.\n\nAll feedback is appreciated!\n\"\"\"\n\nimport urllib\nimport os\n\nfolder = \"hackles\"\n\n# Create folder if it doesn't exist\nif not os.path.exists(folder):\n os.makedirs(folder)\n\n# All comic from first to last\nfor i in range(1, 365):\n filename = \"cartoon%s.png\" % i\n url = \"http://hackles.org/strips/%s\" % filename\n urllib.urlretrieve(url, \"%s\" % os.path.join(folder, filename))\n","sub_path":"hackles.py","file_name":"hackles.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"581605251","text":"from unittest import mock\n\nfrom django.test import TestCase, RequestFactory, Client\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import auth\n\nfrom tse.forms import ProjectQuestionsForm\nfrom tse.models import Organisation, Project, User, \\\n ProjectDeclaration, ProjectWhitelist\nfrom user_accounts.models import Profile\nfrom tse.models import DiscountStage, ProjectPageSection\nfrom tse.views import QuestionnaireWizardView, projects_view\nfrom tse.views import project_details_view, project_invest_view, \\\n project_declaration_choices\nfrom tse.coinmarketcap import get_coinmarketcap_client\nfrom datetime import datetime, timedelta\nimport pytz\nfrom unittest.mock import patch, ANY\nfrom trading.tests.common import MockResponse\nfrom django.urls import reverse\n\n\nclass QuestionnaireWizrardViewTest(TestCase):\n\n @mock.patch(\"tse.views.Organisation\")\n def test_get_form(self, org):\n qv = QuestionnaireWizardView()\n qv.request = mock.Mock()\n qv.steps = mock.Mock()\n qv.steps.current = 0\n qv.initial_dict = {}\n qv.instance_dict = {}\n form = qv.get_form()\n self.assertTrue(isinstance(form, ProjectQuestionsForm))\n\n def test_get(self):\n qv = QuestionnaireWizardView()\n qv.request = mock.Mock()\n qv.request.user.organisation_set.count.return_value = 0\n res = qv.get()\n self.assertIsInstance(res, HttpResponseRedirect)\n\n def test_post(self):\n qv = QuestionnaireWizardView()\n qv.request = mock.Mock()\n qv.request.user.organisation_set.count.return_value = 0\n res = qv.post()\n self.assertIsInstance(res, HttpResponseRedirect)\n\n @mock.patch('tse.views.Questionnaire')\n def test_done(self, q):\n qv = QuestionnaireWizardView()\n qv.request = mock.Mock()\n f1 = mock.Mock()\n res = qv.done([f1()], {})\n self.assertIsInstance(res, HttpResponseRedirect)\n\n @mock.patch('tse.views.Questionnaire')\n def test_populate_instance_data(self, q):\n qv = QuestionnaireWizardView()\n qv.kwargs = {\"pk\": 4}\n qv._populate_instance_data()\n q.objects.get.return_value.projectquestions_set\\\n .all.assert_called_with()\n q.objects.get.return_value.teamquestions_set\\\n .all.assert_called_with()\n q.objects.get.return_value.tsequestions_set\\\n .all.assert_called_with()\n q.objects.get.return_value.questionquestions_set\\\n .all.assert_called_with()\n\n\nclass ProjectsOverviewTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n creator = User(email='a@b.c', password='abc')\n creator.save()\n org = Organisation(name='Test Org', created_by=creator)\n org.save()\n project_a = Project(\n name='Project A',\n active=True,\n creator=creator,\n organisation=org)\n project_a.save()\n project_b = Project(\n name='Project B',\n active=True,\n creator=creator,\n organisation=org)\n project_b.save()\n\n discount_stage_project_a = DiscountStage(project=project_a, created_by=creator, title='Stage A:A', discount=50, start_date=datetime.now(pytz.UTC)-timedelta(days=1), end_date=datetime.now(pytz.UTC)+timedelta(hours=23)) # noqa: E501\n discount_stage_project_a.save()\n\n discount_stage_project_b_a = DiscountStage(project=project_b, created_by=creator, title='Stage B:A', discount=40, start_date=datetime.now(pytz.UTC)-timedelta(days=2), end_date=datetime.now(pytz.UTC)+timedelta(hours=23)) # noqa: E501\n discount_stage_project_b_a.save()\n discount_stage_project_b_b = DiscountStage(project=project_b, created_by=creator, title='Stage B:B', discount=25, start_date=datetime.now(pytz.UTC)+timedelta(days=2), end_date=datetime.now(pytz.UTC)+timedelta(days=3)) # noqa: E501\n discount_stage_project_b_b.save()\n\n def test_projects_view(self):\n request = self.factory.get('/tse/projects')\n\n response = projects_view(request)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Project A')\n self.assertContains(response, 'Project B')\n self.assertContains(response, 'Current discount 50%')\n self.assertContains(response, 'Current discount 40%')\n self.assertNotContains(response, 'Current discount 25%')\n\n\nclass ProjectDetailsTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n self.creator = User(email='a@b.c', password='abc')\n org = Organisation(name='Test Org', created_by=self.creator)\n self.project = Project(\n name='Test project',\n active=True,\n creator=self.creator,\n organisation=org)\n self.creator.save()\n org.save()\n self.project.save()\n\n discount_stage_a = DiscountStage(project=self.project, created_by=self.creator, title='Stage A', discount=50, start_date=datetime.now(pytz.UTC)-timedelta(days=1), end_date=datetime.now(pytz.UTC)+timedelta(hours=23)) # noqa: E501\n discount_stage_a.save()\n\n discount_stage_b = DiscountStage(project=self.project, created_by=self.creator, title='Stage B', discount=25, start_date=datetime.now(pytz.UTC)+timedelta(days=2), end_date=datetime.now(pytz.UTC)+timedelta(days=3)) # noqa: E501\n discount_stage_b.save()\n\n page_section_markdown = ProjectPageSection(project=self.project, created_by=self.creator, template='markdown', data=\"I'm [Markdown](https://www.markdown.org/) enabled with **bold** and _italic_ styling.\", order_nr=10) # noqa: E501\n page_section_markdown.save()\n\n page_section_people = ProjectPageSection(project=self.project, created_by=self.creator, template='people', data=\"- name: John Doe\\n image: https://path.to/img/john.png\\n title: CEO\\n linkedin: https://www.linkedin.com/in/johndoe\", order_nr=20) # noqa: E501\n page_section_people.save()\n\n def test_project_details_view(self):\n request = self.factory.get('/tse/project/' + str(self.project.id))\n request.user = auth.get_user(Client())\n self.assertTrue(request.user.is_anonymous)\n\n response = project_details_view(request, self.project.id)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Test project')\n self.assertContains(response, 'Current discount 50%')\n self.assertNotContains(response, 'Current discount 25%')\n self.assertContains(response, 'John Doe')\n self.assertContains(response, 'bold')\n\n def test_malformed_yaml(self):\n request = self.factory.get('/tse/project/' + str(self.project.id))\n request.user = auth.get_user(Client())\n\n page_section_malformed_yaml = ProjectPageSection(project=self.project, created_by=self.creator, template='people', data=\"[]foo]\", order_nr=30) # noqa: E501\n page_section_malformed_yaml.save()\n\n response = project_details_view(request, self.project.id)\n self.assertContains(response, 'ERR: YAML')\n\n\nclass ProjectInvestTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n self.creator = User(\n id='65888f1a-faa4-4385-8973-1d1eabe22836',\n email='a@b.c',\n password='abc')\n self.profile = Profile.objects.create(\n user_id='65888f1a-faa4-4385-8973-1d1eabe22836',\n first_name='John',\n last_name='Doe',\n verified='t',\n country='DNK',\n country_from_id='DNK'\n )\n self.profile.save()\n org = Organisation(name='Test Org', created_by=self.creator)\n self.project = Project(\n name='Test project',\n active=True,\n creator=self.creator,\n organisation=org,\n token_investment_address='0x1234567890123456789012345678901234567890', # noqa: E501\n token_contract_address='0x1234567890123456789012345678901234567891', # noqa: E501\n token_decimals=8,\n token_exchange_rate=0.001,\n token_symbol='ACME',\n ssot_project_announcement='https://path.to/announcement',\n min_investment_eth=1,\n max_investment_eth=999,\n distribution_time='2 days',\n unlocking_time='2 weeks',\n listing_time='2 months'\n )\n self.creator.save()\n org.save()\n self.project.save()\n\n self.discount_stage_a = DiscountStage(project=self.project, created_by=self.creator, title='Stage A', discount=50, start_date=datetime.now(pytz.UTC)-timedelta(days=1), end_date=datetime.now(pytz.UTC)+timedelta(hours=23)) # noqa: E501\n self.discount_stage_a.save()\n\n self.discount_stage_b = DiscountStage(project=self.project, created_by=self.creator, title='Stage B', discount=25, start_date=datetime.now(pytz.UTC)+timedelta(days=2), end_date=datetime.now(pytz.UTC)+timedelta(days=3)) # noqa: E501\n self.discount_stage_b.save()\n\n def test_project_invest_view_anonymous(self):\n request = self.factory.get(\n '/tse/project/' + str(self.project.id) + '/invest')\n request.user = auth.get_user(Client())\n self.assertTrue(request.user.is_anonymous)\n response = project_invest_view(request, self.project.id)\n self.assertEqual(response.status_code, 302)\n\n def test_project_invest_view(self):\n ProjectDeclaration(\n user_id=self.creator.id,\n project_id=self.project.id,\n declaration_key='confirm_test',\n declaration_text='I confirm this is a test.'\n ).save()\n\n client = Client()\n client.force_login(self.creator)\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/invest',\n follow=True\n )\n\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Test project')\n self.assertContains(response, 'Current discount 50%')\n self.assertNotContains(response, 'Current discount 25%')\n self.assertContains(\n response,\n '0x1234567890123456789012345678901234567890')\n self.assertContains(\n response,\n 'Token contract address: 0x1234567890123456789012345678901234567891') # noqa: E501\n self.assertContains(response, 'Token symbol: ACME')\n self.assertContains(response, 'Decimals: 8')\n self.assertContains(response, 'Min investment: 1')\n self.assertContains(response, 'Max investment: 999')\n self.assertContains(\n response,\n 'Token exchange rate: 1 ETH = 0.001 ACME')\n self.assertContains(response, 'ETH exchange rate: 1 ETH = $')\n self.assertContains(response, '2 days')\n self.assertContains(response, '2 weeks')\n self.assertContains(response, '2 months')\n\n now = datetime.now(pytz.UTC)\n self.discount_stage_a.start_date = now+timedelta(days=1)\n self.discount_stage_a.end_date = now+timedelta(days=2)\n self.discount_stage_a.save()\n self.discount_stage_b.start_date = now+timedelta(days=2)\n self.discount_stage_b.end_date = now+timedelta(days=3)\n self.discount_stage_b.save()\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/invest',\n follow=True\n )\n self.assertNotContains(response, 'Current discount 50%')\n self.assertContains(response, 'Kick off')\n\n self.discount_stage_a.start_date = now-timedelta(days=4)\n self.discount_stage_a.end_date = now-timedelta(days=3)\n self.discount_stage_a.save()\n self.discount_stage_b.start_date = now-timedelta(days=2)\n self.discount_stage_b.end_date = now-timedelta(days=1)\n self.discount_stage_b.save()\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/invest',\n follow=True\n )\n self.assertNotContains(response, 'Current discount 50%')\n self.assertNotContains(response, 'Kick off')\n self.assertContains(response, 'Finished')\n\n def test_project_invest_view_project_declaration_false(self):\n\n client = Client()\n client.force_login(self.creator)\n\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/invest',\n follow=True\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=reverse(\n 'tse:project-declaration',\n args=[self.project.id]\n )\n )\n\n def test_project_invest_view_can_invest_false(self):\n self.profile.country = 'USA'\n self.profile.save()\n\n client = Client()\n client.force_login(self.creator)\n\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/invest',\n follow=True\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=reverse('tse:country-restricted')\n )\n\n @patch(\"requests.get\")\n def test_get_eth_exchange_rate(self, mockrequestsget):\n mockrequestsget.return_value = \\\n MockResponse(\n {},\n 200\n )\n\n coinmarketcap_client = get_coinmarketcap_client()\n eth_to_usd = coinmarketcap_client.get_eth_exchange_rate()\n # self.assertRaises(RuntimeError)\n self.assertIsNone(eth_to_usd)\n\n\nclass ProjectCreateTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n self.user = User(\n id='65888f1a-faa4-4385-8973-1d1eabe22836',\n email='a@b.c',\n password='abc')\n self.user.save()\n Profile.objects.create(\n user_id='65888f1a-faa4-4385-8973-1d1eabe22836',\n first_name='John',\n last_name='Doe',\n verified=True\n )\n\n def test_project_create_view_no_org(self):\n client = Client()\n client.force_login(self.user)\n response = client.get(\n '/tse/project/',\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=f'{reverse(\"organisations:organisation-add\")}?next=/tse/project/' # noqa: E501\n )\n\n def test_project_create_view(self):\n org = Organisation(name='Test Org', created_by=self.user)\n org.save()\n\n client = Client()\n client.force_login(self.user)\n response = client.get(\n '/tse/project/',\n )\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Project')\n\n def test_project_create_view_post(self):\n org = Organisation(name='Test Org', created_by=self.user)\n org.save()\n\n client = Client()\n client.force_login(self.user)\n\n response = client.post(\n '/tse/project/',\n data={\n 'name': 'Test Project',\n 'organisation': str(org.id),\n },\n follow=True\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=reverse('tse:project-done')\n )\n\n def test_project_edit_view(self):\n org = Organisation(name='Test Org', created_by=self.user)\n org.save()\n project = Project(\n name='Project A',\n active=True,\n creator=self.user,\n organisation=org)\n project.save()\n\n client = Client()\n client.force_login(self.user)\n response = client.get(\n reverse('tse:project-edit', args=[project.id]),\n )\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Project A')\n\n def test_project_invalid_edit_view(self):\n org = Organisation(name='Test Org', created_by=self.user)\n org.save()\n project = Project(\n name='Project A',\n active=True,\n creator=self.user,\n organisation=org)\n project.save()\n\n client = Client()\n client.force_login(self.user)\n with self.assertRaises(RuntimeError):\n client.post(\n reverse(\n 'tse:project-edit',\n args=['65888f1a-faa4-4385-8973-1d1eabe22836']),\n data={\n 'name': 'Test Project',\n 'organisation': str(org.id),\n }\n )\n\n def test_project_edit_view_post(self):\n org = Organisation(name='Test Org', created_by=self.user)\n org.save()\n project = Project(\n name='Project A',\n active=True,\n creator=self.user,\n organisation=org)\n project.save()\n\n client = Client()\n client.force_login(self.user)\n\n response = client.post(\n reverse('tse:project-edit', args=[project.id]),\n data={\n 'name': 'Test Project',\n 'organisation': str(org.id),\n },\n follow=True\n )\n self.assertContains(\n response,\n 'Test Project'\n )\n\n\nclass ProjectDeclarationTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n self.user = User(\n id='65888f1a-faa4-4385-8973-1d1eabe22836',\n email='a@b.c',\n password='abc')\n self.user.save()\n self.profile = Profile.objects.create(\n user_id='65888f1a-faa4-4385-8973-1d1eabe22836',\n first_name='John',\n last_name='Doe',\n country='DNK',\n country_from_id='DNK',\n verified=True\n )\n self.org = Organisation(name='Test Org', created_by=self.user)\n self.org.save()\n self.project = Project(\n name='Project A',\n active=True,\n creator=self.user,\n organisation=self.org)\n self.project.save()\n self.project_whitelist = ProjectWhitelist(\n project=self.project,\n contract_address='0xE74F303c4665C54dA89e8782a74CaBbB07B46Ab7'\n )\n self.project_whitelist.save()\n\n def test_project_declaration_view_get(self):\n client = Client()\n client.force_login(self.user)\n\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/declaration',\n )\n self.assertEqual(\n 200,\n response.status_code\n )\n self.assertContains(\n response,\n 'id=\"confirm_terms\"'\n )\n self.assertContains(\n response,\n 'id=\"confirm_countries\"'\n )\n self.assertContains(\n response,\n 'id=\"confirm_funds\"'\n )\n\n def test_project_declaration_view_post(self):\n # preconditions\n self.assertEqual(\n 0,\n ProjectDeclaration.objects.all().count()\n )\n\n client = Client()\n client.force_login(self.user)\n\n response = client.post(\n '/tse/project/' + str(self.project.id) + '/declaration',\n data={\n 'confirms': [\n 'confirm_terms', 'confirm_countries', 'confirm_funds'\n ]\n },\n follow=False\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=reverse(\n 'tse:project-add-to-whitelist',\n args=[self.project.id]\n ),\n fetch_redirect_response=False\n )\n self.assertEqual(\n 3,\n ProjectDeclaration.objects.all().count()\n )\n project_declarations = ProjectDeclaration.objects\\\n .order_by('declaration_key')\\\n .all()\n self.assertEqual(\n self.user.id,\n str(project_declarations[0].user.id)\n )\n self.assertEqual(\n str(self.project.id),\n str(project_declarations[0].project.id)\n )\n self.assertEqual(\n 'confirm_countries',\n str(project_declarations[0].declaration_key)\n )\n self.assertEqual(\n 'confirm_funds',\n str(project_declarations[1].declaration_key)\n )\n self.assertEqual(\n 'confirm_terms',\n str(project_declarations[2].declaration_key)\n )\n\n def test_project_declaration_view_post_validation_error(self):\n \"\"\"\n POST with missing confirms value - confirm_funds.\n \"\"\"\n # preconditions\n self.assertEqual(\n 0,\n ProjectDeclaration.objects.all().count()\n )\n\n client = Client()\n client.force_login(self.user)\n\n response = client.post(\n '/tse/project/' + str(self.project.id) + '/declaration',\n data={\n 'confirms': [\n 'confirm_terms', 'confirm_countries'\n ]\n },\n follow=True\n )\n self.assertEqual(\n 200,\n response.status_code\n )\n self.assertContains(\n response,\n 'All confirmations must be checked.'\n )\n self.assertEqual(\n 0,\n ProjectDeclaration.objects.all().count()\n )\n\n def test_project_declaration_choices(self):\n request = self.factory.get('/kyc/')\n request.user = self.user\n choices = project_declaration_choices(request, self.project)\n self.assertEqual(\n 3,\n len(choices)\n )\n\n def test_project_declaration_choices_aus(self):\n request = self.factory.get('/kyc/')\n self.profile.country = 'AUS'\n self.profile.save()\n request.user = self.user\n choices = project_declaration_choices(request, self.project)\n self.assertEqual(\n 4,\n len(choices)\n )\n self.assertTrue(\n 1,\n len([item for item in choices if 'confirm_aus_sophisticated' in item]) # noqa: E501\n )\n\n\nclass ProjectAddToWhitelistTest(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n self.user = User(\n id='65888f1a-faa4-4385-8973-1d1eabe22836',\n email='a@example.com',\n password='abc')\n self.user.save()\n self.profile = Profile.objects.create(\n user_id='65888f1a-faa4-4385-8973-1d1eabe22836',\n first_name='John',\n last_name='Doe',\n verified='t',\n country='DNK',\n country_from_id='DNK',\n eth_address='0x10594B019de165B051c2dD99ED484DC9DAA20005'\n )\n self.profile.save()\n self.org = Organisation(name='Test Org', created_by=self.user)\n self.org.save()\n self.project = Project(\n name='Project A',\n active=True,\n creator=self.user,\n organisation=self.org)\n self.project.save()\n self.project_whitelist = ProjectWhitelist(\n project=self.project,\n contract_address='0xE74F303c4665C54dA89e8782a74CaBbB07B46Ab7'\n )\n self.project_whitelist.save()\n ProjectDeclaration(\n user_id=self.user.id,\n project_id=self.project.id,\n declaration_key='confirm_test',\n declaration_text='I confirm this is a test.'\n ).save()\n\n @patch(\"tse.views.add_address_to_whitelist\", autospec=True) # noqa: E501\n def test_project_add_to_whitelist(self, whitelist_mock):\n\n whitelist_mock.return_value = 'ADDED'\n client = Client()\n client.force_login(self.user)\n\n response = client.get(\n '/tse/project/' + str(self.project.id) + '/add-to-whitelist',\n follow=False\n )\n self.assertRedirects(\n response,\n status_code=302,\n target_status_code=200,\n expected_url=reverse('tse:project-invest', args=[self.project.id]),\n fetch_redirect_response=False\n )\n whitelist_mock.assert_called_once_with(\n eth_address=self.profile.eth_address,\n geth_node_client=ANY,\n user=ANY,\n whitelist_contract_address=self.project_whitelist.contract_address, # noqa: E501\n whitelist_contract_owner_private_key=ANY\n )\n","sub_path":"web/tse/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":24653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465147780","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 4 12:32:53 2017\n\n@author: wroscoe\n\"\"\"\nimport os\nimport sys\nimport time\nimport json\nimport datetime\nimport random\nimport glob\nimport numpy as np\nimport pandas as pd\n\nfrom PIL import Image\nfrom donkeycar import utils\n\nfrom AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient\n\n\nclass Tub(object):\n \"\"\"\n A datastore to store sensor data in a key, value format.\n\n Accepts str, int, float, image_array, image, and array data types.\n\n For example:\n\n #Create a tub to store speed values.\n >>> path = '~/mydonkey/test_tub'\n >>> inputs = ['user/speed', 'cam/image']\n >>> types = ['float', 'image']\n >>> t=Tub(path=path, inputs=inputs, types=types)\n\n \"\"\"\n\n def __init__(self, path, inputs=None, types=None):\n\n self.path = os.path.expanduser(path)\n print('path_in_tub:', self.path)\n self.meta_path = os.path.join(self.path, 'meta.json')\n self.df = None\n\n exists = os.path.exists(self.path)\n\n if exists:\n #load log and meta\n print(\"Tub exists: {}\".format(self.path))\n with open(self.meta_path, 'r') as f:\n self.meta = json.load(f)\n self.current_ix = self.get_last_ix() + 1\n\n elif not exists and inputs:\n print('Tub does NOT exist. Creating new tub...')\n #create log and save meta\n os.makedirs(self.path)\n self.meta = {'inputs': inputs, 'types': types}\n with open(self.meta_path, 'w') as f:\n json.dump(self.meta, f)\n self.current_ix = 0\n print('New tub created at: {}'.format(self.path))\n else:\n msg = \"The tub path you provided doesn't exist and you didnt pass any meta info (inputs & types)\" + \\\n \"to create a new tub. Please check your tub path or provide meta info to create a new tub.\"\n\n raise AttributeError(msg)\n\n self.start_time = time.time()\n\n\n def get_last_ix(self):\n index = self.get_index()\n return max(index)\n\n def update_df(self):\n df = pd.DataFrame([self.get_json_record(i) for i in self.get_index(shuffled=False)])\n self.df = df\n\n def get_df(self):\n if self.df is None:\n self.update_df()\n return self.df\n\n\n def get_index(self, shuffled=True):\n files = next(os.walk(self.path))[2]\n record_files = [f for f in files if f[:6]=='record']\n \n def get_file_ix(file_name):\n try:\n name = file_name.split('.')[0]\n num = int(name.split('_')[1])\n except:\n num = 0\n return num\n\n nums = [get_file_ix(f) for f in record_files]\n \n if shuffled:\n random.shuffle(nums)\n else:\n nums = sorted(nums)\n \n return nums \n\n\n @property\n def inputs(self):\n return list(self.meta['inputs'])\n\n @property\n def types(self):\n return list(self.meta['types'])\n\n def get_input_type(self, key):\n input_types = dict(zip(self.inputs, self.types))\n return input_types.get(key)\n\n def write_json_record(self, json_data):\n path = self.get_json_record_path(self.current_ix)\n try:\n with open(path, 'w') as fp:\n json.dump(json_data, fp)\n #print('wrote record:', json_data)\n except TypeError:\n print('troubles with record:', json_data)\n except FileNotFoundError:\n raise\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n def get_num_records(self):\n import glob\n files = glob.glob(os.path.join(self.path, 'record_*.json'))\n return len(files)\n\n\n\n\n def make_record_paths_absolute(self, record_dict):\n #make paths absolute\n d = {}\n for k, v in record_dict.items():\n if type(v) == str: #filename\n if '.' in v:\n v = os.path.join(self.path, v)\n d[k] = v\n\n return d\n\n\n\n\n def check(self, fix=False):\n '''\n Iterate over all records and make sure we can load them.\n Optionally remove records that cause a problem.\n '''\n print('Checking tub:%s.' % self.path)\n print('Found: %d records.' % self.get_num_records())\n problems = False\n for ix in self.get_index(shuffled=False):\n try:\n self.get_record(ix)\n except:\n problems = True\n if fix == False:\n print('problems with record:', self.path, ix)\n else:\n print('problems with record, removing:', self.path, ix)\n self.remove_record(ix)\n if not problems:\n print(\"No problems found.\")\n\n def remove_record(self, ix):\n '''\n remove data associate with a record\n '''\n record = self.get_json_record_path(ix)\n os.unlink(record)\n\n def put_record(self, data):\n \"\"\"\n Save values like images that can't be saved in the csv log and\n return a record with references to the saved values that can\n be saved in a csv.\n \"\"\"\n json_data = {}\n self.current_ix += 1\n \n for key, val in data.items():\n typ = self.get_input_type(key)\n\n if typ in ['str', 'float', 'int', 'boolean']:\n json_data[key] = val\n\n elif typ is 'image':\n path = self.make_file_path(key)\n val.save(path)\n json_data[key]=path\n\n elif typ == 'image_array':\n img = Image.fromarray(np.uint8(val))\n name = self.make_file_name(key, ext='.jpg')\n img.save(os.path.join(self.path, name))\n json_data[key]=name\n\n else:\n msg = 'Tub does not know what to do with this type {}'.format(typ)\n raise TypeError(msg)\n\n self.write_json_record(json_data)\n return self.current_ix\n\n\n def get_json_record_path(self, ix):\n return os.path.join(self.path, 'record_'+str(ix)+'.json')\n\n def get_json_record(self, ix):\n path = self.get_json_record_path(ix)\n try:\n with open(path, 'r') as fp:\n json_data = json.load(fp)\n except UnicodeDecodeError:\n raise Exception('bad record: %d. You may want to run `python manage.py check --fix`' % ix)\n except FileNotFoundError:\n raise\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n record_dict = self.make_record_paths_absolute(json_data)\n return record_dict\n\n\n def get_record(self, ix):\n\n json_data = self.get_json_record(ix)\n data = self.read_record(json_data)\n return data\n\n\n\n def read_record(self, record_dict):\n data={}\n for key, val in record_dict.items():\n typ = self.get_input_type(key)\n\n #load objects that were saved as separate files\n if typ == 'image_array':\n img = Image.open((val))\n val = np.array(img)\n\n data[key] = val\n\n\n return data\n\n\n def make_file_name(self, key, ext='.png'):\n name = '_'.join([str(self.current_ix), key, ext])\n name = name = name.replace('/', '-')\n return name\n\n def delete(self):\n \"\"\" Delete the folder and files for this tub. \"\"\"\n import shutil\n shutil.rmtree(self.path)\n\n def shutdown(self):\n pass\n\n\n def get_record_gen(self, record_transform=None, shuffle=True, df=None):\n\n if df is None:\n df = self.get_df()\n\n\n while True:\n for row in self.df.iterrows():\n if shuffle:\n record_dict = df.sample(n=1).to_dict(orient='record')[0]\n\n if record_transform:\n record_dict = record_transform(record_dict)\n\n record_dict = self.read_record(record_dict)\n\n yield record_dict\n\n\n def get_batch_gen(self, keys, record_transform=None, batch_size=128, shuffle=True, df=None):\n\n record_gen = self.get_record_gen(record_transform, shuffle=shuffle, df=df)\n\n if keys == None:\n keys = list(self.df.columns)\n\n while True:\n record_list = []\n for _ in range(batch_size):\n record_list.append(next(record_gen))\n\n batch_arrays = {}\n for i, k in enumerate(keys):\n arr = np.array([r[k] for r in record_list])\n # if len(arr.shape) == 1:\n # arr = arr.reshape(arr.shape + (1,))\n batch_arrays[k] = arr\n\n yield batch_arrays\n\n\n def get_train_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, df=None):\n\n batch_gen = self.get_batch_gen(X_keys + Y_keys,\n batch_size=batch_size, record_transform=record_transform, df=df)\n\n while True:\n batch = next(batch_gen)\n X = [batch[k] for k in X_keys]\n Y = [batch[k] for k in Y_keys]\n yield X, Y\n\n\n def get_train_val_gen(self, X_keys, Y_keys, batch_size=128, record_transform=None, train_frac=.8):\n train_df = train=self.df.sample(frac=train_frac,random_state=200)\n val_df = self.df.drop(train_df.index)\n\n train_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size,\n record_transform=record_transform, df=train_df)\n\n val_gen = self.get_train_gen(X_keys=X_keys, Y_keys=Y_keys, batch_size=batch_size,\n record_transform=record_transform, df=val_df)\n\n return train_gen, val_gen\n\n\n\n\n\nclass TubWriter(Tub):\n def __init__(self, *args, **kwargs):\n super(TubWriter, self).__init__(*args, **kwargs)\n\n def run(self, *args):\n '''\n API function needed to use as a Donkey part.\n\n Accepts values, pairs them with their inputs keys and saves them\n to disk.\n '''\n assert len(self.inputs) == len(args)\n\n self.record_time = int(time.time() - self.start_time)\n record = dict(zip(self.inputs, args))\n self.put_record(record)\n\ndef customCallback(client, userdata, message):\n print(\"Received a new message\")\n print(message.payload)\n print(\"From Topic:\")\n print(message.topic)\n print(\"--------------------\\n\\n\")\n\nclass IotPush(Tub):\n def __init__(self, inputs=None, types=None):\n self.client = self.connect()\n self.meta = {'inputs': inputs, 'types': types}\n self.start_time = time.time()\n self.current_ix = 1\n\n def update(self):\n time.sleep(1)\n\n def put_record(self, data):\n \"\"\"\n Save values like images that can't be saved in the csv log and\n return a record with references to the saved values that can\n be saved in a csv.\n \"\"\"\n json_data = {}\n self.current_ix += 1\n\n for key, val in data.items():\n typ = self.get_input_type(key)\n\n if typ in ['str', 'float', 'int', 'boolean']:\n json_data[key] = val\n\n elif typ is 'image':\n pass\n\n elif typ == 'image_array':\n pass\n\n else:\n msg = 'Tub does not know what to do with this type {}'.format(typ)\n raise TypeError(msg)\n\n self.write_json_record(json_data)\n return self.current_ix\n\t\n\n def connect(self):\n\n base_path = \"/opt/devicesdk\"\n rootCAPath = os.path.join(base_path, \"root-CA.crt\")\n privateKeyPath = os.path.join(base_path, \"donkeyng.private.key\")\n certificatePath = os.path.join(base_path, \"donkeyng.cert.pem\")\n topic = \"AutonomousVehicles\"\n clientId = \"BasicPubSub\"\n host = \"a3u210mv68xw24.iot.us-east-1.amazonaws.com\"\n\n #print (rootCAPath, privateKeyPath, certificatePath)\n\n # Init AWSIoTMQTTClient\n useWebsocket = False\n myAWSIoTMQTTClient = None\n if useWebsocket:\n myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)\n myAWSIoTMQTTClient.configureEndpoint(host, 443)\n myAWSIoTMQTTClient.configureCredentials(rootCAPath)\n else:\n myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)\n myAWSIoTMQTTClient.configureEndpoint(host, 8883)\n myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)\n\n # AWSIoTMQTTClient connection configuration\n myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)\n myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publ$\n myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz\n myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec\n myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec\n\n # Connect and subscribe to AWS IoT\n myAWSIoTMQTTClient.connect()\n myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)\n time.sleep(2)\n\n return myAWSIoTMQTTClient\n\n def run_threaded(self, *args):\n assert len(self.inputs) == len(args)\n \n self.record_time = int(time.time() - self.start_time)\n record = dict(zip(self.inputs, args))\n self.put_record(record)\n #time.sleep(1)\n \n def write_json_record(self, json_data):\n topic = \"AutonomousVehicles\"\n self.client.publish(topic, json.dumps(json_data), 1)\n\nif __name__==\"__main__\":\n \n inputs = [10, 20, \"A string\"]\n types = ['int', 'int', 'str']\n iot = IotPush(inputs=inputs, types=types)\n topic = \"AutonomousVehicles\"\n for i in range (0,10):\n iot.run_threaded()\n time.sleep(1)\n","sub_path":"donkeycar/parts/iot.py","file_name":"iot.py","file_ext":"py","file_size_in_byte":13928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"466148668","text":"# Get information about the process's memory usage.\nimport resource, os\n\ndef current():\n\twith open(\"/proc/self/statm\",\"r\") as f:\n\t\treturn int(f.readline().split()[0])*resource.getpagesize()\n\ndef resident():\n\twith open(\"/proc/self/status\",\"r\") as f:\n\t\tfor line in f:\n\t\t\ttoks = line.split()\n\t\t\tif toks[0] == \"VmRSS:\":\n\t\t\t\treturn int(toks[1])*1024\n\ndef max():\n\twith open(\"/proc/self/status\",\"r\") as f:\n\t\tfor line in f:\n\t\t\ttoks = line.split()\n\t\t\tif toks[0] == \"VmPeak:\":\n\t\t\t\treturn int(toks[1])*1024\n","sub_path":"memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"606175965","text":"from setuptools import setup, find_packages\n\nwith open('README.md', 'r') as f:\n long_description = f.read()\n\nsetup(\n author='Chavithra PARANA',\n author_email='chavithra@gmail.com',\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n ],\n entry_points={\n 'console_scripts': [\n 'quotecast = quotecast.applications.cli:cli',\n 'trading = trading.applications.cli:cli',\n ],\n },\n extras_require={\n 'tests': [\n 'pytest',\n ],\n 'lint': [\n 'flake8',\n ],\n },\n install_requires=[\n 'grpcio',\n 'onetimepass',\n 'orjson',\n 'pandas',\n 'protobuf',\n 'requests',\n 'wheel',\n 'wrapt',\n ],\n long_description=long_description,\n long_description_content_type='text/markdown',\n name='degiro-connector',\n packages=find_packages(),\n python_requires='>=3.6',\n url='https://github.com/chavithra/degiro-connector',\n version='0.0.9',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"642864181","text":"from django.db import models\nfrom django.core.validators import RegexValidator\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\nfrom ...cabila.models.baseUser import BaseProfile\nfrom ...vagas.models.adresse import Adresse\n\nimport datetime\n#import pytz\n#apps imports\n#from apps.vagas.models import Adresse\n\n# Create your models here.\n\nclass EmpresaProfile(models.Model):\n \"\"\" Dados inicias para registro de empresa, rest a ser preenchido no perfil\"\"\"\n user = models.OneToOneField(BaseProfile)\n alias = models.CharField(_(\"Nome\"),max_length=15, default=\"nenhum\",null=True, blank=True)\n show_alias = models.BooleanField(_(\"Monstrar nome\"), default=False)\n cnpj = models.CharField(RegexValidator(regex=\"\\d{2}\\.\\d{3}\\.\\d{3}\\/\\d{4}\\-\\d{2}\", message=\"telefone invalido\"), max_length=20)\n telefone = models.CharField(RegexValidator(regex = \"\\([1-9]{2}\\)\\-[0-9]{4,5}\\-[0-9]{4}|\\([1-9]{2}\\)[0-9]{4,5}\\-[0-9]{4}|\\([1-9]{2}\\)[0-9]{4,5}[0-9]{4}\",message=\"telefone invalido\"),max_length=15,null=True, blank=True)\n agent = models.CharField(max_length=15, default=\"nenhum\",null=True, blank=True)\n\n def __str__(self):\n return self.alias\n\nclass EmpresaDados(models.Model):\n porte = (\n (\"Pequena\",\"Pequena\"),\n (\"Media\",\"Media\"),\n (\"Grande\",\"Grande\"),\n (\"Internacional\",\"Multi-nacioanal\"),\n (\"Micro-empresa\",\"Micro-empresa\")\n )\n r_social = models.CharField(_(\"Razão social\"), max_length=15,null=True, blank=True)\n description = models.TextField(_(\"Atividades da empresa\"), null=True, blank=True)\n porte_empresa = models.CharField(_(\"Porte da empresa\"), max_length=15, choices=porte, null=True, blank=True)\n vagas_anuais = models.PositiveIntegerField(_(\"Vagas anuais\"), default=1)\n adresse = models.OneToOneField(Adresse, null=True, blank=True)\n #logo\n\n class Meta:\n verbose_name = \"Detalhe da empresa\"\n\nclass Empresa(models.Model):\n user = models.OneToOneField(BaseProfile)\n is_empresa = models.BooleanField(_(\"é empresa\"), default=True)\n profile = models.OneToOneField(EmpresaProfile, null=True, blank=True)\n dados = models.OneToOneField(EmpresaDados, null=True, blank=True)\n created = models.DateField(_(\"criado no\"), auto_now_add=True)\n\n def __str__(self):\n return self.profile.alias\n class Meta:\n verbose_name = \"Empresa\"\n verbose_name_plural = \"Empresas\"\n\n","sub_path":"apps/azohoue/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"418242690","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 19 09:08:18 2019\r\n\r\n@author: MB87511\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom random import random\r\nimport pandas as pd\r\n\r\n\r\nclass K_means(object):\r\n \r\n def __init__(self, n_clusters = 3, max_iter = 300):\r\n self.n_clusters = n_clusters \r\n self.max_iter = max_iter\r\n \r\n def fit(self, data):\r\n \r\n self.centroids = data[np.random.permutation(data.shape[0])[:self.n_clusters]]\r\n for i in range(self.max_iter):\r\n self.labels = [self.closest_cluster(self.centroids, point) for point in data]\r\n\r\n old_centroids = np.array(self.centroids)\r\n for k in range(self.n_clusters):\r\n idxs = [idx for idx, label in enumerate(self.labels) if label == k]\r\n points_in_cluster = data[idxs]\r\n self.centroids[k] = points_in_cluster.sum(axis=0) / len(points_in_cluster)\r\n\r\n self.sum_of_errors = sum(((self.centroids[label] - point)**2).sum() for point, label in zip(X, self.labels))\r\n \r\n if(np.array_equal(self.centroids, old_centroids)):\r\n return self\r\n \r\n return self\r\n \r\n def euclid_dist(self, a, b):\r\n return np.sqrt(((a-b)**2).sum())\r\n \r\n def closest_cluster(self, centroids, points):\r\n return np.argmin([self.euclid_dist(points, centroid) for centroid in centroids])\r\n \r\n def predict(self, data):\r\n return self.labels\r\n \r\n def fit_predict(self, data):\r\n return self.fit(data).predict(data)\r\n \r\n def get_centroids(self):\r\n return self.centroids\r\n \r\n def get_sum_of_errors(self):\r\n return self.sum_of_errors\r\n\r\n\r\n#### Method that returns best number of clusters for the data\r\ndef get_best_k(errors_sum_list):\r\n diffs = []\r\n for i in range(1,len(errors_sum_list)):\r\n diff = (errors_sum_list[i-1]-errors_sum_list[i])/errors_sum_list[i-1]\r\n diffs.append(diff)\r\n threshold = 0.2 \r\n best_k = [idx+1 for idx, diff in enumerate(diffs) if diff <= threshold][0]\r\n pd.DataFrame(errors_sum_list, index = range(1,10)).plot(title = 'Elbow Rule to determine best number of clusters, below threshold: ' +str(threshold))\r\n return best_k \r\n\r\n### Method to return labels of clusters for each datapoint and cluster's centroids for best_k kmean model\r\ndef best_kMeans_results(X, errors_sum_list, kmean_clusters):\r\n best_k = get_best_k(errors_sum_list)\r\n return best_k, pd.DataFrame(X).join(pd.Series(kmean_clusters['#clusters:'+str(best_k)].predict(X)).rename('Labels')), kmean_clusters['#clusters:'+str(best_k)].get_centroids()\r\n \r\n\r\ndef run_k_means(X):\r\n #### Generate different kmeans models and listing each sum of squared errors <<< MAIN >>> \r\n errors_sum_list = []\r\n kmean_clusters = {}\r\n for i in range(1,10):\r\n model = K_means(n_clusters=i)\r\n model.fit(X)\r\n kmean_clusters['#clusters:'+str(i)] = model\r\n error = model.get_sum_of_errors()\r\n errors_sum_list.append(error)\r\n \r\n best_number_clusters, labels, centroids = best_kMeans_results(X, errors_sum_list, kmean_clusters)\r\n \r\n print('Best_number of clusters', best_number_clusters)\r\n print\r\n print('Labels for datapoints')\r\n print(labels)\r\n print \r\n print('Centroids of clusters')\r\n print(centroids)\r\n\r\n### Test case for any X-array\r\n### Init 100-lenght random array of points\r\nX= np.array([[random()*100, random()*100] for x in range(100)])\r\nrun_k_means(X)\r\n","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"197969904","text":"\nimport unittest\nimport torch\n\nimport neuralprocess as npr\n\n\nclass TestKLDivergence(unittest.TestCase):\n\n def test_kl_batch(self):\n batch = 10\n x_dim = 5\n\n mu0 = torch.randn(batch, x_dim)\n var0 = torch.rand(batch, x_dim) + 0.01\n mu1 = torch.randn(batch, x_dim)\n var1 = torch.rand(batch, x_dim) + 0.01\n\n kl = npr.kl_divergence_normal(mu0, var0, mu1, var1)\n self.assertTupleEqual(kl.size(), (batch,))\n self.assertTrue((kl >= 0).all())\n\n def test_kl_batch_num(self):\n batch = 10\n num_points = 8\n x_dim = 5\n\n mu0 = torch.randn(batch, num_points, x_dim)\n var0 = torch.rand(batch, num_points, x_dim) + 0.01\n mu1 = torch.randn(batch, num_points, x_dim)\n var1 = torch.rand(batch, num_points, x_dim) + 0.01\n\n kl = npr.kl_divergence_normal(mu0, var0, mu1, var1)\n self.assertTupleEqual(kl.size(), (batch, num_points))\n self.assertTrue((kl >= 0).all())\n\n def test_kl_same(self):\n batch = 10\n x_dim = 5\n\n mu0 = torch.randn(batch, x_dim)\n var0 = torch.rand(batch, x_dim) + 0.01\n\n kl = npr.kl_divergence_normal(mu0, var0, mu0, var0)\n self.assertTupleEqual(kl.size(), (batch,))\n self.assertTrue((kl == 0).all())\n\n def test_nll_normal(self):\n batch = 10\n x_dim = 5\n\n mu = torch.randn(batch, x_dim)\n var = torch.rand(batch, x_dim) + 0.01\n x = torch.randn(batch, x_dim)\n\n nll = npr.nll_normal(x, mu, var)\n self.assertTupleEqual(nll.size(), (batch,))\n self.assertTrue((nll >= 0).all())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_base_np.py","file_name":"test_base_np.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"398145651","text":"import requests\nfrom dateutil import parser\nimport sys\n\nCI_SERVER_URL=sys.argv[1]\nGITLAB_TOKEN=sys.argv[2]\nCI_PROJECT_ID=sys.argv[3]\nGITLAB_REGISTRY_ID=sys.argv[4]\n\n\ndef get_available_registry_tags():\n registry_tags = requests.get(f'{CI_SERVER_URL}/api/v4/projects/{CI_PROJECT_ID}/registry/repositories/{GITLAB_REGISTRY_ID}/tags',\n headers={\"PRIVATE-TOKEN\":GITLAB_TOKEN})\n return registry_tags.json()\n\ndef populate_registry_tags():\n registry_tags = get_available_registry_tags()\n populated_tags = []\n for tag in registry_tags:\n populated_tag_resp = requests.get('{}/api/v4/projects/{}/registry/repositories/{}/tags/{}'.format(CI_SERVER_URL,CI_PROJECT_ID,GITLAB_REGISTRY_ID,tag['name']),\n headers={\"PRIVATE-TOKEN\":GITLAB_TOKEN})\n populated_tag = populated_tag_resp.json()\n populated_tag['created_at'] = parser.parse(populated_tag['created_at'])\n populated_tags.append(populated_tag)\n return populated_tags\n\n\ndef sorted_registry_tags():\n tagss = populate_registry_tags()\n tagss.sort(key = lambda x:x['created_at'],reverse=True)\n return [t[\"name\"] for t in tagss]\n\n\n\ndef delete_more_than_5_tags():\n registry_tagnames = sorted_registry_tags()\n for i in range(len(registry_tagnames)):\n if(i>4):\n print(\"[INFO] Delete registry tag {}\".format(registry_tagnames[i]))\n requests.delete('{}/api/v4/projects/{}/registry/repositories/{}/tags/{}'.format(CI_SERVER_URL,CI_PROJECT_ID,GITLAB_REGISTRY_ID,registry_tagnames[i]),\n headers={\"PRIVATE-TOKEN\":GITLAB_TOKEN})\n\n\ndelete_more_than_5_tags()","sub_path":"ci/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"237055276","text":"import socket\nimport threading\n\nudpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\nrecieveAddr = (\"192.168.31.223\", 9999)\nudpSocket.bind(recieveAddr)\n\n\ndef recieve():\n recieveData = udpSocket.recvfrom(1024)\n print(recieveData[0])\n\n\ndef send():\n msg = input(\"\")\n print(\" \"+msg)\n sendToAddr = (\"192.168.31.223\",8888)\n udpSocket.sendto(msg.encode(\"utf-8\"),sendToAddr)\n\nwhile True:\n recieve()\n send()\n","sub_path":"ChatRoom2.py","file_name":"ChatRoom2.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"528463709","text":"from dateutil.parser import parse\nfrom dateutil.relativedelta import relativedelta\nfrom django.utils.timezone import now\nfrom rest_framework import status\n\nfrom posthog.models import Person, SessionRecordingEvent\nfrom posthog.models.session_recording_event import SessionRecordingViewed\nfrom posthog.models.team import Team\nfrom posthog.test.base import APIBaseTest\n\n\ndef factory_test_session_recordings_api(session_recording_event_factory):\n class TestSessionRecordings(APIBaseTest):\n def create_snapshot(self, distinct_id, session_id, timestamp, type=2, team_id=None):\n if team_id == None:\n team_id = self.team.pk\n session_recording_event_factory(\n team_id=team_id,\n distinct_id=distinct_id,\n timestamp=timestamp,\n session_id=session_id,\n snapshot_data={\"timestamp\": timestamp.timestamp(), \"type\": type},\n )\n\n def test_get_session_recordings(self):\n Person.objects.create(\n team=self.team, distinct_ids=[\"user\"], properties={\"$some_prop\": \"something\", \"email\": \"bob@bob.com\"},\n )\n base_time = now()\n self.create_snapshot(\"user\", \"1\", base_time)\n self.create_snapshot(\"user\", \"1\", base_time + relativedelta(seconds=10))\n self.create_snapshot(\"user2\", \"2\", base_time + relativedelta(seconds=20))\n self.create_snapshot(\"user\", \"1\", base_time + relativedelta(seconds=30))\n\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n response_data = response.json()\n self.assertEqual(len(response_data[\"results\"]), 2)\n first_session = response_data[\"results\"][0]\n second_session = response_data[\"results\"][1]\n\n self.assertEqual(first_session[\"id\"], \"2\")\n self.assertEqual(first_session[\"distinct_id\"], \"user2\")\n self.assertEqual(parse(first_session[\"start_time\"]), (base_time + relativedelta(seconds=20)))\n self.assertEqual(parse(first_session[\"end_time\"]), (base_time + relativedelta(seconds=20)))\n self.assertEqual(first_session[\"recording_duration\"], \"0.0\")\n self.assertEqual(first_session[\"viewed\"], False)\n self.assertEqual(first_session[\"email\"], None)\n\n self.assertEqual(second_session[\"id\"], \"1\")\n self.assertEqual(second_session[\"distinct_id\"], \"user\")\n self.assertEqual(parse(second_session[\"start_time\"]), (base_time))\n self.assertEqual(parse(second_session[\"end_time\"]), (base_time + relativedelta(seconds=30)))\n self.assertEqual(second_session[\"recording_duration\"], \"30.0\")\n self.assertEqual(second_session[\"viewed\"], False)\n self.assertEqual(second_session[\"email\"], \"bob@bob.com\")\n\n def test_session_recordings_dont_leak_teams(self):\n another_team = Team.objects.create(organization=self.organization)\n\n self.create_snapshot(\"user\", \"1\", now(), team_id=another_team.pk)\n self.create_snapshot(\"user\", \"2\", now())\n\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n response_data = response.json()\n self.assertEqual(len(response_data[\"results\"]), 1)\n self.assertEqual(response_data[\"results\"][0][\"id\"], \"2\")\n\n def test_session_recording_for_user_with_multiple_distinct_ids(self):\n Person.objects.create(\n team=self.team,\n distinct_ids=[\"d1\", \"d2\"],\n properties={\"$some_prop\": \"something\", \"email\": \"bob@bob.com\"},\n )\n self.create_snapshot(\"d1\", \"1\", now())\n self.create_snapshot(\"d2\", \"2\", now() + relativedelta(seconds=30))\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n response_data = response.json()\n self.assertEqual(len(response_data[\"results\"]), 2)\n self.assertEqual(response_data[\"results\"][0][\"email\"], \"bob@bob.com\")\n self.assertEqual(response_data[\"results\"][1][\"email\"], \"bob@bob.com\")\n\n def test_viewed_state_of_session_recording(self):\n SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id=\"1\")\n self.create_snapshot(\"u1\", \"1\", now())\n self.create_snapshot(\"u1\", \"2\", now() + relativedelta(seconds=30))\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n response_data = response.json()\n self.assertEqual(len(response_data[\"results\"]), 2)\n self.assertEqual(response_data[\"results\"][0][\"id\"], \"2\")\n self.assertEqual(response_data[\"results\"][0][\"viewed\"], False)\n self.assertEqual(response_data[\"results\"][1][\"id\"], \"1\")\n self.assertEqual(response_data[\"results\"][1][\"viewed\"], True)\n\n def test_get_single_session_recording(self):\n p = Person.objects.create(\n team=self.team, distinct_ids=[\"d1\"], properties={\"$some_prop\": \"something\", \"email\": \"bob@bob.com\"},\n )\n base_time = now()\n self.create_snapshot(\"d1\", \"1\", base_time)\n self.create_snapshot(\"d1\", \"1\", base_time + relativedelta(seconds=30))\n response = self.client.get(\"/api/projects/@current/session_recordings/1\")\n response_data = response.json()\n self.assertEqual(response_data[\"result\"][\"snapshots\"][0], {\"timestamp\": base_time.timestamp(), \"type\": 2})\n self.assertEqual(\n response_data[\"result\"][\"snapshots\"][1],\n {\"timestamp\": (base_time + relativedelta(seconds=30)).timestamp(), \"type\": 2},\n )\n self.assertEqual(response_data[\"result\"][\"person\"][\"id\"], p.pk)\n self.assertEqual(parse(response_data[\"result\"][\"start_time\"]), base_time)\n\n def test_single_session_recording_doesnt_leak_teams(self):\n another_team = Team.objects.create(organization=self.organization)\n self.create_snapshot(\"user\", \"1\", now(), team_id=another_team.pk)\n response = self.client.get(\"/api/projects/@current/session_recordings/1\")\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_session_recording_with_no_person(self):\n self.create_snapshot(\"d1\", \"1\", now())\n response = self.client.get(\"/api/projects/@current/session_recordings/1\")\n response_data = response.json()\n self.assertEqual(response_data[\"result\"][\"person\"], None)\n\n def test_session_recording_doesnt_exist(self):\n response = self.client.get(\"/api/projects/@current/session_recordings/1\")\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_setting_viewed_state_of_session_recording(self):\n self.create_snapshot(\"u1\", \"1\", now())\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n response_data = response.json()\n # Make sure it starts not viewed\n self.assertEqual(response_data[\"results\"][0][\"viewed\"], False)\n\n response = self.client.get(\"/api/projects/@current/session_recordings/1\")\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n response_data = response.json()\n # Make sure it remains not viewed\n self.assertEqual(response_data[\"results\"][0][\"viewed\"], False)\n\n response = self.client.get(\"/api/projects/@current/session_recordings/1?save_view=True\")\n response = self.client.get(\"/api/projects/@current/session_recordings\")\n response_data = response.json()\n # Make sure the query param sets it to viewed\n self.assertEqual(response_data[\"results\"][0][\"viewed\"], True)\n\n return TestSessionRecordings\n\n\nclass TestSessionRecordingsAPI(factory_test_session_recordings_api(SessionRecordingEvent.objects.create)): # type: ignore\n pass\n","sub_path":"posthog/api/test/test_session_recordings.py","file_name":"test_session_recordings.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"170622978","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nfrom os.path import exists, isdir\nfrom fabric.api import *\n\nVMT_ETC = os.getenv('VMT_ETC')\n\nVimBundles = {\n 'bufexplorer': {\n 'version' : '7.2.8',\n 'url' : 'https://github.com/vim-scripts/bufexplorer.zip.git',\n 'type' : 'git'\n }\n}\n\npjoin = os.path.join\n\ndef etcpath(*s):\n return os.path.join(VMT_ETC, *s)\n\ndef setup_paths():\n with cd(etcpath('local')):\n local(\"mkdir -p vim/runtime/bundle\")\n\ndef setup_vim():\n runtime_dir = etcpath('local/vim/runtime')\n for name, spec in VimBundles.iteritems():\n bundle_dir = pjoin(runtime_dir, \"bundle\", \n \"%s-%s\" % (name, spec['version']))\n if exists(bundle_dir):\n warn(\"%s is already setup\" % bundle_dir)\n continue\n if spec['type'] == 'git':\n with cd(os.path.basename(bundle_dir)):\n local('git clone %s %s' % (spec['url'], bundle_dir))\n else:\n warn(\"Unknown bundle source type: %s\" % spec['type'])\n\ndef setup():\n setup_paths()\n setup_vim()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"222914009","text":"from database.data.user import User\nfrom database.data.event import Event\nfrom database.data.cluster import Cluster\n\n\ndef create_new_user(name, email, password, age, educ, major, preferences, weight_sum):\n usr = User()\n\n usr.name = name\n usr.email = email\n usr.password = password\n usr.age = age\n usr.educ = educ\n usr.major = major\n usr.preferences = preferences\n usr.weight_sum = weight_sum\n\n usr.save()\n return usr\n\n\ndef create_multiple_users(user_document_list):\n usrs = User.objects().insert(user_document_list)\n return usrs\n\n\ndef get_user_info(email, password):\n usr = User.objects().filter(email=email, password=password).first()\n return usr\n\ndef get_user_pref(email):\n pref = User.objects().filter(email=email).first()\n return pref\n\n\ndef insert_events(event_document_list):\n ret = Event.objects().insert(event_document_list)\n return ret\n\n\ndef get_all_event_data():\n events = Event.objects().filter()\n\n # TODO: Remove\n # events = Event.objects(image_url__ne=\"gatech_logo.png\")\n return events\n\n\ndef get_events_by_clusters(cluster=0):\n events = Event.objects().filter(cluster_number=cluster)\n return events\n\n\ndef get_event_by_id(event_id):\n event = Event.objects().filter(pk=event_id).first()\n return event\n\ndef get_unique_descriptions():\n events = Event.objects.distinct('description')\n return events\n\n\ndef get_cluster_counts(cluster=0):\n cluster_count = Event.objects(cluster_number=cluster).count()\n return cluster_count\n\n\ndef create_new_cluster(number, name, event_count):\n clsrt = Cluster()\n clsrt.number = number\n clsrt.name = name\n clsrt.event_count = event_count\n\n clsrt.save()\n return clsrt\n\n\ndef get_all_clusters():\n clstrs = Cluster.objects().filter()\n return clstrs\n\n\n\ndef get_event_by_cluster_limit(cluster=0, limit=10):\n events = Event.objects.filter(cluster_number=cluster).aggregate(\n {'$group': {'originalId': {'$first': '$_id'},\n '_id': '$title',\n 'description': {'$first': '$description'},\n 'category': {'$first': '$category'},\n 'location': {'$first': '$location'},\n 'image_url': {'$first': '$image_url'},\n 'related_link': {'$first': '$related_link'},\n 'st_date': {'$first': '$st_date'},\n 'end_date': {'$first': '$end_date'},\n 'st_time': {'$first': '$st_time'},\n 'cluster_number': {'$first': '$cluster_number'},\n }\n },\n {'$project': {'_id': '$originalId',\n 'title': \"$_id\",\n 'description': '$description',\n 'category': '$category',\n 'location': '$location',\n 'image_url': '$image_url',\n 'related_link': '$related_link',\n 'st_date': '$st_date',\n 'end_date': '$end_date',\n 'st_time': '$st_time',\n 'cluster_number': '$cluster_number',\n }\n },\n {'$limit': limit}\n )\n return events\n\n\ndef update_user_preference(email, cluster='0'):\n field = 'inc__preferences__' + cluster\n uptd = User.objects(email=email).update(**{field: 1})\n uptd_weight = User.objects(email=email).update(inc__weight_sum=1)\n return uptd\n\ndef update_cluster_names(cluster_number=0, name='Festivals'):\n uptd = Cluster.objects(number=cluster_number).update(set__name=name)\n return uptd\n\n","sub_path":"public/database/services/data_service.py","file_name":"data_service.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"249587067","text":"import tensorflow as tf\nimport tensorflow.keras as ks\nfrom tensorflow.keras import backend as K\nimport tensorflow_datasets as tfds\nfrom yolo.modeling.yolo_v3 import Yolov3\nfrom yolo.modeling.functions.iou import *\n\n\nclass Yolo_Loss(ks.losses.Loss):\n def __init__(self, \n mask, \n anchors, \n scale_anchors = 1, \n num_extras = 0, \n ignore_thresh = 0.7, \n truth_thresh = 1, \n loss_type = \"mse\", \n iou_normalizer = 1.0,\n cls_normalizer = 1.0, \n scale_x_y = 1.0,\n nms_kind = \"greedynms\",\n beta_nms = 0.6,\n reduction = tf.keras.losses.Reduction.AUTO, \n name=None, \n dtype = tf.float32,\n **kwargs):\n\n \"\"\"\n parameters for the loss functions used at each detection head output\n\n Args: \n mask: list of indexes for which anchors in the anchors list should be used in prediction\n anchors: list of tuples (w, h) representing the anchor boxes to be used in prediction \n num_extras: number of indexes predicted in addition to 4 for the box and N + 1 for classes \n ignore_thresh: float for the threshold for if iou > threshold the network has made a prediction, \n and should not be penealized for p(object) prediction if an object exists at this location\n truth_thresh: float thresholding the groud truth to get the true mask \n loss_type: string for the key of the loss to use, \n options -> mse, giou, ciou\n iou_normalizer: float used for appropriatly scaling the iou or the loss used for the box prediction error \n cls_normalizer: float used for appropriatly scaling the classification error\n scale_x_y: float used to scale the predictied x and y outputs\n nms_kind: string used for filtering the output and ensuring each object ahs only one prediction\n beta_nms: float for the thresholding value to apply in non max supression(nms) -> not yet implemented\n\n call Return: \n float: for the average loss \n \"\"\"\n super(Yolo_Loss, self).__init__(reduction = reduction, name = name, **kwargs)\n self.dtype = dtype\n self._anchors = tf.convert_to_tensor([anchors[i] for i in mask], dtype= self.dtype)/scale_anchors #<- division done for testing\n\n self._num = tf.cast(len(mask), dtype = tf.int32)\n self._num_extras = tf.cast(num_extras, dtype = self.dtype)\n self._truth_thresh = tf.cast(truth_thresh, dtype = self.dtype) \n self._ignore_thresh = tf.cast(ignore_thresh, dtype = self.dtype)\n\n # used (mask_n >= 0 && n != best_n && l.iou_thresh < 1.0f) for id n != nest_n\n # checks all anchors to see if another anchor was used on this ground truth box to make a prediction\n # if iou > self._iou_thresh then the network check the other anchors, so basically \n # checking anchor box 1 on prediction for anchor box 2\n self._iou_thresh = tf.cast(0.213, dtype = self.dtype) # recomended use = 0.213 in [yolo]\n \n self._loss_type = loss_type\n self._iou_normalizer= tf.cast(iou_normalizer, dtype = self.dtype)\n self._cls_normalizer = tf.cast(cls_normalizer, dtype = self.dtype)\n self._scale_x_y = tf.cast(scale_x_y, dtype = self.dtype)\n\n #used in detection filtering\n self._beta_nms = tf.cast(beta_nms, dtype = self.dtype)\n self._nms_kind = nms_kind\n return\n\n @tf.function\n def _get_centers(self, lwidth, lheight, batch_size):\n \"\"\" generate a grid that is used to detemine the relative centers of the bounding boxs \"\"\"\n x_left, y_left = tf.meshgrid(tf.range(0, lheight), tf.range(0, lwidth))\n x_y = K.stack([x_left, y_left], axis = -1)\n x_y = tf.cast(x_y, dtype = self.dtype)/tf.cast(lwidth, dtype = self.dtype)\n x_y = tf.repeat(tf.expand_dims(tf.repeat(tf.expand_dims(x_y, axis = -2), self._num, axis = -2), axis = 0), batch_size, axis = 0)\n return x_y\n \n @tf.function\n def _get_anchor_grid(self, width, height, batch_size):\n \"\"\" get the transformed anchor boxes for each dimention \"\"\"\n anchors = tf.cast(self._anchors, dtype = self.dtype)\n anchors = tf.reshape(anchors, [1, -1])\n anchors = tf.repeat(anchors, width*height, axis = 0)\n anchors = tf.reshape(anchors, [1, width, height, self._num, -1])\n anchors = tf.repeat(anchors, batch_size, axis = 0)\n return anchors\n\n @tf.function\n def print_error(self, pred_conf):\n if tf.reduce_any(tf.math.is_nan(pred_conf)) == tf.convert_to_tensor([True]):\n tf.print(\"\\nerror\")\n\n def call(self, y_true, y_pred):\n #1. generate and store constants and format output\n batch_size = tf.cast(tf.shape(y_pred)[0], dtype = tf.int32)\n width = tf.cast(tf.shape(y_pred)[1], dtype = tf.int32)\n height = tf.cast(tf.shape(y_pred)[2], dtype = tf.int32)\n grid_points = self._get_centers(width, height, batch_size)\n anchor_grid = self._get_anchor_grid(width, height, batch_size)\n\n y_pred = tf.reshape(y_pred, [batch_size, width, height, self._num, -1])\n y_pred = tf.cast(y_pred, dtype = self.dtype)\n\n fwidth = tf.cast(width, self.dtype)\n fheight = tf.cast(height, self.dtype)\n\n #2. split up layer output into components, xy, wh, confidence, class -> then apply activations to the correct items\n pred_xy = tf.math.sigmoid(y_pred[..., 0:2]) * self._scale_x_y - 0.5 * (self._scale_x_y - 1)\n pred_wh = y_pred[..., 2:4]\n pred_conf = tf.expand_dims(tf.math.sigmoid(y_pred[..., 4]), axis = -1)\n pred_class = tf.math.sigmoid(y_pred[..., 5:])\n self.print_error(pred_conf)\n\n #3. split up ground_truth into components, xy, wh, confidence, class -> apply calculations to acchive safe format as predictions\n true_xy = tf.nn.relu(y_true[..., 0:2] - grid_points)\n true_xy = K.concatenate([K.expand_dims(true_xy[..., 0] * fwidth, axis = -1), K.expand_dims(true_xy[..., 1] * fheight, axis = -1)], axis = -1)\n true_wh = tf.math.log(tf.math.divide_no_nan(y_true[..., 2:4],(anchor_grid + 1.0e-16)))\n #graph profiler cant optimize these tf.where statments you get NHWCtoNCWH failed or some thing\n true_conf = y_true[..., 4]\n true_class = y_true[..., 5:]\n\n #4. use iou to calculate the mask of where the network belived there to be an object -> used to penelaize the network for wrong predictions\n box_xy = pred_xy[..., 0:2]/fwidth + grid_points\n box_wh = tf.math.exp(pred_wh) * anchor_grid\n pred_box = K.concatenate([box_xy, box_wh], axis = -1) \n true_box = y_true[..., 0:4]\n iou = box_iou(true_box, pred_box, dtype = self.dtype) \n #graph profiler cant optimize these tf.where statments you get NHWCtoNCWH failed or some thing \n #iou = tf.where(tf.math.is_nan(iou), zeros[..., 0], iou)\n #iou = tf.where(tf.math.is_inf(iou), zeros[..., 0], iou)\n mask_iou = tf.cast(iou < self._ignore_thresh, dtype = self.dtype)\n\n #5. apply generalized IOU or mse to the box predictions -> only the indexes where an object exists will affect the total loss -> found via the true_confidnce in ground truth \n if self._loss_type == \"mse\":\n #yolo_layer.c: scale = (2-truth.w*truth.h)\n #error exists here\n scale = (2 - true_box[...,2] * true_box[...,3]) * self._iou_normalizer \n loss_xy = tf.reduce_sum(K.square(true_xy - pred_xy), axis = -1)\n loss_wh = tf.reduce_sum(K.square(true_wh - pred_wh), axis = -1)\n loss_box = (loss_wh + loss_xy) * true_conf * scale \n else:\n giou_loss = giou(true_box, pred_box, dtype = self.dtype)\n #graph profiler cant optimize these tf.where statments you get NHWCtoNCWH failed or some thing, i think because of the loss being a tesnor and 0 being a value?\n #giou_loss = tf.where(tf.math.is_nan(giou_loss), zeros[..., 0], giou_loss)\n #giou_loss = tf.where(tf.math.is_inf(giou_loss), zeros[..., 0], giou_loss)\n loss_box = (1 - giou_loss) * self._iou_normalizer * true_conf\n\n #6. apply binary cross entropy(bce) to class attributes -> only the indexes where an object exists will affect the total loss -> found via the true_confidnce in ground truth \n class_loss = self._cls_normalizer * tf.reduce_sum(ks.losses.binary_crossentropy(K.expand_dims(true_class, axis = -1), K.expand_dims(pred_class, axis = -1)), axis= -1) * true_conf\n \n #7. apply bce to confidence at all points and then strategiacally penalize the network for making predictions of objects at locations were no object exists\n bce = ks.losses.binary_crossentropy(K.expand_dims(true_conf, axis = -1), pred_conf)\n conf_loss = (true_conf + (1 - true_conf) * mask_iou) * bce\n\n #8. take the sum of all the dimentions and reduce the loss such that each batch has a unique loss value\n loss_box = tf.cast(tf.reduce_sum(loss_box, axis=(1, 2, 3)), dtype = self.dtype)\n conf_loss = tf.cast(tf.reduce_sum(conf_loss, axis=(1, 2, 3)), dtype = self.dtype)\n class_loss = tf.cast(tf.reduce_sum(class_loss, axis=(1, 2, 3)), dtype = self.dtype)\n\n #9. i beleive tensorflow will take the average of all the batches loss, so add them and let TF do its thing\n loss = tf.reduce_mean(class_loss + conf_loss + loss_box)\n\n #debug\n # if loss > 100 and batch_size == 1:\n # tf.print(\"iou recall75:, \", tf.reduce_sum(tf.cast(iou > 0.75, dtype = self.dtype) * true_conf)/tf.reduce_sum(true_conf + 0.0000001))\n # tf.print(\"iou recall50:, \", tf.reduce_sum(tf.cast(iou > 0.5, dtype = self.dtype) * true_conf)/tf.reduce_sum(true_conf + 0.0000001))\n \n # mask = tf.reduce_any(K.expand_dims(true_conf, axis = -1) > tf.cast(0, dtype = self.dtype), axis= -1)\n # #mask = tf.reduce_any(mask, axis= 0) \n # mask_best = tf.reduce_any(K.expand_dims(tf.math.sigmoid(y_pred[..., 4]), axis = -1) > tf.cast(0.5, dtype = self.dtype), axis= -1)\n # #mask_best = tf.reduce_any(mask_best, axis= 0) \n # tf.print(tf.shape(mask_best))\n # bridge = 1\n # for batch in range(batch_size):\n # tf.print(\"\\npred high: \", tf.boolean_mask(pred_box, mask_best[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"pred: \", tf.boolean_mask(pred_box, mask[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"true: \", tf.boolean_mask(true_box, mask[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"pred objness high: \", tf.boolean_mask(pred_conf , mask_best[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"pred objness: \", tf.boolean_mask(pred_conf , mask[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"x_y high: \", tf.boolean_mask(grid_points * fwidth, mask_best[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"x_y: \", tf.boolean_mask(grid_points * fwidth, mask[batch], axis = 1)[batch, :bridge, :])\n # tf.print(\"objness loss\", conf_loss)\n return loss\n\n def get_config(self):\n \"\"\"save all loss attributes\"\"\"\n layer_config = {\n \"anchors\": self._anchors, \n \"classes\": self._classes,\n \"ignore_thresh\": self._ignore_thresh, \n \"truth_thresh\": self._truth_thresh, \n \"iou_thresh\": self._iou_thresh, \n \"loss_type\": self._loss_type, \n \"iou_normalizer\": self._iou_normalizer,\n \"cls_normalizer\": self._cls_normalizer, \n \"scale_x_y\": self._scale_x_y, \n }\n layer_config.update(super().get_config())\n return layer_config\n\n","sub_path":"yolo/modeling/functions/yolo_loss.py","file_name":"yolo_loss.py","file_ext":"py","file_size_in_byte":11947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"616210558","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport webapp2\nimport json\nimport time\nfrom Login \t\t\timport Login\nfrom ActivityLog.ActivityLog\timport ActivityLog\nfrom VL_Responses \t \t\timport VL_Responses\nfrom VL_Validator\t\t\t\timport VL_Validator\n\nclass User_Read(webapp2.RequestHandler):\n\n\tlogin\t\t\t= Login()\n\tactivityLog\t\t= ActivityLog()\n\tresponses\t\t= VL_Responses()\n\tvalidator \t\t= VL_Validator()\n\turlPath\t\t\t= \"/Login/Read\"\n\n\tdef get(self):\n\t\tself.response.write(\"Login/Read GET\")\n\n\tdef post(self):\n\n\t\t#Response Object\n\t\tresponseObject \t\t\t\t\t= {}\n\t\tresponseObject[\"status\"] \t\t= \"BAD\"\t#Status of the response to the User\n\t\tresponseObject[\"description\"]\t= \"\"\t#Text description\n\t\tresponseObject[\"data\"]\t\t\t= {}\n\n\t\t#Validate the session\n\t\tif not self.validator.isLoginOkOnRoute({\n\t\t\t\"loginID\":self.request.get(\"sessionID\"),\n\t\t\t\"skey\":self.request.get(\"token\"),\n\t\t\t\"urlPath\":self.urlPath\n\t\t}):\n\n\t\t\tself.responses.unauthorizedResponse(self.response)\n\n\t\telse:\n\n\t\t\t#Read ID\n\t\t\tdataDict = {}\n\t\t\tdataDict[\"loginID\"] = self.validator.validate(self.request.get(\"loginID\"), datatype=\"MongoID\", required=True, fieldname=\"loginID\")\n\n\t\t\t#Validation\n\t\t\tvalidation = self.validator.validateDataDict(dataDict)\n\n\t\t\t#Check all params are sent\n\t\t\tif not validation and dataDict.keys() > 0:\n\n\t\t\t\t#Read object in mongoDB\n\t\t\t\tqueryData = self.login.read(dataDict[\"loginId\"])\n\n\t\t\t\tif queryData:\n\t\t\t\t\tif time.time() <= queryData[\"expiration\"]:\n\t\t\t\t\t\tresponseObject[\"data\"] = {\"isValid\":True}\n\t\t\t\t\telse:\n\t\t\t\t\t\tresponseObject[\"data\"] = {\"isValid\":False}\n\n\t\t\t\t\tresponseObject[\"status\"] \t\t\t\t= \"OK\"\n\n\t\t\t\telse:\n\t\t\t\t\tresponseObject[\"description\"] = \"Invalid Object\"\n\n\t\t\telse:\n\t\t\t\t#Not all paremeters were sent\n\t\t\t\tresponseObject[\"description\"] = \"Invalid mongoID.\"\n\n\t\t\t#Finally end response with JSON\n\t\t\tself.responses.endJSONResponse(self.request, self.response, responseObject)\n","sub_path":"readme/Backend/Login/Login_Read.py","file_name":"Login_Read.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"2328634","text":"import unittest\nimport numpy as np\n\nfrom force_bdss_prototype.mco.MCOsolver import MCOsolver\n\ny0 = np.array([0.5, 0.1, 330, 3600])\nva_range = (0, 1)\nce_range = (0.001, 0.01)\nT_range = (300, 600)\ntau_range = (0, 3600)\nconstr = (va_range, ce_range, T_range, tau_range)\nf = lambda y: (y[0] * y[1] * y[2] * y[3])**2\nobj_f = lambda y: np.array([f(y), f(y), f(y)])\njac1 = lambda y: 2 * y[0] * (y[1] * y[2] * y[3])**2\njac2 = lambda y: 2 * y[1] * (y[0] * y[2] * y[3])**2\njac3 = lambda y: 2 * y[2] * (y[0] * y[1] * y[3])**2\njac4 = lambda y: 2 * y[3] * (y[0] * y[1] * y[2])**2\njac = lambda y: np.array([jac1(y), jac2(y), jac3(y), jac4(y)])\nobj_jac = lambda y: np.array([jac(y), jac(y), jac(y)])\nnptype = type(np.array([]))\ncalltype = type(lambda x: x)\n\nclass MCOsolverTestCase(unittest.TestCase):\n\n def test_instance(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertIsInstance(mcosolver, MCOsolver)\n\n def test_init_types(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(type(obj_f), calltype)\n self.assertEqual(type(obj_jac), calltype)\n self.assertEqual(type(obj_f(y0)), nptype)\n self.assertEqual(type(obj_jac(y0)), nptype)\n\n def test_init_dim(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(len(mcosolver.constr), 4)\n self.assertEqual(mcosolver.y0.shape, (4,))\n self.assertEqual(obj_jac(y0).shape, (3, 4))\n self.assertEqual(obj_f(y0).shape, (3,))\n\n def test_solve_return_type(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(type(mcosolver.solve(N=4)), nptype)\n\n def test_solve_return_shape(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(mcosolver.solve(N=4).shape, (10,4))\n\n def test_KKTsolver_return_type(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(type(mcosolver.KKTsolver(f, jac)), nptype)\n\n def test_KKTsolver_return_shape(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n self.assertEqual(mcosolver.KKTsolver(f, jac).shape, (4,))\n\n def test_store_curr_res_side_effects(self):\n mcosolver = MCOsolver(y0, constr, obj_f, obj_jac)\n iprime = mcosolver.i\n mcosolver.store_curr_res(y0)\n i = mcosolver.i\n mcosolver.i = mcosolver.res.shape[0]\n reslenprime = mcosolver.res.shape[0]\n mcosolver.store_curr_res(y0)\n self.assertEqual(iprime + 1, i)\n self.assertEqual(reslenprime * 2, mcosolver.res.shape[0])\n","sub_path":"force_bdss_prototype/mco/tests/test_MCOsolver.py","file_name":"test_MCOsolver.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"197648629","text":"import requests as rq\nimport json\nfrom riotApiCalls import *\nfrom helperFunctions import *\n\n\nclass SummonerData:\n\n @staticmethod\n def getSummonerData(apiKey, summonerName):\n data = rq.get(RiotApiCalls.summonerIdUrl(apiKey, summonerName))\n\n return data.json()\n\n @staticmethod\n def Main():\n apiKey = HelperFunctions.getKey()\n summonerName = HelperFunctions.getSummonerNameFromUser()\n\n data = SummonerData.getSummonerData(apiKey, summonerName)\n \n return data\n\n\nif __name__ == \"__main__\":\n\n SummonerData.Main()\n","sub_path":"src/summonerSimpleData.py","file_name":"summonerSimpleData.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"72048385","text":"import importlib\nimport sys\n\nimport tensorflow as tf\n\ndef single_tel_model(features, params, training):\n \n # Reshape inputs into proper dimensions\n num_telescope_types = len(params['selected_telescope_types']) \n if num_telescope_types != 1:\n raise ValueError('Must use a single telescope type for single telescope model. Number used: {}'.format(num_telescope_types))\n telescope_type = params['selected_telescope_types'][0]\n image_width, image_length, image_depth = params['image_shapes'][telescope_type]\n num_gamma_hadron_classes = params['num_classes']\n \n telescope_data = features['telescope_data']\n telescope_data = tf.reshape(telescope_data,[-1,image_width,image_length,image_depth], name=\"telescope_images\")\n\n # Load neural network model\n sys.path.append(params['model_directory'])\n network_module = importlib.import_module(params['single_tel']['network']['module'])\n network = getattr(network_module, params['single_tel']['network']['function'])\n\n with tf.variable_scope(\"Network\"):\n output = network(telescope_data, params=params, training=training)\n\n if params['single_tel']['pretrained_weights']:\n tf.contrib.framework.init_from_checkpoint(params['single_tel']['pretrained_weights'],{'Network/':'Network/'})\n\n output_flattened = tf.layers.flatten(output)\n\n logits = tf.layers.dense(output_flattened,units=num_gamma_hadron_classes)\n\n return logits\n","sub_path":"models/single_tel.py","file_name":"single_tel.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42657317","text":"import asyncio\nimport logging\n\nfrom smart_bot.strategies.base_strategy import BaseRobotStrategy\nfrom smart_bot.strategies.motorized_robot import MotorizedSteeringRobotStrategy\n\n\ntrace_log = logging.getLogger('smart_bot.trace')\nlogger = logging.getLogger(__name__)\n\n\nclass StickyDistFollower(BaseRobotStrategy):\n\n def __init__(self, log=None):\n super(StickyDistFollower, self).__init__()\n self.__locked = False\n self.__moving = False\n self.__log = log\n self.distances = {}\n\n def sensor_handler(self, name, data):\n yield from self.recalculate_distances(data)\n\n @asyncio.coroutine\n def recalculate_distances(self, distances):\n distances = distances[:3]\n trace_log.debug('Recalc distances: %s', distances)\n self.log_data = {'dists': distances}\n\n min_dist = min(distances)\n max_dist = max(distances)\n \n if self.motor.stopped:\n logger.info('IS STOPPED')\n return\n \n if min_dist < 10:\n logger.info('Criticaly close to obstacle (%s). Emergency stopping...', distances)\n yield from self.on_stop()\n elif self.motor.moving_forward and min_dist < 20:\n logger.info('Trying to overcome obstacle (%s)...', distances)\n yield from self.__start_relocating(distances)\n elif min_dist < 100:\n logger.info('Found (at %s) a target to follow in %scm. Chasing...', 100, distances)\n yield from self.__start_following(distances)\n else:\n logger.info('Nothing to follow (%s). Stopping...', distances)\n # print(\"finish proc dists\")\n yield from self.log()\n\n @asyncio.coroutine\n def __start_relocating(self, dists):\n #yield from self.on_stop()\n trace_log.info('Relocating at %s', dists)\n \n if dists[0] < dists[2] and dists[2] >= 10:\n trace_log.info('Relocating lefts at %s', dists)\n yield from self.on_left(progress=100)\n yield from self.on_left(progress=100, active=False)\n elif dists[0] >= dists[2] and dists[0] >= 10:\n trace_log.info('Relocating rights at %s', dists)\n yield from self.on_right(progress=100)\n yield from self.on_left(progress=100, active=False)\n #yield from self.on_backward()\n\n @asyncio.coroutine\n def __start_following(self, dists):\n trace_log.info('Following object at %s', dists)\n if dists[2] <= dists[0] and dists[1] - dists[2] > 5:\n yield from self.on_right()\n elif dists[2] > dists[0] and dists[1] - dists[0] > 5:\n yield from self.on_left()\n yield from self.on_forward()\n\n @asyncio.coroutine\n def __turn_right(self):\n if self.__locked:\n return\n self.log_data['action'] = 'right_start'\n yield from self.log()\n self.__locked = True\n yield from asyncio.sleep(0.15)\n self.log_data['action'] = 'right_end'\n self.__locked = False\n\n\nclass MotorizedSteeringDistFollower(MotorizedSteeringRobotStrategy, StickyDistFollower):\n pass\n","sub_path":"src/smart_bot/strategies/dist_follower.py","file_name":"dist_follower.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"62179173","text":"import os\nimport yaml\nimport logging\nimport requests\nimport asyncio\nimport aiohttp\nimport tempfile\nfrom rasa.utils.common import set_log_level\nfrom asyncio import CancelledError\nfrom rasa.utils.endpoints import EndpointConfig\nfrom typing import Text, Dict, Union\nfrom rasa.core.events import UserUttered, BotUttered, SlotSet\nlogger = logging.getLogger(__name__)\n\nfrom rasa.core.constants import DEFAULT_REQUEST_TIMEOUT\n\nasync def load(session, params, url):\n try:\n return await session.request(\"GET\", url, timeout=DEFAULT_REQUEST_TIMEOUT, params=params)\n except aiohttp.ClientError:\n return None\n\nasync def load_from_remote(\n server: EndpointConfig, name: Text, temp_file=True\n) -> Union[Text, Dict]:\n \"\"\"Returns and object or a file from an endpoint\n \"\"\"\n\n logger.debug(\"Requesting {} from server {}...\".format(name, server.url))\n\n async with server.session() as session:\n params = server.combine_parameters()\n url = server.url\n tries = 1; resp = None\n while not resp or resp.status != 200:\n if tries == 1 or tries % 5000 == 0:\n logger.debug('Trying to fetch {} from server (retry #{})'.format(name, str(tries)))\n resp = await load(session, params, url)\n tries += 1\n\n json = await resp.json()\n if temp_file is True:\n with tempfile.NamedTemporaryFile(mode='w', delete=False) as yamlfile:\n yaml.dump(json, yamlfile)\n return yamlfile.name\n else:\n return json\n\ndef set_endpoints_credentials_args_from_remote(args):\n bf_url = os.environ.get('BF_URL')\n project_id = os.environ.get('BF_PROJECT_ID')\n if not project_id or not bf_url:\n return\n\n if not args.endpoints:\n logger.info(\"Fetching endpoints from server\")\n url = \"{}/project/{}/{}\".format(bf_url, project_id, \"endpoints\")\n try:\n args.endpoints = asyncio.get_event_loop().run_until_complete(\n load_from_remote(EndpointConfig(url=url), \"endpoints\")\n )\n except aiohttp.ClientError:\n raise aiohttp.ClientError('Could not load endpoints for project {}.'.format(project_id))\n\n if not args.credentials:\n logger.info(\"Fetching credentials from server\")\n url = \"{}/project/{}/{}\".format(bf_url, project_id, \"credentials\")\n try:\n args.credentials = asyncio.get_event_loop().run_until_complete(\n load_from_remote(EndpointConfig(url=url), \"credentials\")\n )\n except aiohttp.ClientError:\n raise aiohttp.ClientError('Could not load credentials for project {}.'.format(project_id))\n\n\ndef get_latest_parse_data_language(all_events):\n events = reversed(all_events)\n try:\n while True:\n event = next(events)\n if event['event'] == 'user' and 'parse_data' in event and 'language' in event['parse_data']:\n return event['parse_data']['language']\n\n except StopIteration:\n return None\n\n\ndef get_project_default_language(project_id, base_url):\n url = '{base_url}/project/{project_id}/models/published'.format(base_url=base_url, project_id=project_id)\n result = requests.get(url)\n try:\n result = requests.get(url)\n if result.status_code == 200:\n if result.json():\n return result.json().get('default_language', None)\n else:\n return result.json().error\n else:\n logger.error(\n \"Failed to get project default language\"\n \"Error: {}\".format(result.json()))\n return None\n\n except Exception:\n logger.error(\n \"Failed to get project default language\"\n \"Error: {}\".format(result.json()))\n return None\n\n\ndef events_to_dialogue(events):\n dialogue = \"\"\n for e in events:\n if e[\"event\"] == 'user':\n dialogue += \"\\n User: {}\".format(e['text'])\n elif e[\"event\"] == 'bot':\n dialogue += \"\\n Bot: {}\".format(e['text'])\n return dialogue\n\n\ndef slots_from_profile(user_id, user_profile):\n return [SlotSet(\"user_id\", user_id), SlotSet(\"first_name\", user_profile[\"first_name\"]),\n SlotSet(\"last_name\", user_profile[\"last_name\"]), SlotSet(\"phone\", user_profile[\"phone\"]),\n SlotSet('user_profile', user_profile)]\n","sub_path":"botfront/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95332800","text":"\"\"\"\"\n名称:EXT 003 童芯派 urequests ujson webhook机器人\n硬件: 童芯派 \n功能介绍:\n在钉钉或飞书等办公IM软件当中,可以添加一些自动发消息的机器人。\n通过在软件平台上创建webhook机器人获得webhook机器人链接。\n使用micropython的urequests和ujson库(对应python中requests和json库)实现对webhook机器人的信息推送。\n结合温湿度传感器获得温湿度的值并推送至机器人上。\n注意:不支持中文信息的推送,使用中文信息推送会报错。\n\n\n难度:⭐⭐⭐⭐⭐\n支持的模式:上传模式\n无\n\n\"\"\"\n# ---------程序分割线----------------程序分割线----------------程序分割线----------\nimport urequests\nimport ujson\nimport cyberpi\nimport time\n\n\ncyberpi.wifi.connect(\"输入WIFI密码\", \"输入WIFI密码\")\nwhile not cyberpi.wifi.is_connect():\n pass\ncyberpi.console.println(\"已连接至网络\")\n\npost_url = \"填入webhook机器人的地址\"\nheaders = {'Content-Type': 'application/json'}\n\nwhile True:\n hum = cyberpi.humiture.get_humidity()\n temp = cyberpi.humiture.get_temp()\n mes = \"hum:\"+str(hum)+\" temp:\" + str(temp)\n payload_message = {\"msg_type\": \"text\",\"content\": {\"text\": mes}}\n post_data = ujson.dumps(payload_message)\n payload_message_second = {\"msg_type\": \"text\",\"content\": {\"text\": \"temp:\"+str(temp)}}\n response = urequests.request(\"POST\", url=post_url, data=post_data, headers=headers)\n print(response.text)\n time.sleep(5)\n cyberpi.console.println(response.text)","sub_path":"CyberPi V1/Python with CyberPi EXT003(童芯派 urequests ujson webhook机器人) .py","file_name":"Python with CyberPi EXT003(童芯派 urequests ujson webhook机器人) .py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"52762474","text":"import gym\nimport torch\nimport random\nfrom torch.autograd import Variable\nfrom ExperienceReplay import ExperienceReplay\nfrom ValueNetwork import ValueNetwork\nimport torch.optim as optim\nimport torch.nn as nn\n\ndef compute_val(value_network, obs):\n\tvar_obs = Variable(obs)\n\toutput_qs = value_network((var_obs))\n\treturn output_qs \n\ndef hard_copy(targetValueNetwork, valueNetwork):\n\tfor target_param, param in zip(targetValueNetwork.parameters(), valueNetwork.parameters()):\n\t\t\t\t\ttarget_param.data.copy_(param.data)\n\nif __name__ == \"__main__\":\n\tenv = gym.make('CartPole-v0')\n\tnumEpisodes = 4000\n\texp_replay = ExperienceReplay(20000)\n\ttotal_actions = 0\n\tlearning_rate = 1e-3\n\tmax_grads = 1.0\n\tbatch_size = 128\n\tgamma = 0.999\n\tcopy_freq = 2000\n\n\tvalue_network = ValueNetwork(4,[16,16,4],2)\n\ttarget_value_network = ValueNetwork(4,[16,16,4],2)\n\thard_copy(target_value_network, value_network)\n\n\toptimizer = optim.Adam(value_network.parameters(), lr=learning_rate)\n\n\tfor episode in range(numEpisodes):\n\t\tobs = env.reset()\n\t\tdone = False\n\t\tepsilon = 1.0 - (min(1.0, numEpisodes/4000.0) * 0.95)\n\t\t\n\t\ttotal_reward = 0.0\n\t\tif episode % 1000 == 0:\n\t\t\t\tenv.render()\n\n\t\tif episode % 1000 == 0:\n\t\t\ttorch.save(value_network.state_dict(), \"DQNParams/{}\".format(str(episode//500)))\n\n\t\twhile not done:\n\t\t\tobs_tensor = torch.Tensor(obs).unsqueeze(0)\n\t\t\ttens = compute_val(value_network, obs_tensor)\n\t\t\tprint(tens)\n\t\t\tact = torch.max(tens, dim=1)[1].item()\n\t\t\tif random.random() < epsilon:\n\t\t\t\tact = random.randint(0,1)\n\n\t\t\tnext_obs, rewards, done, info = env.step(act)\n\t\t\ttotal_reward += rewards\n\t\t\ttotal_actions += 1\n\n\t\t\texp_replay.insert((obs , act, rewards, next_obs, int(done)))\n\n\t\t\tif episode % 1000 == 0:\n\t\t\t\tenv.render()\n\t\t\t\n\t\t\tif total_actions > batch_size:\n\n\t\t\t\tstateTensors, actionTensors, rewardTensors, nextStateTensors, masksTensor = exp_replay.sample(batch_size)\n\t\t\t\tpredicted_vals = compute_val(value_network, stateTensors).gather(1, actionTensors)\n\t\t\t\ttarget_next_state = torch.max(compute_val(target_value_network, nextStateTensors), dim=1, keepdim=True)[0]\n\t\t\t\ttarget_vals = rewardTensors + gamma * target_next_state * (1 - masksTensor)\n\t\t\t\ttarget_vals = target_vals.detach()\n\n\t\t\t\toptimizer.zero_grad()\n\n\t\t\t\tloss_function = nn.MSELoss()\n\t\t\t\terr = loss_function(predicted_vals, target_vals)\n\t\t\t\terr.backward()\n\t\t\t\tfor param in value_network.parameters():\n\t\t\t\t\tparam.grad.data.clamp_(-max_grads, max_grads)\n\t\t\t\toptimizer.step()\n\n\n\t\t\tif total_actions % copy_freq == 0:\n\t\t\t\thard_copy(target_value_network, value_network)\n\t\t\tobs = next_obs\n\n\t\tprint(episode, total_reward)\n\n\ttorch.save(value_network.state_dict(), \"DQNParams/{}\".format(str(10)))\n","sub_path":"DeepRLLecture-1/DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"21254768","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 3 00:23:16 2019\n\n@author: Sofonias Alemu\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom pydataset import data\n\n\n##### Problem 2 ######\npb2=pd.read_csv(\"titanic.csv\")\n\npb2.pivot_table(values=\"Survived\",\\\ncolumns=[\"Embarked\"],\\\naggfunc=\"mean\", fill_value='-')\n\npb2.pivot_table(values=\"Survived\",\\\nindex=[\"Sex\"],columns=[\"Embarked\"],\\\naggfunc=\"mean\", fill_value='-')\n\n\n##### Problem 3 #########\n\n","sub_path":"Computation/Wk5_PandSolv/pandas3.py","file_name":"pandas3.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"413848868","text":"import numpy as np\nimport tensorflow as tf\nimport copy\nimport math\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.contrib.layers import xavier_initializer\nimport math\nimport os\nimport LoadData\nimport sys\n# Batch_size = 128\nQP = 35\nIteration = 3001\nalpha = 0.2\nbeta = 0.3\ngamma = 0.5\nZreo_Flag = 2\nepsilon = 0.001\ndecay = 0.99\nREGULARIZATION_RATE = 0.01 #正则化项系数\nLEARNING_RATE_DECAY = 0.99 #学习率的衰减率\nMOVING_AVERAGE_DECAY = 0.99 #滑动平均衰减率\ndef Weight_Variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.03)\n # 使用了tf.truncted_normal产生随机变量来进行初始化:\n return tf.Variable(initial)\n\ndef Bias_Variable(shape):\n # 使用tf.constant常量函数来进行初始化:\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\n# 定义卷积操作\ndef Filter(input, w, sde_w, sde_h):\n return tf.nn.conv2d(input, w, [1, sde_w, sde_h, 1], padding=\"SAME\")\n # input:a tensorflow ,shape:[Batch,Height,Width,Channel]\n # w: filter ,shape:[filter_height,filter_width,Channels,filter_numbers]\n # stride: vector ,shape:4*1 represent stride in every dimension\n # padding: \"SAME\" or \"VALID\" SAME:cover the edge of picture,use 0 for padding\n # output: a tensorflow ,shape:[Batch,Height,Width,Channels\n\n\ndef Pool_Layer(input, k_hei, k_wid, str_hei, str_wid):\n return tf.nn.max_pool(input, ksize=[1, k_hei, k_wid, 1], \\\n strides=[1, str_hei, str_wid, 1], padding=\"VALID\")\n # input:a tensorflow ,feature map,shape:[Batch,Height,Width,Channel]\n # ksize: maxpool size shape,normal [1,Height,Width,1]\n # strides : vector ,shape:4*1 represent stride in every dimension\n # padding: \"SAME\" or \"VALID\" SAME:cover the edge of picture\n # output: a tensorflow ,shape:[Batch,Height,Width,Channels]\n\n\ndef Cal_Mulp(input, w, b):\n return tf.matmul(input, w) + b\n\n\ndef SPP(input,size,out_size):\n a1 = Pool_Layer(input,size,size,size,size)\n a2 = Pool_Layer(input,size*2,size*2,size*2,size*2)\n a3 = Pool_Layer(input,size*4,size*4,size*4,size*4)\n a1 = tf.reshape(a1,[-1,16*out_size])\n a2 = tf.reshape(a2,[-1,4*out_size])\n a3 = tf.reshape(a3,[-1,1*out_size])\n Vec1 = tf.concat([a1, a2], 1)\n Vec2 = tf.concat([Vec1, a3], 1)\n return Vec2\n\ndef add_layer(inputs, in_szie, out_size, activate=None):\n weights = tf.Variable(tf.truncated_normal([in_szie, out_size], stddev=0.01))\n biases = tf.Variable(tf.truncated_normal([1, out_size], stddev=0.01))\n result = tf.matmul(inputs, weights) + biases\n if activate is None:\n return result\n else:\n return activate(result)\n# 用于后续训练\n\ndef batch_norm_training(Conv1_1,mean,variance,shift,scale):\n\n batch_mean, batch_variance = tf.nn.moments(Conv1_1, [0, 1, 2], name=None, keep_dims=False)\n train_mean_1 = tf.assign(mean, mean * decay + batch_mean * (1 - decay))\n train_variance_1 = tf.assign(variance, variance * decay + batch_variance * (1 - decay))\n\n with tf.control_dependencies([train_mean_1, train_variance_1]):\n return mean,variance,tf.nn.batch_normalization(Conv1_1, batch_mean, batch_variance, shift, scale, epsilon)\n\ndef batch_norm_inference(Conv1_1,mean,variance,shift,scale):\n\n return mean,variance,tf.nn.batch_normalization(Conv1_1, mean, variance, shift, scale, epsilon)\n\n\ndef Build_Network():\n is_64 = tf.placeholder(tf.int16,name='m_64')\n is_32 = tf.placeholder(tf.int16,name='m_32')\n ln = tf.placeholder(tf.float32,name='ln')\n Pool_para = 2\n def m64():\n return tf.placeholder(tf.float32, (None, 64, 64, 1), name='X')\n def m32():\n return tf.placeholder(tf.float32, (None, 32, 32, 1), name='X')\n def m16():\n return tf.placeholder(tf.float32, (None, 16, 16, 1), name='X')\n def judge():\n return tf.cond(is_32 > 0,lambda: m32(),lambda: m16())\n def judge1(Pool2):\n return tf.cond(is_32 > 0, lambda: SPP(Pool2, 4, 32), lambda: SPP(Pool2, 2, 32))\n def judge2(Pool4):\n return tf.cond(is_32 > 0, lambda: SPP(Pool4, 2, 32), lambda: SPP(Pool4, 1, 32))\n # X = tf.placeholder(tf.float32, (None, None, None, 1))\n # tf.image.ResizeMethod.NEAREST_NEIGHBOR这里的方法用的是最近邻差值\n # 这里是实用双线性差值\n # 使用tf.image系的函数要慎重,一定要check数据类型,check函数处理后是否在0-255的范围,尤其是resize相关。\n # X = tf.image.resize_images(X, (IMAGE_SIZE, IMAGE_SIZE),\n # tf.image.ResizeMethod.BILINEAR+)\n X = tf.cond(is_64 > 0, lambda :m64(), lambda :judge())\n y = tf.placeholder(tf.float32, [None, 1],name='y')\n is_training = tf.placeholder(tf.bool, name='is_train')\n kp = tf.placeholder(tf.float32, name='kp')\n #global_step = tf.Variable(0, trainable=False)\n with tf.name_scope(\"Conv1\") as scope:\n kernel1_1 = tf.Variable(tf.truncated_normal([3, 3, 1, 32], stddev=0.03), name=\"k1\")\n\n b1_1 = tf.Variable(tf.constant(0.1, shape=[32]), name=\"b1\")\n Conv1_1 = tf.nn.bias_add(Filter(X, kernel1_1, 1, 1), b1_1, name='op_add1')\n bn1 = tf.layers.batch_normalization(Conv1_1, training=is_training)\n Output_Conv1_1 = tf.nn.relu(bn1)\n Pool1 = tf.nn.max_pool(Output_Conv1_1, ksize=[1, 2, 2, 1], \\\n strides=[1, 1, 1, 1], padding=\"SAME\")\n kernel1_2 = tf.Variable(tf.truncated_normal([3, 3, 32,32 ], stddev=0.03), name=\"k2\")\n\n # with tf.control_dependencies([assign_from_placeholder]):\n # x_assign = x.assign(1)\n\n b1_2 = tf.Variable(tf.constant(0.1, shape=[32]), name=\"b2\")\n Output_Conv1_2 = tf.nn.bias_add(Filter(Pool1, kernel1_2, 1, 1), b1_2, name='op_add2')\n bn2 = tf.layers.batch_normalization(Output_Conv1_2, training=is_training)\n Output_Conv1_3 = tf.nn.relu(bn2)\n\n Pool2 = Pool_Layer(Output_Conv1_3, Pool_para, Pool_para, Pool_para, Pool_para)\n\n l1 = tf.cond(is_64 > 0, lambda: SPP(Pool2, 8, 32), lambda: judge1(Pool2))\n\n with tf.name_scope(\"Conv2\") as scope:\n kernel2_1 = tf.Variable(tf.truncated_normal([3, 3, 32, 32], stddev=0.03), name=\"k1\")\n # with tf.control_dependencies([assign_from_placeholder]):\n # x_assign = x.assign(1)\n b2_1 = tf.Variable(tf.constant(0.1, shape=[32]), name=\"b1\")\n Conv2_1 = tf.nn.bias_add(Filter(Pool2, kernel2_1, 1, 1), b2_1, name='op_add1')\n bn3 = tf.layers.batch_normalization(Conv2_1, training=is_training)\n Output_Conv2_1 = tf.nn.relu(bn3)\n Pool3 = tf.nn.max_pool(Output_Conv2_1, ksize=[1, 2, 2, 1], \\\n strides=[1, 1, 1, 1], padding=\"SAME\")\n kernel2_2 = tf.Variable(tf.truncated_normal([3, 3, 32, 32], stddev=0.03), name=\"k2\")\n b2_2 = tf.Variable(tf.constant(0.1, shape=[32]), name=\"b2\")\n Output_Conv2_2 = tf.nn.bias_add(Filter(Pool3, kernel2_2, 1, 1), b2_2, name='op_add2')\n bn4 = tf.layers.batch_normalization(Output_Conv2_2, training=is_training)\n Output_Conv2_3 = tf.nn.relu(bn4)\n Pool4 = Pool_Layer(Output_Conv2_3, Pool_para, Pool_para, Pool_para, Pool_para)\n\n l2 = tf.cond(is_64 > 0, lambda: SPP(Pool4, 4,32), lambda: judge2(Pool4))\n Vec1 = tf.concat([l1, l2], 1)\n\n #weights1 = tf.Variable(tf.truncated_normal([1344, 128], stddev=0.01), name=\"w1\")\n weights1=tf.get_variable('w1',[1344, 128], tf.float32, xavier_initializer())\n # weight_loss1 = tf.multiply(tf.nn.l2_loss(weights1), 0.001, name='weight_loss1')\n # tf.add_to_collection('losses', weight_loss1)\n b3 = tf.Variable(tf.truncated_normal([1, 128], stddev=0.01), name=\"b3\")\n result1 = tf.matmul(Vec1, weights1) + b3\n Layer_1_pre = tf.nn.relu(result1)\n\n Layer_1_pre = tf.nn.dropout(Layer_1_pre, kp)\n\n #weights2 = tf.Variable(tf.truncated_normal([128, 8], stddev=0.01), name=\"w2\")\n weights2 = tf.get_variable('w2',[128, 16], tf.float32, xavier_initializer())\n b4 = tf.Variable(tf.truncated_normal([1, 16], stddev=0.01), name=\"b4\")\n result2 = tf.matmul(Layer_1_pre, weights2) + b4\n Layer_2_pre = tf.nn.relu(result2)\n Layer_2_pre = tf.nn.dropout(Layer_2_pre, kp)\n\n #weights3 = tf.Variable(tf.truncated_normal([8, 1], stddev=0.01), name=\"w3\")\n weights3 = tf.get_variable( 'w3',[16, 1], tf.float32, xavier_initializer())\n b5 = tf.Variable(tf.truncated_normal([1, 1], stddev=0.01), name=\"b5\")\n result4 = tf.matmul(Layer_2_pre, weights3) + b5\n Pre_Label = tf.nn.sigmoid(result4)\n # tf.add_to_collection(\"pre64\", Pre_64)\n Pre = tf.round(Pre_Label, name=\"output\")\n # variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)\n # variables_averages_op = variable_averages.apply(tf.trainable_variables())\n # LOSS = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Pre, labels=y))\n LOSS = -tf.reduce_mean(y * tf.log(tf.clip_by_value\\\n (Pre_Label, 1e-10, 1.0)) + (1 - y) * tf.log(tf.clip_by_value \\\n (1 - Pre_Label, 1e-10,\n 1.0)))\n correct_Cu64_Num = tf.equal(Pre, y)\n # 把bool矩阵转换为float类型,并求平均即得到了准确率\n acc = tf.reduce_mean(tf.cast(correct_Cu64_Num, dtype=tf.float32),name='acc')\n #tf.add_to_collection('losses', LOSS)\n # LOSS_REGU = tf.add_n(tf.get_collection('losses'), name='total_loss')\n # learning_rate = tf.train.exponential_decay(\n # 0.2,\n # global_step=500*64,\n # decay_rate=0.99,\n # decay_steps=200,\n # staircase=True)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n Train = tf.train.AdamOptimizer(learning_rate=ln, beta1=0.9, beta2=0.999, epsilon=1e-08).minimize(LOSS)\n # Train = tf.group(Train_op, variables_averages_op)\n # Train = tf.train.AdamOptimizer(0.2).minimize(LOSS_REGU)\n\n return dict(\n inputs_Mat=X,\n ys_label=y,\n is_training=is_training,\n kp=kp,\n ln=ln,\n is_64=is_64,\n is_32=is_32,\n Train=Train,\n LOSS=LOSS,\n acc=acc,\n Pre=Pre,\n Pre_Label=Pre_Label,\n )","sub_path":"NewGraph.py","file_name":"NewGraph.py","file_ext":"py","file_size_in_byte":10311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"135845785","text":"import requests\n\nacc_num = 1000\n\nURL = 'https://www.roblox.com/usercheck/checkifinvalidusernameforsignup?birthday=2000-02-01T05:00:00.000Z&username='\n\nAPI = 'http://www.shittyusernames.com/api/get-username'\n\ndef createfile():\n create = open('namesnipe.txt','w')\n\ncreatefile()\n\nfor i in range(1,acc_num): #I have no clue how many usernames are in this API you might get the same results. (?)\n\n getname = requests.get(API)\n\n name = getname.text\n\n checkname = requests.get(URL+str(name))\n\n if checkname.text == '{\"data\":0}':\n print(name+' : is open. (logged to file)')\n log = open('namesnipe.txt','a+')\n log.write(name+ '\\n')\n else:\n print(name+' : is taken')\n","sub_path":"sniperrblx.py","file_name":"sniperrblx.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"206168205","text":"#/usr/bin/env python3\n\nimport requests\nimport random\nfrom sys import exit\n\ndef loadWordList(\n\tpathsToTry=['/usr/share/dict/words','enable1.txt'],\n\turlFallback='http://svnweb.freebsd.org/base/head/share/dict/web2?view=co'):\n\twordList = None\n\tfor path in pathsToTry:\n\t\tif wordList is None:\n\t\t\ttry:\n\t\t\t\twith open(path) as f:\n\t\t\t\t\twordList = f.read().split('\\n')\n\t\t\t\tif not any(wordList):\n\t\t\t\t\twordList = None\n\t\t\t\t\traise IOError\n\t\t\t\tbreak\n\t\t\texcept IOError:\n\t\t\t\tcontinue\n\tif wordList is None:\n\t\twordlist = requests.get('http://svnweb.freebsd.org/base/head/share/dict/web2?view=co').content.decode('utf-8').split('\\n')\n\t\tif not any(wordlist):\n\t\t\tprint(\"Could not read wordlist.\")\n\t\t\treturn None\n\treturn wordList\n\ndef getDifficulty():\n\twhile True:\n\t\ttry:\n\t\t\tlevel = int(input(\"Difficulty (1-5)? \"))\n\t\t\tif level >= 1 and level <= 5:\n\t\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tcontinue\n\treturn [(4,5), (7,8), (10,10), (12,13), (15,15)][level - 1]\n\n\ndef play(choices, correct):\n\tprint('\\n'.join(choices))\n\n\tlives = 4\n\twhile lives > 0:\n\t\tguess = input('Guess ({} left)? '.format(lives)).upper()\n\t\tif guess == correct:\n\t\t\tprint(\"Correct!\")\n\t\t\treturn\n\t\telse:\n\t\t\tlives -= 1\n\t\t\ta, b = sorted([guess, correct], key=len)\n\t\t\tmatches = 0\n\t\t\tfor i in range(len(a)):\n\t\t\t\tif a[i] == b[i]:\n\t\t\t\t\tmatches += 1\n\t\t\tprint(\"{}/{} correct\".format(matches, len(correct)))\n\nif __name__ == '__main__':\n\tprint('\\033[32m\\033[40m')\n\twordList = loadWordList()\n\n\tlength, num = getDifficulty()\n\t\n\twords = [i.upper() for i in wordList if len(i) == length]\n\t\n\tchoices = random.sample(words, num)\n\tcorrect = random.choice(choices)\n\tplay(choices, correct)\n\tprint('\\033[0m')","sub_path":"163i/hacking_game.py","file_name":"hacking_game.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"280391772","text":"import RPi.GPIO as gpio\nimport pyaudio\nimport time\nfrom record import Recorder\nfrom play_thread import Player\n# from pynput import mouse\nimport threading\n\n\ngpio.setmode(gpio.BCM)\ngpio.setwarnings(False) # Ignore warning for now\ngpio.setup(4, gpio.OUT) # LED == 4 in BCM\ngpio.output(4, False) # Set output to off\ngpio.setup(17, gpio.IN, pull_up_down=gpio.PUD_UP)\n\n\nclass ButtonRecorderPlayer(object):\n def __init__(self):\n self.isPlaying = True\n self.p = pyaudio\n self.rec = Recorder(channels=1)\n self.play = None\n self.playback_thread = threading.Thread(name='button_listener', target=self.button_listener)\n\n def on_button(self, channel): # Called by inbuilt threaded interrupt\n print('button')\n if recPlayBtn.isPlaying:\n print('stoping playback and starting recording')\n recPlayBtn.stop_playback()\n recPlayBtn.isPlaying = False\n recPlayBtn.start_recording()\n else:\n print('stoping recording and starting playback')\n recPlayBtn.stop_recording()\n recPlayBtn.isPlaying = True\n recPlayBtn.start_playback()\n\n def button_listener(self):\n # with mouse.Listener( on_click = self.on_click) as listener:\n with gpio.add_event_detect(17, gpio.FALLING, callback=self.on_button, bouncetime=100) as listener:\n listener.join()\n print ('listener started')\n\n def start(self):\n self.playback_thread.start()\n self.start_playback()\n\n def start_recording(self, channel=1):\n print ('Recording, click to stop recording')\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n gpio.output(4, True) #LED on\n self.recfile = self.rec.open('recordings/' + timestr + '.wav', self.p, 'wb')\n self.recfile.start_recording()\n\n def stop_recording(self, channel=1):\n self.recfile.stop_recording()\n self.recfile.close()\n gpio.output(4, False) #LED on\n print ('Recording Stopped')\n\n def start_playback(self, channel=1):\n print ('playback starting')\n self.play = Player('recordings', self.p)\n self.play.start()\n\n def stop_playback(self):\n self.play.stopper()\n print ('playback stopped')\n\n\nrecPlayBtn = ButtonRecorderPlayer()\nrecPlayBtn.start()\n\ntry:\n input()\nexcept KeyboardInterrupt:\n pass\n\n#exit if invalid state\ngpio.cleanup()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"639869683","text":"from joblib import dump, load\nimport numpy as np\nimport csv as cv\nimport pandas as pd\nimport os\n\ndef String2List(string):\n return list(string.split(\" \"))\n\ndef file_len(fname):\n if(os.stat(fname).st_size == 0):\n return 'empty'\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\ndef convDataInst(X, df, j, no_of_class):\n with open('param_dict.csv') as csv_file:\n reader = cv.reader(csv_file)\n paramDict = dict(reader)\n if(paramDict['multi_label'] == 'False'):\n no_of_class = 1\n data_inst= np.zeros((1, df.shape[1]-no_of_class))\n if(j > X.shape[0]):\n raise Exception('Z3 has produced counter example with all 0 values of the features: Run the script Again')\n sys.exit(1)\n for i in range(df.shape[1]-no_of_class):\n data_inst[0][i] = X[j][i]\n return data_inst\n\ndef funcAdd2Oracle(data): \n with open('TestingData.csv', 'a', newline='') as csvfile: \n writer = cv.writer(csvfile)\n writer.writerows(data)\n\n\ndef funcCreateOracle(no_of_class, multi_label, model):\n df = pd.read_csv('TestingData.csv')\n data = df.values\n if multi_label == 'False':\n X = data[:, :-1]\n predict_class = model.predict(X)\n for i in range(0, X.shape[0]):\n df.loc[i, 'Class'] = predict_class[i]\n else:\n X = data[:, :-no_of_class]\n predict_class = model.predict(X)\n index = df.shape[1]-no_of_class\n for i in range(0, no_of_class):\n className = str(df.columns.values[index+i])\n for j in range(0, X.shape[0]):\n df.loc[j, className] = predict_class[j][i]\n df.to_csv('OracleData.csv', index=False, header=True)\n\n\ndef storeMapping(file_name, dictionary):\n try:\n with open(file_name, 'w') as csv_file: \n writer = cv.writer(csv_file)\n for key, value in dictionary.items():\n writer.writerow([key, value])\n except IOError:\n print(\"I/O error\")\n\ndef addContent(file_name, f_content): \n f1 = open(file_name, 'a')\n for x in f_content:\n f1.write('\\n')\n f1.write(x)\n f1.close()\n\ndef addSatOpt(file_name):\n f = open(file_name, 'a')\n f.write('\\n')\n f.write(\"(check-sat) \\n\")\n f.write(\"(get-model) \\n\")\n\ndef storeAssumeAssert(file_name):\n with open('dict.csv') as csv_file:\n reader = cv.reader(csv_file)\n assumeDict = dict(reader)\n if(assumeDict['no_assumption'] == 'True'):\n pass\n else:\n with open('assumeStmnt.txt') as f2:\n f2_content = f2.readlines()\n f2_content = [x.strip() for x in f2_content]\n addContent(file_name, f2_content)\n with open('assertStmnt.txt') as f3:\n f3_content = f3.readlines()\n f3_content = [x.strip() for x in f3_content]\n addContent(file_name, f3_content)\n\n\n\n","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"189352988","text":"from utils import *\nimport pickle\nimport sys\n\ng = Log()\nh = Sum()\n\n# rank Shannon discrimination measure\nf_r = Dsr()\nrsdm = Gdm(h, g, f_r)\n\n# conditional Shannon entropy\nf = Ds()\nsdm = Gdm(h, g, f)\n\n# pessimistic rank discrimination measure\nf_p = Mindsr()\ng_p = Frac()\nprdm = Gdm(h, g_p, f_p)\n\nstart = time.time()\n\ndataset, t = generate_2Ddataset(0, 2, 1000, 0, 0.1, [[-10, 10], [-10, 10]])\n\nprint(\"noise : \", 0.05 * int(sys.argv[2]))\n\nfor k in range(int(sys.argv[2])):\n dataset = add_noise(dataset, 0.05)\n\nsets = get_ten_folds(dataset)\n\nacc1 = 0\nleaves1 = 0\ndepth1 = 0\nratio1 = 0\npairs1 = 0\n\nacc2 = 0\nleaves2 = 0\ndepth2 = 0\nratio2 = 0\npairs2 = 0\n\nacc3 = 0\nleaves3 = 0\ndepth3 = 0\nratio3 = 0\npairs3 = 0\n\nfor i in range(10):\n test_set = sets[i]\n train_set = LabeledSet(2)\n for j in range(10):\n if i != j:\n train_set.addExamples(sets[j].x, sets[j].y)\n tree1 = RDMT(rsdm, \"shannon\", 0, 100, 0.01, [1, 2])\n tree1.train(train_set)\n acc1 += tree1.accuracy(test_set)\n leaves1 += tree1.get_nb_leaves()\n depth1 += tree1.get_depth()\n ratio1 += tree1.get_ratio_non_monotone_pairs()\n pairs1 += tree1.get_total_pairs()\n print(\"Iter {} tree1\".format(i))\n\n tree2 = RDMT(sdm, \"shannon\", 0, 100, 0.01, [1, 2])\n tree2.train(train_set)\n acc2 += tree2.accuracy(test_set)\n leaves2 += tree2.get_nb_leaves()\n depth2 += tree2.get_depth()\n ratio2 += tree2.get_ratio_non_monotone_pairs()\n pairs2 += tree2.get_total_pairs()\n\n print(\"Iter {} tree2\".format(i))\n tree3 = RDMT(prdm, \"shannon\", 0, 100, 0.01, [1, 2])\n tree3.train(train_set)\n acc3 += tree3.accuracy(test_set)\n leaves3 += tree3.get_nb_leaves()\n depth3 += tree3.get_depth()\n ratio3 += tree3.get_ratio_non_monotone_pairs()\n pairs3 += tree3.get_total_pairs()\n print(\"Iter {} tree3\".format(i))\n\nacc1 = acc1 * (1.0/10)\ndepth1 = depth1 * (1.0/10)\nratio1 = ratio1 * (1.0/10)\npairs1 = pairs1 * (1.0/10)\n\nacc2 = acc2 * (1.0/10)\nleaves2 = leaves2 * (1.0/10)\ndepth2 = depth2 * (1.0/10)\nratio2 = ratio2 * (1.0/10)\npairs2 = pairs2 * (1.0/10)\n\nacc3 = acc3 * (1.0/10)\nleaves3 = leaves3 * (1.0/10)\ndepth3 = depth3 * (1.0/10)\nratio3 = ratio3 * (1.0/10)\npairs3 = pairs3 * (1.0/10)\n\nprint(\"Running time (\" + sys.argv[2]+ \") : \" + str(time.time() - start))\nf_acc1 = open(\"acc1_\" + sys.argv[2], \"wb\")\nf_leaves1 = open(\"leaves1_\"+ sys.argv[2], \"wb\")\nf_depth1 = open(\"depth1_\"+ sys.argv[2], \"wb\")\nf_ratio1 = open(\"ratio1_\"+ sys.argv[2], \"wb\")\nf_pairs1 = open(\"pairs1_\"+ sys.argv[2], \"wb\")\n\n\nf_acc2 = open(\"acc2_\"+ sys.argv[2], \"wb\")\nf_leaves2 = open(\"leaves2_\"+ sys.argv[2], \"wb\")\nf_depth2 = open(\"depth2_\"+ sys.argv[2], \"wb\")\nf_ratio2 = open(\"ratio2_\"+ sys.argv[2], \"wb\")\nf_pairs2 = open(\"pairs2_\"+ sys.argv[2], \"wb\")\n\nf_acc3 = open(\"acc3_\"+ sys.argv[2], \"wb\")\nf_leaves3 = open(\"leaves3_\"+ sys.argv[2], \"wb\")\nf_depth3 = open(\"depth3_\"+ sys.argv[2], \"wb\")\nf_ratio3 = open(\"ratio3_\"+ sys.argv[2], \"wb\")\nf_pairs3 = open(\"pairs3_\"+ sys.argv[2], \"wb\")\n\npickle.dump(acc1, f_acc1)\npickle.dump(leaves1, f_leaves1)\npickle.dump(depth1, f_depth1)\npickle.dump(ratio1, f_ratio1)\npickle.dump(pairs1, f_pairs1)\n\npickle.dump(acc2, f_acc2)\npickle.dump(leaves2, f_leaves2)\npickle.dump(depth2, f_depth2)\npickle.dump(ratio2, f_ratio2)\npickle.dump(pairs2, f_pairs2)\n\npickle.dump(acc3, f_acc3)\npickle.dump(leaves3, f_leaves3)\npickle.dump(depth3, f_depth3)\npickle.dump(ratio3, f_ratio3)\npickle.dump(pairs3, f_pairs3)\n\n\nf_acc1.close()\nf_leaves1.close()\nf_depth1.close()\nf_ratio1.close()\nf_pairs1.close()\n\n\nf_acc2.close()\nf_leaves2.close()\nf_depth2.close()\nf_ratio2.close()\nf_pairs2.close()\n\nf_acc3.close()\nf_leaves3.close()\nf_depth3.close()\nf_ratio3.close()\nf_pairs3.close()\n","sub_path":"code-experimentations/experimentations/experimentations-artificial-sets.py","file_name":"experimentations-artificial-sets.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"400595801","text":"from django.conf import settings\n\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\n\ndef send_email(to_email, subject, text_content, html_content):\n\n email_user = settings.EMAIL_HOST_USER\n email_password = settings.EMAIL_HOST_PASSWORD\n from_email = 'Charles Vogl'\n\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject\n msg['From'] = from_email\n msg['To'] = to_email\n\n part1 = MIMEText(text_content, 'plain')\n part2 = MIMEText(html_content, 'html')\n\n msg.attach(part1)\n msg.attach(part2)\n\n server = smtplib.SMTP(\"smtp.gmail.com\", settings.EMAIL_PORT)\n server.ehlo()\n server.starttls()\n server.login(email_user, email_password)\n server.sendmail(to_email, to_email, msg.as_string())\n server.close()\n\n return True\n\ndef send_book_download(to_email):\n\n subject = \"The Art of Community (early full book download)\"\n\n text_content = \"You will find the full download of \\\"The Art of Community\\\" at this link:\"\n text_content += \"\\n\\n\"\n text_content += \"https://drive.google.com/file/d/0B5bP-YNgJyn5NmxnLXpudnVNT2M/view\"\n text_content += \"\\n\\n\"\n text_content += \"May it embolden your vision in bringing people together.\"\n text_content += \"\\n\\n\"\n text_content += \"If the book inspires you, please know Amazon Pre-orders are important to show that the world embraces the work. \"\n text_content += \"I will personally be thrilled if you order a copy as a gift to someone making a difference in the world.\"\n text_content += \"\\n\\n\"\n text_content += \"Some wisdom from one of my heroes:\"\n text_content += \"\\n\\n\"\n text_content += \"\\\"It is the reality of personal relationships that saves everything.”\\\"\"\n text_content += \"\\n\"\n text_content += \"- Thomas Merton\"\n text_content += \"\\n\\n\"\n text_content += \"Enjoy.\"\n text_content += \"\\n\\n\"\n text_content += \"-Charles Vogl, M.Div.\\n\"\n text_content += \"Oakland, CA\\n\"\n text_content += \"charlesvogl.com\"\n text_content += \"\\n\\n\"\n text_content += \"P.S. Groups of mission driven leaders can get the gift before the book release. \"\n text_content += \"If you know a group that deserves it, please have them contact us at: team@charlesvogl.com\"\n\n html_content = \"Greetings,\"\n html_content += \"

\"\n html_content += \"You will find the full download of The Art of Community at this link:\"\n html_content += \"

\"\n html_content += \"\"\n html_content += \"The Art of Community: Seven Principles for Belonging\"\n html_content += \"

\"\n html_content += \"May it embolden your vision in bringing people together. \"\n html_content += \"If the book inspires you, please know Amazon Pre-orders are \"\n html_content += \"important to show that the world embraces the work. \"\n html_content += \"I will personally be thrilled if you order a copy as a gift to someone making a difference in the world.\"\n html_content += \"

\"\n html_content += \"Some wisdom from one of my heroes:\"\n html_content += \"

\"\n html_content += \"    \"\n html_content += \"“It is the reality of personal relationships that saves everything.”\"\n html_content += \"
\"\n html_content += \"    \"\n html_content += \"-- Thomas Merton\"\n html_content += \"

\"\n html_content += \"Enjoy.\"\n html_content += \"


\"\n html_content += \"Charles Vogl, M.Div.
\"\n html_content += \"Oakland, CA
\"\n html_content += \"charlesvogl.com\"\n html_content += \"

\"\n html_content += \"P.S. Groups of mission driven leaders can get the gift before the book release. \"\n html_content += \"If you know a group that deserves it, please have them contact us at team@charlesvogl.com\"\n\n send_email(to_email, subject, text_content, html_content)\n","sub_path":"charlesvogl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519167441","text":"#! /usr/bin/env python\nimport sys\n\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n buy1 = -sys.maxint - 1 # min integer\n buy2 = -sys.maxint - 1 # min integer\n sell1 = 0\n sell2 = 0\n\n for curr_price in prices:\n buy1 = max( buy1, 0 - curr_price )\n sell1 = max( sell1, buy1 + curr_price )\n buy2 = max( buy2, sell1 - curr_price )\n sell2 = max( sell2, buy2 + curr_price )\n \n return sell2\n\n\n\nif __name__=='__main__':\n input_1 = [3,3,5,0,0,3,1,4]\n\n sol = Solution()\n maxProfit = sol.maxProfit( input_1 )\n print('Input: {}\\t\\tOutput: {}'.format(input_1, maxProfit) )\n\n input_2 = [1,2,3,4,5]\n maxProfit = sol.maxProfit( input_2 )\n print('Input: {}\\t\\tOutput: {}'.format(input_2, maxProfit) )\n\n input_3 = [7,6,4,3,1]\n maxProfit = sol.maxProfit( input_3 )\n print('Input: {}\\t\\tOutput: {}'.format(input_3, maxProfit) )\n","sub_path":"scripts/Array/123_Best_Time_to_Buy_and_Sell_Stock_III/123_Best_Time_to_Buy_and_Sell_Stock_III.py","file_name":"123_Best_Time_to_Buy_and_Sell_Stock_III.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"324911859","text":"import json\nimport os\nimport shutil\nimport tarfile\nimport time\nimport uuid\nfrom tempfile import gettempdir\nfrom tempfile import NamedTemporaryFile\n\nimport pytest\nfrom ibutsu_client import ApiClient\nfrom ibutsu_client import ApiException\nfrom ibutsu_client import ArtifactApi\nfrom ibutsu_client import Configuration\nfrom ibutsu_client import HealthApi\nfrom ibutsu_client import ResultApi\nfrom ibutsu_client import RunApi\nfrom urllib3.exceptions import MaxRetryError\n\n# A list of markers that can be filtered out\nFILTERED_MARKERS = [\"parametrize\"]\nCA_BUNDLE_ENVS = [\"REQUESTS_CA_BUNDLE\", \"IBUTSU_CA_BUNDLE\"]\n\n# Convert the blocker category into an Ibutsu Classification\nBLOCKER_CATEGORY_TO_CLASSIFICATION = {\n \"automation-issue\": \"test_failure\",\n \"environment-issue\": \"environment_failure\",\n \"product-issue\": \"product_failure\",\n \"product-rfe\": \"product_rfe\",\n}\n\n# Place a limit on the file-size we can upload for artifacts\nUPLOAD_LIMIT = 256 * 1024 # 256 KiB\n\n\ndef safe_string(o):\n \"\"\"This will make string out of ANYTHING without having to worry about the stupid Unicode errors\n\n This function tries to make str/unicode out of ``o`` unless it already is one of those and then\n it processes it so in the end there is a harmless ascii string.\n\n Args:\n o: Anything.\n \"\"\"\n if not isinstance(o, str):\n o = str(o)\n if isinstance(o, bytes):\n o = o.decode(\"utf-8\", \"ignore\")\n o = o.encode(\"ascii\", \"xmlcharrefreplace\").decode(\"ascii\")\n return o\n\n\ndef merge_dicts(old_dict, new_dict):\n for key, value in old_dict.items():\n if key not in new_dict:\n new_dict[key] = value\n elif isinstance(value, dict):\n merge_dicts(value, new_dict[key])\n\n\ndef parse_data_option(data_list):\n if not data_list:\n return {}\n data_dict = {}\n for data_str in data_list:\n if not data_str:\n continue\n key_str, value = data_str.split(\"=\", 1)\n keys = key_str.split(\".\")\n current_item = data_dict\n for key in keys[:-1]:\n if key not in current_item:\n current_item[key] = {}\n current_item = current_item[key]\n key = keys[-1]\n current_item[key] = value\n return data_dict\n\n\ndef get_test_idents(item):\n try:\n return item.location[2], item.location[0]\n except AttributeError:\n try:\n return item.fspath.strpath, None\n except AttributeError:\n return (None, None)\n\n\ndef get_name(obj):\n return getattr(obj, \"_param_name\", None) or getattr(obj, \"name\", None) or str(obj)\n\n\ndef overall_test_status(statuses):\n # Handle some logic for when to count certain tests as which state\n for when, status in statuses.items():\n if when == \"call\" and status[1] and status[0] == \"skipped\":\n return \"xfailed\"\n elif when == \"call\" and status[1] and status[0] == \"passed\":\n return \"xpassed\"\n elif (when == \"setup\" or when == \"teardown\") and status[0] == \"failed\":\n return \"error\"\n elif status[0] == \"skipped\":\n return \"skipped\"\n elif when == \"call\" and status[0] == \"failed\":\n return \"failed\"\n return \"passed\"\n\n\nclass IbutsuArchiver(object):\n \"\"\"\n Save all Ibutsu results to archive\n \"\"\"\n\n _start_time = None\n _stop_time = None\n frontend = None\n\n def __init__(self, source=None, path=None, extra_data=None):\n self._results = {}\n self._run_id = None\n self.run = None\n self.temp_path = path\n self.source = source or \"local\"\n self.extra_data = extra_data or {}\n\n # Set an env var ID\n if os.environ.get(\"IBUTSU_ENV_ID\"):\n self.extra_data.update({\"env_id\": os.environ.get(\"IBUTSU_ENV_ID\")})\n # Auto-detect running in Jenkins and add to the metadata\n if os.environ.get(\"JOB_NAME\") and os.environ.get(\"BUILD_NUMBER\"):\n self.extra_data.update(\n {\n \"jenkins\": {\n \"job_name\": os.environ.get(\"JOB_NAME\"),\n \"build_number\": os.environ.get(\"BUILD_NUMBER\"),\n \"build_url\": os.environ.get(\"BUILD_URL\"),\n }\n }\n )\n # If the project is set via environment variables\n if os.environ.get(\"IBUTSU_PROJECT\"):\n self.extra_data.update({\"project\", os.environ.get(\"IBUTSU_PROJECT\")})\n\n def _status_to_summary(self, status):\n return {\n \"failed\": \"failures\",\n \"error\": \"errors\",\n \"skipped\": \"skips\",\n \"xfailed\": \"xfailures\",\n \"xpassed\": \"xpasses\",\n \"tests\": \"tests\",\n }.get(status)\n\n def _save_run(self, run):\n if not self.temp_path:\n self.temp_path = os.path.join(gettempdir(), run[\"id\"])\n os.makedirs(self.temp_path, exist_ok=True)\n if not run.get(\"metadata\"):\n run[\"metadata\"] = {}\n run[\"metadata\"].update(self.extra_data)\n with open(os.path.join(self.temp_path, \"run.json\"), \"w\") as f:\n json.dump(run, f)\n\n @property\n def run_id(self):\n if not self._run_id:\n raise Exception(\"You need to use set_run_id() to set a run ID\")\n return self._run_id\n\n @property\n def duration(self):\n if self._start_time and self._stop_time:\n return self._stop_time - self._start_time\n elif self._start_time:\n return time.time() - self._start_time\n else:\n return 0\n\n def start_timer(self):\n if not self._start_time:\n self._start_time = time.time()\n\n def stop_timer(self):\n if not self._stop_time:\n self._stop_time = time.time()\n\n def shutdown(self):\n # Gather the summary before building the archive\n summary = {\"failures\": 0, \"skips\": 0, \"errors\": 0, \"xfailures\": 0, \"xpasses\": 0, \"tests\": 0}\n for result in self._results.values():\n key = self._status_to_summary(result[\"result\"])\n if key in summary:\n summary[key] += 1\n summary[\"tests\"] += 1\n self.run[\"summary\"] = summary\n self.update_run()\n # Build the tarball\n self.tar_file = os.path.join(os.path.abspath(\".\"), f\"{self.run_id}.tar.gz\")\n print(\"Creating archive {}...\".format(os.path.basename(self.tar_file)))\n with tarfile.open(self.tar_file, \"w:gz\") as tar:\n tar.add(self.temp_path, self.run_id)\n\n def output_msg(self):\n if hasattr(self, \"tar_file\"):\n print(f\"Saved results archive to {self.tar_file}\")\n\n def get_run_id(self):\n if not self.run:\n run = {\n \"duration\": 0,\n \"summary\": {\n \"failures\": 0,\n \"skips\": 0,\n \"errors\": 0,\n \"xfailures\": 0,\n \"xpasses\": 0,\n \"tests\": 0,\n },\n \"metadata\": self.extra_data,\n \"source\": getattr(self, \"source\", \"local\"),\n \"start_time\": time.time(),\n }\n self.run = self.add_run(run=run)\n return self.run[\"id\"]\n\n def set_run_id(self, run_id):\n self._run_id = run_id\n self.refresh_run()\n\n def add_run(self, run=None):\n if not run.get(\"id\"):\n run[\"id\"] = str(uuid.uuid4())\n if not run.get(\"source\"):\n run[\"source\"] = self.source\n self._save_run(run)\n return run\n\n def refresh_run(self):\n \"\"\"This does nothing, there's nothing to do here\"\"\"\n pass\n\n def update_run(self, duration=None):\n if duration:\n self.run[\"duration\"] = duration\n self._save_run(self.run)\n\n def add_result(self, result):\n result_id = result.get(\"id\")\n if not result_id:\n result_id = str(uuid.uuid4())\n result[\"id\"] = result_id\n art_path = os.path.join(self.temp_path, result_id)\n os.makedirs(art_path, exist_ok=True)\n if not result.get(\"metadata\"):\n result[\"metadata\"] = {}\n result[\"metadata\"].update(self.extra_data)\n with open(os.path.join(art_path, \"result.json\"), \"w\") as f:\n json.dump(result, f)\n self._results[result_id] = result\n return result\n\n def update_result(self, id, result):\n art_path = os.path.join(self.temp_path, id)\n os.makedirs(art_path, exist_ok=True)\n if not result.get(\"metadata\"):\n result[\"metadata\"] = {}\n result[\"metadata\"].update(self.extra_data)\n with open(os.path.join(art_path, \"result.json\"), \"w\") as f:\n json.dump(result, f)\n self._results[id] = result\n\n def upload_artifact(self, id, filename, data):\n file_size = os.stat(data).st_size\n if file_size < UPLOAD_LIMIT:\n art_path = os.path.join(self.temp_path, id)\n os.makedirs(art_path, exist_ok=True)\n shutil.copyfile(data, os.path.join(art_path, filename))\n else:\n print(\n f\"File '{filename}' of size '{file_size}' bytes\"\n f\" exceeds global Ibutsu upload limit of '{UPLOAD_LIMIT}' bytes.\"\n f\" File will not be uploaded to Ibutsu.\"\n )\n\n def upload_artifact_raw(self, res_id, filename, data):\n file_object = NamedTemporaryFile(delete=False)\n os_file_name = file_object.name\n file_object.write(data)\n file_object.close()\n self.upload_artifact(res_id, filename, os_file_name)\n\n def upload_artifact_from_file(self, res_id, logged_filename, filename):\n self.upload_artifact(res_id, logged_filename, filename)\n\n def get_skip_reason(self, data, report):\n skip_reason = None\n # first see if the reason is in the marker skip\n if data[\"metadata\"].get(\"markers\"):\n for marker in data[\"metadata\"][\"markers\"]:\n if marker.get(\"name\") == \"skipif\":\n skip_reason = marker[\"kwargs\"].get(\"reason\")\n elif marker.get(\"name\") == \"skip\":\n try:\n skip_reason = marker[\"args\"][0]\n except IndexError:\n pass\n # otherwise we must use the report to get the skip information\n else:\n try:\n if report.longrepr:\n skip_reason = report.longrepr[2].split(\"Skipped: \")[1]\n except IndexError:\n pass\n return skip_reason\n\n def get_skip_classification(self, skip_reason):\n \"\"\" Get the skip classification and category from the skip_reason\"\"\"\n category = None\n try:\n category = skip_reason.split(\"category:\")[1].strip()\n except IndexError:\n pass\n return BLOCKER_CATEGORY_TO_CLASSIFICATION.get(category)\n\n @pytest.mark.tryfirst\n def pytest_collection_modifyitems(self, items):\n for item in items:\n data = getattr(item, \"_ibutsu\", {})\n new_data = {\"id\": None, \"data\": {\"metadata\": {}}, \"artifacts\": {}}\n merge_dicts(data, new_data)\n item._ibutsu = new_data\n\n @pytest.mark.hookwrapper\n def pytest_runtest_protocol(self, item):\n if hasattr(item, \"callspec\"):\n try:\n params = {p: get_name(v) for p, v in item.callspec.params.items()}\n except Exception:\n params = {}\n else:\n params = {}\n start_time = time.time()\n fspath = item.location[0] or item.fspath.strpath\n if \"site-packages/\" in fspath:\n fspath = fspath[fspath.find(\"site-packages/\") + 14 :]\n data = {\n \"result\": \"failed\",\n \"source\": getattr(self, \"source\", \"local\"),\n \"params\": params,\n \"starttime\": start_time,\n \"start_time\": start_time,\n \"test_id\": get_test_idents(item)[0],\n \"metadata\": {\n \"statuses\": {},\n \"run\": self.run_id,\n \"durations\": {},\n \"fspath\": fspath,\n \"markers\": [\n {\"name\": m.name, \"args\": m.args, \"kwargs\": m.kwargs}\n for m in item.iter_markers()\n if m.name not in FILTERED_MARKERS\n ],\n },\n }\n\n def _default(obj):\n if callable(obj) and hasattr(obj, \"__code__\"):\n return f\"function: '{obj.__name__}', args: {str(obj.__code__.co_varnames)}\"\n else:\n return str(obj)\n\n # serialize the metadata just in case of any functions present\n data[\"metadata\"] = json.loads(json.dumps(data[\"metadata\"], default=_default))\n result = self.add_result(result=data)\n item._ibutsu[\"id\"] = result[\"id\"]\n # Update result data\n old_data = item._ibutsu[\"data\"]\n merge_dicts(old_data, data)\n item._ibutsu[\"data\"] = data\n yield\n\n def pytest_exception_interact(self, node, call, report):\n if not hasattr(report, \"_ibutsu\"):\n return\n val = safe_string(call.excinfo.value)\n last_lines = \"\\n\".join(report.longreprtext.split(\"\\n\")[-4:])\n short_tb = \"{}\\n{}\\n{}\".format(\n last_lines, call.excinfo.type.__name__, val.encode(\"ascii\", \"xmlcharrefreplace\")\n )\n id = report._ibutsu[\"id\"]\n data = report._ibutsu[\"data\"]\n self.upload_artifact_raw(id, \"traceback.log\", bytes(report.longreprtext, \"utf8\"))\n data[\"metadata\"][\"short_tb\"] = short_tb\n data[\"metadata\"][\"exception_name\"] = call.excinfo.type.__name__\n self.update_result(id, result=data)\n\n def pytest_runtest_logreport(self, report):\n if not hasattr(report, \"_ibutsu\"):\n return\n\n if hasattr(report, \"wasxfail\"):\n xfail = True\n else:\n xfail = False\n\n id = report._ibutsu[\"id\"]\n data = report._ibutsu[\"data\"]\n data[\"metadata\"][\"user_properties\"] = {key: value for key, value in report.user_properties}\n data[\"metadata\"][\"statuses\"][report.when] = (report.outcome, xfail)\n data[\"metadata\"][\"durations\"][report.when] = report.duration\n data[\"result\"] = overall_test_status(data[\"metadata\"][\"statuses\"])\n if data[\"result\"] == \"skipped\" and not data[\"metadata\"].get(\"skip_reason\"):\n skip_reason = self.get_skip_reason(data, report)\n if skip_reason:\n data[\"metadata\"][\"skip_reason\"] = skip_reason\n classification = self.get_skip_classification(skip_reason)\n if classification:\n data[\"metadata\"][\"classification\"] = classification\n data[\"duration\"] = sum([v for v in data[\"metadata\"][\"durations\"].values()])\n self.update_result(id, result=data)\n\n def pytest_sessionfinish(self):\n self.stop_timer()\n self.update_run(duration=self.duration)\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtest_makereport(self, item, call):\n outcome = yield\n res = outcome.get_result() # will raise if outcome was exception\n res._ibutsu = item._ibutsu\n\n\nclass IbutsuSender(IbutsuArchiver):\n \"\"\"\n An enhanced Ibutsu plugin that also sends Ibutsu results to an Ibutsu server\n \"\"\"\n\n def __init__(self, server_url, source=None, path=None, extra_data=None):\n self.server_url = server_url\n self._has_server_error = False\n self._server_error_tbs = []\n self._sender_cache = []\n\n config = Configuration()\n config.host = self.server_url\n # Only set the SSL CA cert if one of the environment variables is set\n for env_var in CA_BUNDLE_ENVS:\n if os.getenv(env_var, None):\n config.ssl_ca_cert = os.getenv(env_var)\n\n api_client = ApiClient(config)\n self.result_api = ResultApi(api_client)\n self.artifact_api = ArtifactApi(api_client)\n self.run_api = RunApi(api_client)\n self.health_api = HealthApi(api_client)\n super().__init__(source=source, path=path, extra_data=extra_data)\n\n def _make_call(self, api_method, *args, **kwargs):\n for res in self._sender_cache:\n if res.ready():\n self._sender_cache.remove(res)\n try:\n out = api_method(*args, **kwargs)\n if \"async_req\" in kwargs:\n self._sender_cache.append(out)\n return out\n except (MaxRetryError, ApiException) as e:\n self._has_server_error = self._has_server_error or True\n self._server_error_tbs.append(str(e))\n return None\n\n def add_run(self, run=None):\n server_run = self._make_call(self.run_api.add_run, run=run)\n if server_run:\n run = server_run.to_dict()\n return super().add_run(run)\n\n def refresh_run(self):\n # This can safely completely override the underlying method, because it does nothing\n if not self.run_id:\n return\n server_run = self._make_call(self.run_api.get_run, self.run_id)\n if server_run:\n self.run = server_run.to_dict()\n\n def update_run(self, duration=None):\n super().update_run(duration)\n self._make_call(self.run_api.update_run, self.run[\"id\"], run=self.run)\n\n def add_result(self, result):\n if not result.get(\"metadata\"):\n result[\"metadata\"] = {}\n result[\"metadata\"].update(self.extra_data)\n server_result = self._make_call(self.result_api.add_result, result=result)\n if server_result:\n result.update(server_result.to_dict())\n return super().add_result(result)\n\n def update_result(self, id, result):\n self._make_call(self.result_api.update_result, id, result=result, async_req=True)\n super().update_result(id, result)\n\n def upload_artifact(self, id, filename, data):\n super().upload_artifact(id, filename, data)\n file_size = os.stat(data).st_size\n if file_size < UPLOAD_LIMIT:\n self._make_call(self.artifact_api.upload_artifact, id, filename, data)\n\n def output_msg(self):\n with open(\".last-ibutsu-run-id\", \"w\") as f:\n f.write(self.run_id)\n url = f\"{self.frontend}/runs/{self.run_id}\"\n with open(\".last-ibutsu-run-url\", \"w\") as f:\n f.write(url)\n if not self._has_server_error:\n print(f\"Results can be viewed on: {url}\")\n else:\n print(\n \"There was an error while uploading results,\"\n \" and not all results were uploaded to the server.\"\n )\n print(f\"All results were written to archive, partial results can be viewed on: {url}\")\n super().output_msg()\n\n def shutdown(self):\n super().shutdown()\n print(f\"Ibutsu client finishing up...({len(self._sender_cache)} tasks left)...\")\n while self._sender_cache:\n for res in self._sender_cache:\n if res.ready():\n self._sender_cache.remove(res)\n time.sleep(0.1)\n print(\"Cleanup complete\")\n\n\ndef pytest_addoption(parser):\n parser.addini(\"ibutsu_server\", help=\"The Ibutsu server to connect to\")\n parser.addini(\"ibutsu_source\", help=\"The source of the test run\")\n parser.addini(\"ibutsu_metadata\", help=\"Extra metadata to include with the test results\")\n parser.addini(\"ibutsu_project\", help=\"Project ID or name\")\n group = parser.getgroup(\"ibutsu\")\n group.addoption(\n \"--ibutsu\",\n dest=\"ibutsu_server\",\n action=\"store\",\n metavar=\"URL\",\n default=None,\n help=\"URL for the Ibutsu server\",\n )\n group.addoption(\n \"--ibutsu-source\",\n dest=\"ibutsu_source\",\n action=\"store\",\n metavar=\"SOURCE\",\n default=None,\n help=\"set the source for the tests\",\n )\n group.addoption(\n \"--ibutsu-data\",\n dest=\"ibutsu_data\",\n action=\"store\",\n metavar=\"KEY=VALUE\",\n nargs=\"*\",\n help=\"extra metadata for the test result, key=value\",\n )\n group.addoption(\n \"--ibutsu-project\",\n dest=\"ibutsu_project\",\n action=\"store\",\n metavar=\"PROJECT\",\n default=None,\n help=\"project id or name\",\n )\n\n\n@pytest.hookimpl(optionalhook=True)\ndef pytest_configure_node(node):\n if not hasattr(node.config, \"_ibutsu\"):\n # If this plugin is not active\n return\n node.workerinput[\"run_id\"] = node.config._ibutsu.run_id\n\n\ndef pytest_configure(config):\n ibutsu_server = config.getoption(\"ibutsu_server\", None)\n if config.getini(\"ibutsu_server\"):\n ibutsu_server = config.getini(\"ibutsu_server\")\n if not ibutsu_server:\n return\n ibutsu_source = config.getoption(\"ibutsu_source\", None)\n if config.getini(\"ibutsu_source\"):\n ibutsu_source = config.getini(\"ibutsu_source\")\n ibutsu_data = parse_data_option(config.getoption(\"ibutsu_data\", []))\n ibutsu_project = config.getoption(\"ibutsu_project\", None)\n if config.getini(\"ibutsu_project\"):\n ibutsu_project = config.getini(\"ibutsu_project\")\n if ibutsu_project:\n ibutsu_data.update({\"project\": ibutsu_project})\n if ibutsu_server != \"archive\":\n try:\n print(\"Ibutsu server: {}\".format(ibutsu_server))\n if ibutsu_server.endswith(\"/\"):\n ibutsu_server = ibutsu_server[:-1]\n if not ibutsu_server.endswith(\"/api\"):\n ibutsu_server += \"/api\"\n ibutsu = IbutsuSender(ibutsu_server, ibutsu_source, extra_data=ibutsu_data)\n ibutsu.frontend = ibutsu.health_api.get_health_info().frontend\n except MaxRetryError:\n print(\"Connection failure in health check - switching to archiver\")\n ibutsu = IbutsuArchiver(extra_data=ibutsu_data)\n except ApiException:\n print(\"Error in call to Ibutsu API\")\n ibutsu = IbutsuArchiver(extra_data=ibutsu_data)\n else:\n ibutsu = IbutsuArchiver(extra_data=ibutsu_data)\n if config.pluginmanager.has_plugin(\"xdist\"):\n if hasattr(config, \"workerinput\") and config.workerinput.get(\"run_id\"):\n ibutsu.set_run_id(config.workerinput[\"run_id\"])\n else:\n ibutsu.set_run_id(ibutsu.get_run_id())\n config._ibutsu = ibutsu\n config.pluginmanager.register(config._ibutsu)\n\n\ndef pytest_collection_finish(session):\n if not hasattr(session.config, \"_ibutsu\"):\n # If this plugin is not active\n return\n ibutsu = session.config._ibutsu\n if not session.config.pluginmanager.has_plugin(\"xdist\"):\n ibutsu.set_run_id(ibutsu.get_run_id())\n ibutsu.start_timer()\n ibutsu.output_msg()\n\n\ndef pytest_unconfigure(config):\n ibutsu_instance = getattr(config, \"_ibutsu\", None)\n if ibutsu_instance:\n del config._ibutsu\n config.pluginmanager.unregister(ibutsu_instance)\n ibutsu_instance.shutdown()\n if ibutsu_instance.run_id:\n ibutsu_instance.output_msg()\n","sub_path":"pytest_ibutsu.py","file_name":"pytest_ibutsu.py","file_ext":"py","file_size_in_byte":23056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"4181145","text":"# 함수 반환값\n\n\ndef getSum(start, end):\n sum = 0\n for i in range(start, end, 1):\n sum = sum + i\n\n return sum\n\n\nvalue = getSum(1, 10)\nprint( value ) # 55\n\n\ndef getMax(a, b):\n result = 0\n if a > b:\n result = a\n else:\n result = b\n return result\n\nvalue = getMax(1, 10)\nprint( value ) # 10","sub_path":"python20200322-master/class_Python기초/py10함수/py10_07_반환값.py","file_name":"py10_07_반환값.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"204433121","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy import Request\nimport re\nfrom crazy.items import ImageItem\nfrom scrapy.contrib.loader import ItemLoader\nimport urlparse\n\nclass FirstSpider(scrapy.Spider):\n name = \"first\"\n allowed_domains = [\"1024.c2048ao.pw/\"]\n start_urls = ['http://1024.c2048ao.pw/pw/thread.php?fid=16']\n download_delay = 2\n\n def parse(self, response):\n cate = response.xpath('//td[@style=\"text-align:left;padding-left:8px\"]/h3/a/@href').extract()\n url_content = urlparse.urlparse(response.url)\n scheme = url_content.scheme\n net_location = url_content.netloc\n for link in cate:\n if re.findall(r\"htm_data\",link) == '':\n continue\n else:\n url = scheme + \"://\" + net_location + \"/pw/\" + link\n yield Request(url, callback=self.download_image,dont_filter=True)\n #\n # request.meta['*'] = item\n # return request\n\n def download_image(self,response):\n item = ImageItem()\n srcs = response.xpath('//div[@class=\"tpc_content\"]/a/img/@src').extract()\n item['image_urls'] = srcs\n yield item\n # yield {\"test\" : srcs}\n","sub_path":"PythonProjects/pyscrpay/crazy/crazy/spiders/country.py","file_name":"country.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127804785","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom anvil.actions import install\nfrom anvil.actions import package\nfrom anvil.actions import start\nfrom anvil.actions import status\nfrom anvil.actions import stop\nfrom anvil.actions import test\nfrom anvil.actions import uninstall\n\n\n_NAMES_TO_RUNNER = {\n 'install': install.InstallAction,\n 'package': package.PackageAction,\n 'start': start.StartAction,\n 'status': status.StatusAction,\n 'stop': stop.StopAction,\n 'test': test.TestAction,\n 'uninstall': uninstall.UninstallAction,\n}\n_RUNNER_TO_NAMES = dict((v, k) for k, v in _NAMES_TO_RUNNER.items())\n\n\ndef names():\n \"\"\"\n Returns a list of the available action names.\n \"\"\"\n return list(sorted(_NAMES_TO_RUNNER.keys()))\n\n\ndef class_for(action):\n \"\"\"\n Given an action name, look up the factory for that action runner.\n \"\"\"\n try:\n return _NAMES_TO_RUNNER[action]\n except KeyError:\n raise RuntimeError('Unrecognized action %s' % action)\n","sub_path":"anvil/actions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"568222023","text":"from itertools import tee\nimport json\nimport logging\nimport os\nimport re\n\nimport bs4\nimport gensim\nfrom nltk.collocations import TrigramCollocationFinder\nfrom nltk.metrics import BigramAssocMeasures, TrigramAssocMeasures\nimport numpy as np\nimport pandas as pd\nfrom textblob import TextBlob\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\ndef unzip(pairs):\n a, b = tee(pairs)\n return (_[0] for _ in a), (_[1] for _ in b)\n\ndef html2text(html):\n soup = bs4.BeautifulSoup(html)\n for s in soup('script'):\n s.extract()\n return soup.text\n\ndef collocations(stream, top_n=10000, min_bigram_freq=50, min_trigram_freq=20):\n \"\"\"Extract text collocations (bigrams and trigrams), from a stream of words.\n\n Parameters\n ----------\n stream: iterable object\n An iterable of words\n\n top_n: int\n Number of collocations to retrieve from the stream of words (order by decreasing frequency). Default is 10000\n\n min_bigram_freq: int\n Minimum frequency of a bigram in order to retrieve it. Default is 50.\n\n min_trigram_freq: int\n Minimum frequency of a trigram in order to retrieve it. Default is 20.\n\n \"\"\"\n tcf = TrigramCollocationFinder.from_words(stream)\n\n tcf.apply_freq_filter(min_trigram_freq)\n trigrams = [' '.join(w) for w in tcf.nbest(TrigramAssocMeasures.chi_sq, top_n)]\n logging.info(\"%i trigrams found: %s...\" % (len(trigrams), trigrams[:20]))\n\n bcf = tcf.bigram_finder()\n bcf.apply_freq_filter(min_bigram_freq)\n bigrams = [' '.join(w) for w in bcf.nbest(BigramAssocMeasures.pmi, top_n)]\n logging.info(\"%i bigrams found: %s...\" % (len(bigrams), bigrams[:20]))\n\n bigrams_patterns = re.compile('(%s)' % '|'.join(bigrams), re.UNICODE)\n trigrams_patterns = re.compile('(%s)' % '|'.join(trigrams), re.UNICODE)\n\n return bigrams_patterns, trigrams_patterns\n\n\ndef entities(document_stream, freq_min=2, freq_max=10000):\n \"\"\"Return noun phrases from stream of documents.\n\n Parameters\n ----------\n document_stream: iterable object\n\n freq_min: int\n Minimum frequency of a noun phrase occurrences in order to retrieve it. Default is 2.\n\n freq_max: int\n Maximum frequency of a noun phrase occurrences in order to retrieve it. Default is 10000.\n\n \"\"\"\n np_counts_total = {}\n for docno, doc in enumerate(document_stream):\n # print \"DocNo: \" + str(docno)\n # print \"Doc: \" + str(doc)\n doc = str(doc)\n docno += 1\n if docno % 1000 == 0:\n sorted_phrases = sorted(np_counts_total.items(), \n key=lambda item: -item[1])\n np_counts_total = dict(sorted_phrases)\n logging.info(\"at document #%i, considering %i phrases: %s...\" %\n (docno, len(np_counts_total), sorted_phrases[0]))\n\n for np in TextBlob(doc).noun_phrases:\n np_counts_total[np] = np_counts_total.get(np, 0) + 1\n\n # Remove noun phrases in the list that have higher frequencies than 'freq_max' or lower frequencies than 'freq_min'\n np_counts = {}\n for np, count in np_counts_total.items():\n if freq_max >= count >= freq_min:\n np_counts[np] = count\n\n return set(np_counts)\n\n\ndef get_document_length(corpus_bow, folder):\n corpus_file = corpus_bow.filename\n corpus = gensim.corpora.MmCorpus(corpus_file)\n doc_length = []\n with open(os.path.join(folder, 'doc_length'), 'w') as f:\n for document in corpus:\n n_tokens = len(document)\n doc_length.append(n_tokens)\n f.write(\"%s\\n\" % n_tokens)\n\n return doc_length\n\n\ndef to_r_ldavis(corpus_bow, lda, dir_name):\n \"\"\"Generate the input that the R package LDAvis needs.\n\n Parameters\n ----------\n corpus_bow: topik.vectorizers.CorpusBOW\n The corpus bag-of-words representation\n\n lda: topik.models.LDA\n LDA model\n\n dir_name: string\n Directory name where to store the files required in R package LDAvis.\n\n \"\"\"\n if os.path.isdir(dir_name):\n pass\n else:\n os.makedirs(dir_name)\n doc_length = get_document_length(corpus_bow, dir_name)\n\n corpus_dict = corpus_bow.dict\n corpus_dict.save_as_text(os.path.join(dir_name,'dictionary'), sort_by_word=False)\n\n df = pd.read_csv(os.path.join(dir_name,'dictionary'), sep='\\t', index_col=0, header=None)\n df = df.sort_index()\n\n df[2].to_csv(os.path.join(dir_name,'term_frequency'), index=False)\n df[1].to_csv(os.path.join(dir_name,'vocab'), index=False, header=False)\n\n tt_dist = np.array(lda.model.expElogbeta)\n np.savetxt(os.path.join(dir_name,'topicTermDist'), tt_dist, delimiter=',', newline='\\n',)\n\n corpus_file = corpus_bow.filename\n corpus = gensim.corpora.MmCorpus(corpus_file)\n docTopicProbMat = lda.model[corpus]\n gensim.corpora.MmCorpus.serialize(os.path.join(dir_name,'docTopicProbMat.mm'), docTopicProbMat)\n\n\ndef generate_csv_output_file(reader, tokenizer, corpus_bow, lda_model, output_file='output.csv'):\n \"\"\"Utility function to retrieve the results of your topic modeling in a csv file.\n Uses a pandas.DataFrame, only useful for smaller datasets.\n\n Parameters\n ----------\n reader: topik.readers\n tokenizer: topik.tokenizer\n corpus_bow: topik.vectorizer.CorpusBOW\n lda: topik.models.LDA\n output_file: string\n Desired name for your output file\n\n Returns\n -------\n pandas.DataFrame\n A pandas.DataFrame with fields:\n `text`: The original text content of the document\n `tokens`: The tokens extracted from the text\n `lda_probabilities`: A list of topic number and probability of the document belonging to each of the topics.\n `topic_group`: Topic with max. probability\n\n \"\"\"\n logging.info(\"getting output file %s \" %output_file)\n documents = []\n\n with open(output_file, 'w') as wfile:\n #for fullpath, content in reader:3\n for content in reader:\n document = {}\n document['text'] = content\n tokens = tokenizer.tokenize(content)\n document['tokens'] = tokens\n bow_document = corpus_bow.dict.doc2bow(tokens)\n document['lda_probabilities'] = lda_model[bow_document]\n document['topic_group'] = max(lda_model[bow_document], key=lambda item: item[1])[0]\n wfile.write(json.dumps(document))\n wfile.write('\\n')\n documents.append(document)\n\n df = pd.DataFrame(documents)\n logging.info(\"writing dataframe to output file %s \" %output_file)\n df.to_csv(output_file, sep='\\t', encoding='utf-8')\n return pd.DataFrame(documents)\n\n \n","sub_path":"static/custom/process/topik/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47326852","text":"#!/usr/bin/env python\nimport json\nimport subprocess\nimport os\n\nhome = os.path.expanduser('~')\nscript_dir = os.path.dirname(os.path.realpath(__file__))\n\ndef write_ssh_file(filename):\n if not os.path.isfile(home + \"/.ssh/key_\" + filename):\n try:\n subprocess.call('ssh-keygen -t ed25519 -a 100 -N \"\" -f ~/.ssh/key_' + filename, shell=True)\n except:\n return False\n return True\n\n\ndef add_host_to_file(name, port, user, address, key):\n hostSection = \"\"\n hostSection+=('Host ' + name + '\\n')\n hostSection+=('\\tHostName ' + address + '\\n')\n hostSection+=('\\tPort ' + str(port) + '\\n')\n hostSection+=('\\tUser ' + user + '\\n')\n hostSection+=('\\tIdentityFile ~/.ssh/' + key + '\\n')\n return hostSection\n\nif not os.path.exists(script_dir + '/hosts.json'):\n print(\"Couldn't find hosts.json in \" + script_dir)\n exit()\n\nwith open(script_dir + '/hosts.json') as hosts:\n data = json.load(hosts)\n home = os.path.expanduser('~')\n public_keys = []\n configFilePath = script_dir + '/ssh-config'\n configFileContents = \"\"\n\n if not os.path.exists(home + '/.ssh'):\n os.makedirs(home + '/.ssh')\n configFileContents+=('#THIS FILE WAS GENERATED BY ' + os.path.basename(__file__) + '\\n')\n external_address = data['external-address']\n\n # AWS CodeCommit User\n CODE_COMMIT = 'code-commit'\n if write_ssh_file(CODE_COMMIT):\n publickeyfile = open(home + '/.ssh/key_' + CODE_COMMIT + '.pub', 'r')\n public_keys.append({'name': CODE_COMMIT, 'pubkey': publickeyfile.read()});\n publickeyfile.close()\n configFileContents+=('Host git-codecommit.*.amazonaws.com\\n')\n configFileContents+=('\\tUser Your-IAM-SSH-Key-ID-Here\\n')\n configFileContents+=('\\tIdentityFile ~/.ssh/key_' + CODE_COMMIT + '\\n')\n\n # Github User\n GITHUB = 'github'\n if write_ssh_file(GITHUB):\n publickeyfile = open(home + '/.ssh/key_' + GITHUB + '.pub', 'r')\n public_keys.append({'name': GITHUB, 'pubkey': publickeyfile.read()});\n publickeyfile.close()\n configFileContents+=('Host github.com\\n')\n configFileContents+=('\\tHostName github.com\\n')\n configFileContents+=('\\tUser git\\n')\n configFileContents+=('\\tIdentityFile ~/.ssh/key_' + GITHUB + '\\n')\n\n for host in data['hosts']:\n name = host['hostname']\n port = host['port']\n user = host['user']\n description = host['description']\n address = host.get('address', external_address)\n alias = name\n #if no address specified, assume we want to hit the external IP\n if address is external_address:\n name = name + '-external'\n\n if alias and name and description and port and user and address and write_ssh_file(alias):\n configFileContents+=('#' + description + '\\n')\n configFileContents+=add_host_to_file(name, port, user, address, 'key_' + alias)\n publickeyfile = open(home + '/.ssh/key_' + alias + '.pub', 'r')\n public_keys.append({'name': name, 'pubkey': publickeyfile.read()})\n publickeyfile.close()\n else:\n print ('Couldn\\'t write host ' + name + ' to file.')\n\n print ('\\n------------------------------------------------------------\\n')\n print (\"Add these public keys to authorized_keys of your host:\")\n print ('\\n------------------------------------------------------------\\n')\n for key in public_keys:\n print (key['name'] + '\\n' + key['pubkey'])\n\n if os.path.exists(configFilePath)or os.path.exists(home + \"/.ssh/config\"):\n print ('\\n------------------------------------------------------------\\n')\n print ('Config file already exists; here are the contents we would add.')\n print ('\\n------------------------------------------------------------\\n')\n print (configFileContents)\n else:\n with open(configFilePath,'w+') as config:\n config.write(configFileContents)\n config.close()\n subprocess.call('ln -s ' + script_dir + '/ssh-config' + ' ~/.ssh/config', shell=True)\n\n hosts.close()\n","sub_path":"ssh/generate_ssh_config.py","file_name":"generate_ssh_config.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"427373344","text":"#largest continuous sum\n\ndef largestsum(arr):\n if len(arr)==0:\n return \"wrong input array\"\n else:\n max_sum = curr_sum = arr[0]\n \n for num in arr[1:]:\n curr_sum = max(curr_sum+num,num)\n max_sum = max(curr_sum,max_sum)\n return max_sum\n \nprint(largestsum(arr)) \n \n \n","sub_path":"Arrays/Largestcontinuoussum.py","file_name":"Largestcontinuoussum.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277441923","text":"from lxml import etree\r\nimport mwparserfromhell\r\nf = open('C:\\\\Users\\\\Sagebrecht\\\\Desktop\\\\nodes.txt','a')\r\n#C:\\Users\\Sagebrecht\\Desktop\\WikiFiles\\split42043.xml\r\nfor x in range(42041, 46670): #change range to first number and second to range plus 1\r\n if x % 2 == 1:\r\n testobj = etree.parse('C:\\\\Users\\\\Sagebrecht\\\\Desktop\\\\WikiFiles\\\\split' + str(x) + '.xml') #change path to match where the wiki files are ect\r\n testroot = testobj.getroot()\r\n code = str()\r\n print(x) # Print what file your on\r\n for text in testroot.iter('{http://www.mediawiki.org/xml/export-0.10/}text'):\r\n code = text.text\r\n testcode = mwparserfromhell.parse(code)\r\n testtemplates = testcode.filter_templates()\r\n for y in range(0, len(testtemplates)):\r\n checkname = str(testtemplates[y].name)\r\n if checkname.replace(\" \", \"\").replace(\"\\n\", \"\").lower() == \"infoboxperson\" or checkname.replace(\" \", \"\").replace(\"\\n\", \"\").lower() == 'infoboxchinese-languagesingerandactor':\r\n testtemp = testtemplates[y]\r\n date = mwparserfromhell.parse(testtemp.get('birth_date').value)\r\n datetemplate = date.filter_templates()\r\n dob = str()\r\n if not datetemplate:\r\n dob = str(testtemp.get('birth_date').value)\r\n else:\r\n datefinish = datetemplate[0]\r\n dob = str(datefinish.get(2)) + \"/\" + str(datefinish.get(3)) + '/' + str(datefinish.get(1).value)\r\n name = mwparserfromhell.parse(testtemp.get('name').value)\r\n nametemp = name.filter()\r\n tea = str(nametemp[0].replace(\" \", \"\", 1).replace(\"\\n\", \"\"))\r\n namelist = tea.split(\" \")\r\n personname = str(nametemp[0])\r\n string = \"CREATE (\" + personname.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\":\", \"\").replace(\"'\", \"\").replace(\",\", \"\").replace(\".\", \"\") + \":Person {name:\\\"\" + personname.replace(\"\\n\", \"\").replace(\" \", \"\", 1) + \"\\\", born:\\\"\" + dob.replace(\"\\n\", \"\").replace(\" \", \"\", 1) + \"\\\"\"\r\n string += \"})\"\r\n f.write(string + \"\\n\")\r\n elif checkname.replace(\" \", \"\").replace(\"\\n\", \"\").lower() == \"infoboxfilm\":\r\n testtemp = testtemplates[y]\r\n part = mwparserfromhell.parse(testtemp.get('starring').value)\r\n parts = part.filter()\r\n date = mwparserfromhell.parse(testtemp.get('released').value)\r\n datetemplate = date.filter_templates()\r\n release = str()\r\n if not datetemplate:\r\n release = str(testtemp.get('released').value)\r\n #elif not datetemplate[1]:\r\n # release = str(datefinish.get(1))\r\n else:\r\n datefinish = datetemplate[0]\r\n release = str(datefinish.get(2)) + \"/\" + str(datefinish.get(3)) + '/' + str(datefinish.get(1).value)\r\n title = str(testtemp.get('name').value)\r\n string = \"CREATE (\" + title.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\":\", \"\").replace(\"'\", \"\").replace(\",\", \"\").replace(\".\", \"\") + \":Film {title:\\\"\" + title.replace(\"\\n\", \"\").replace(\" \", \"\", 1) + \"\\\", released:\\\"\" + release.replace(\"\\n\", \"\").replace(\" \", \"\", 1)\r\n string += \"\\\"})\"\r\n f.write(string + \"\\n\")\r\n elif checkname.replace(\" \", \"\").replace(\"\\n\", \"\").lower() == \"infoboxmusicalartist\":\r\n testtemp = testtemplates[y]\r\n if testtemp.has('name'):\r\n name = str(testtemp.get('name').value)\r\n string = \"CREATE (\" + name.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\":\", \"\").replace(\"'\", \"\").replace(\",\", \"\").replace(\".\", \"\") + \":MusicalArtist {title:\\\"\" + name.replace(\"\\n\", \"\").replace(\" \", \"\", 1) + \"\\\"\"\r\n string += \"})\"\r\n f.write(string + \"\\n\")\r\nf.close()","sub_path":"SCRAp/Nodes.py","file_name":"Nodes.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540862398","text":"import math\nqual_velocidade = float(input('Qual a velocidade da jaca?'))\nqual_angulo = float(input('Qual o angulo de lançamento em graus?'))\n\nd = (qual_velocidade**2)*(math.sin(math.radians(2*qual_angulo)))/9.8\nif d < 98:\n print ('Muito perto')\nelif d > 102:\n print ('Muito longe')\nelse: \n print ('Acertou!')","sub_path":"backup/user_042/ch25_2020_10_05_19_08_02_862059.py","file_name":"ch25_2020_10_05_19_08_02_862059.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"22987546","text":"# NOTE: In Python we can inherit from build in types.\n# so we inherit all features of built in types and extend/add more as we require.\n\n# Extend str :\n\n\nclass Text(str):\n def duplicate(self):\n return self+self\n\n# Extend List :\n\n\nclass TrackableList(list):\n # overriding append method\n def append(self, object):\n print(\"Append Called\")\n # now calling append method of the base class.\n super().append(object)\n\n\ntext = Text(\"Python\")\nprint(text.lower())\nprint(text.duplicate())\n\nlist = TrackableList()\nlist.append(\"1\")\nprint(list)\n","sub_path":"CodeKitchen/Python Scripts/4_Classes/20_ExtendingBuiltInTypes.py","file_name":"20_ExtendingBuiltInTypes.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"481307045","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Thu May 3 23:54:20 2018\n\nMauricio de Oliveira\nUFMG - Belo Horizonte, Brazil\noliveiramauricio@dcc.ufmg.br\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import genfromtxt\nfrom utils import Y_dict, params\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.utils import shuffle\nfrom timeit import default_timer as timer\n\ndata = genfromtxt('data_tp1', delimiter=',')\n\n#plot a few inputs\nX = data[:,1:]/255 # X \nY = data[:,0] # Y\n\nX_train = X\nY_train = np.array([Y_dict[y] for y in Y])\n\n\nX_train, Y_train, Y = shuffle(X_train, Y_train, Y)\n\nrunning_times = {}\ntrained_networks = {}\n\n\nfor param in params:\n \n start = timer()\n ann = MLPClassifier(**params[param]).fit(X_train, Y_train)\n end = timer()\n \n running_times[param] = end - start\n trained_networks[param] = ann\n \n print(param + \" finished.\")\n print(running_times[param])\n print(ann.score(X_train, Y_train))\n\n","sub_path":"UFMG/tp1/ml1.py","file_name":"ml1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"394689927","text":"# author: rango\n# version: 1.0.0\n# email: lizhiping2016@gmail.com\n\nimport pickle\nimport os\n\ndef get_obj(path):\n try:\n if os.path.exists(path):\n #使用pickle模块从文件中重构python对象\n pkl_file = open(path, 'rb')\n obj = pickle.load(pkl_file)\n return obj\n else:\n return False\n except expression as identifier:\n return False\n\ndef get_data(path,key):\n '''\n if success return data\n else return false\n '''\n try:\n if os.path.exists(path):\n obj = get_obj(path)\n if obj:\n return obj[key]\n else:\n return False\n else:\n return False\n except expression as identifier:\n return False\n \ndef set_data(path,key,value):\n '''\n if success return True\n else return false\n '''\n try:\n obj = get_obj(path)\n if obj:\n obj[key] = value\n data = obj\n else:\n data = {key:value}\n output = open(path, 'wb')\n # Pickle dictionary using protocol 0.\n pickle.dump(data, output)\n # Pickle the list using the highest protocol available.\n output.close()\n return True\n except expression as identifier:\n return False\n \n\nif __name__ == \"__main__\":\n set_data(\"kv_database\",\"key_1\",\"value_1\")\n set_data(\"kv_database\",\"key_2\",\"value_2\")\n print(get_data(\"kv_database\",\"key_1\"))\n print(get_data(\"kv_database\",\"key_2\"))\n","sub_path":"coding/code/library/python/pickle_kv_database.py","file_name":"pickle_kv_database.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188837008","text":"#!/usr/bin/env python\nimport RPi.GPIO as GPIO\nimport time\nimport os\nimport sys\n\nbuzzer_pin = 12\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(buzzer_pin, GPIO.OUT)\n\ndef buzz(pitch=1500, duration=0.1) :\n pitch = float(pitch)\n duration = float(duration)\n period = 1.0 / pitch\n delay = period / 2\n cycles = int(duration * pitch)\n for i in range(cycles) :\n GPIO.output(buzzer_pin, True)\n time.sleep(delay)\n GPIO.output(buzzer_pin, False)\n time.sleep(delay)\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n try:\n buzz(*args)\n except KeyboardInterrupt:\n GPIO.cleanup()\n except:\n raise\n finally:\n GPIO.cleanup()\n","sub_path":"deploy/buzzer.py","file_name":"buzzer.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"370869500","text":"import numpy as np\nfrom tqdm import tqdm\n\nfrom saliency_interpreter import SaliencyInterpreter\n\nclass IntegratedGradient(SaliencyInterpreter):\n \"\"\"\n Interprets the prediction using Integrated Gradients\n \"\"\"\n def __init__(self, model, criterion, tokenizer, num_steps=20, show_progress=True, **kwargs):\n super().__init__(model, criterion, tokenizer, show_progress, **kwargs)\n self.num_steps = num_steps\n\n def saliency_interpret(self, test_dataloader):\n instances_with_grads = []\n iterator = tqdm(test_dataloader) if self.show_progress else test_dataloader\n\n for batch in iterator:\n self.batch_output = []\n self._integrate_gradients(batch)\n batch_output = self.update_output()\n instances_with_grads.extend(batch_output)\n\n return instances_with_grads\n\n def _register_forward_hook(self, alpha, embeddings_list):\n \"\"\"\n Register a forward hook on the embedding layer which scales the embeddings by alpha.\n \"\"\"\n def forward_hook(module, inputs, output):\n if alpha == 0:\n embeddings_list.append(output.squeeze(0).clone().detach())\n\n # Scale the embedding by alpha\n output.mul_(alpha)\n \n embedding_layer = self.get_embeddings_layer()\n handle = embedding_layer.register_forward_hook(forward_hook)\n return handle\n\n def _integrate_gradients(self, batch):\n\n ig_grads = None\n embeddings_list = []\n\n for alpha in np.linspace(0, 1.0, num=self.num_steps, endpoint=False): # 0.05\n # Hook for modifying embedding value\n handle = self._register_forward_hook(alpha, embeddings_list)\n\n grads = self._get_gradients(batch)\n handle.remove()\n\n if ig_grads is None:\n ig_grads = grads\n else:\n ig_grads = ig_grads + grads\n\n # Averaging of each gradient term\n ig_grads /= self.num_steps\n\n # Gradients get backward from network\n embeddings_list.reverse()\n\n # Element-wise multiply average gradient by the input\n ig_grads *= embeddings_list[0]\n\n self.batch_output.append(ig_grads)\n\n","sub_path":"saliency-map/integrated_gradient.py","file_name":"integrated_gradient.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"36596279","text":"import Resnet34\nimport LoadTinyImageNet\nimport torch\nfrom torch.autograd import Variable\nfrom torch.autograd import Function\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom abc import ABCMeta, abstractmethod\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport os\nfrom torch.utils.data import Dataset\nimport time\nimport pickle as pkl\nfrom torch import nn\nimport torch.optim as optim\nimport torch.nn.init\nimport math\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '4'\ndevice = Resnet34.device\n\nif __name__ == '__main__':\n\n \"\"\"\n resnet18_model = [Resnet34.getResnet34, Resnet34.getResnetPlus34FC, Resnet34.getResnetN34FC]\n\n resnet18_name = ['Resnet34.getResnet34', 'Resnet34.getResnetPlus34FC', 'Resnet34.getResnetN34FC']\n \"\"\"\n resnet18_model = [Resnet34.getResnetPlus34FC, Resnet34.getResnetN34FC]\n\n resnet18_name = ['Resnet34.getResnetPlus34FC', 'Resnet34.getResnetN34FC']\n batch_size = 128\n loss = 0.\n train_dataloader, test_dataloader = LoadTinyImageNet.get_data(batch_size)\n\n for j in range(len(resnet18_model)):\n print('new model training:{}'.format(resnet18_name[j]))\n model = resnet18_model[j]()\n model = model.to(device)\n trainLoss = 0.\n testLoss = 0.\n learning_rate = 1e-2\n start_epoch = 0\n test_loss_list = []\n train_loss_list = []\n acc_list = []\n epoches = 80\n SoftmaxWithXent = nn.CrossEntropyLoss()\n # define optimization algorithm\n optimizer = optim.SGD(model.parameters(), momentum=0.9, lr=learning_rate, weight_decay=5e-04)\n scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.8)\n print('{} epoch to run:{} learning rate:{}'.format(resnet18_name[j], epoches, learning_rate))\n for epoch in range(start_epoch, start_epoch + epoches):\n train_N = 0.\n train_n = 0.\n trainLoss = 0.\n model.train()\n for batch, [trainX, trainY] in enumerate(tqdm(train_dataloader, ncols=10)):\n # print(trainX.shape)\n train_n = len(trainX)\n train_N += train_n\n trainX = trainX.to(device)\n trainY = trainY.to(device).long()\n optimizer.zero_grad()\n predY = model(trainX)\n loss = SoftmaxWithXent(predY, trainY)\n\n loss.backward() # get gradients on params\n optimizer.step() # SGD update\n trainLoss += loss.detach().cpu().numpy()\n trainLoss /= train_N\n scheduler.step()\n train_loss_list.append(trainLoss)\n test_N = 0.\n testLoss = 0.\n correct = 0.\n model.eval()\n for batch, [testX, testY] in enumerate(tqdm(test_dataloader, ncols=10)):\n test_n = len(testX)\n test_N += test_n\n testX = testX.to(device)\n testY = testY.to(device).long()\n predY = model(testX)\n loss = SoftmaxWithXent(predY, testY)\n testLoss += loss.detach().cpu().numpy()\n _, predicted = torch.max(predY.data, 1)\n correct += (predicted == testY).sum()\n testLoss /= test_N\n test_loss_list.append(testLoss)\n acc = correct / test_N\n acc_list.append(acc)\n print('epoch:{} train loss:{} testloss:{} acc:{}'.format(epoch, trainLoss, testLoss, acc))\n if not os.path.exists('./SGDmnist_model'):\n os.mkdir('SGDmnist_model')\n if not os.path.exists('./SGDmnist_logs'):\n os.mkdir('SGDmnist_logs')\n torch.save(model.state_dict(), './SGDmnist_model/{}.pth'.format(resnet18_name[j]))\n print('模型已经保存')\n with open('./SGDmnist_logs/{}.pkl'.format(resnet18_name[j]), 'wb') as file:\n pkl.dump([train_loss_list, test_loss_list, acc_list], file)\n\n\n","sub_path":"NoiseOptimizationInANN/tinyImageNet/train34FC.py","file_name":"train34FC.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"138258739","text":"import sys\n\n\nx = \" \"\n\nif len(sys.argv) == 2:\n File = sys.argv[1]\nelse:\n print(\"wrong number of arguments !\")\n sys.exit()\n\nwith open(File, \"r\") as f:\n while len(x) != 0:\n y = \" \"\n x = f.readline().strip()\n with open(File, \"r\") as r:\n while len(y) != 0:\n y = r.readline().strip()\n if(x == y[::-1]):\n print(x + \" \" + y) \n \n\n","sub_path":"anagrams.py","file_name":"anagrams.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"372210596","text":"from mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as tri\nfrom functools import reduce\nimport numpy as np\nimport time\n\nclass Dirichlet(object):\n def __init__(self, alpha):\n from math import gamma\n from operator import mul\n self._alpha = np.array(alpha)\n self._coef = gamma(np.sum(self._alpha)) / \\\n reduce(mul, [gamma(a) for a in self._alpha])\n def pdf(self, x):\n '''Returns pdf value for `x`.'''\n from operator import mul\n return self._coef * reduce(mul, [xx ** (aa - 1)\n for (xx, aa)in zip(x, self._alpha)])\n\ncorners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])\ntriangle = tri.Triangulation(corners[:, 0], corners[:, 1])\nrefiner = tri.UniformTriRefiner(triangle)\ntrimesh = refiner.refine_triangulation(subdiv=8)\n\n\nmidpoints = [(corners[(i + 1) % 3] + corners[(i + 2) % 3]) / 2.0 \\\n for i in range(3)]\ndef xy2bc(xy, tol=1.e-3):\n '''Converts 2D Cartesian coordinates to barycentric.'''\n s = [(corners[i] - midpoints[i]).dot(xy - midpoints[i]) / 0.75 \\\n for i in range(3)]\n return np.clip(s, tol, 1.0 - tol)\n\ndef generate(alphas, trimesh):\n '''\n Generates Z data for the points in the X, Y meshgrid and parameter phi.\n '''\n dist = Dirichlet(alphas)\n pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]\n return pvals\n\na = np.linspace(0.2, 2, 20)\nalphas_list = [[al, al, al] for al in a]\n\nZ = [generate(alphas_list[nframe], trimesh) for nframe in range(20)]\ndef animate(nframe):\n ax.clear()\n plot = ax.plot_trisurf(trimesh, Z[nframe], cmap=plt.cm.CMRmap)\n ax.set_title('Alphas: {}, {}, {}'.format(*np.round(alphas_list[nframe], decimals = 2)))\n return plot,\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nanim = animation.FuncAnimation(fig, animate, frames = 20)\nplt.show()\nanim.save('dirichlet.gif', writer='imagemagic', fps=4)\n","sub_path":"dirichletanimation.py","file_name":"dirichletanimation.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"555230101","text":"# Create a function that takes a list as a parameter,\n# and returns a new list with all its element's values doubled.\n# It should raise an error if the parameter is not a list.\n\n\ndef listValuesDubler(inputList):\n\n newList = []\n if type(inputList) == list:\n for item in inputList:\n newList.append(item*2)\n else:\n raise TypeError('only list type input accepted!')\n return newList\n\n\ntestList = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(listValuesDubler(testList))\n\ntestFakeList = 'alma'\nprint(listValuesDubler(testFakeList))\n\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191030575","text":"import csv\nimport os\n\n\"\"\"\nDescription\n\"\"\"\nscriptRoot = os.path.dirname(__file__)\npathToAdapter = os.path.join(scriptRoot, \"assets\\\\adapter.txt\")\npathToSavedConfigurations = os.path.join(scriptRoot, \"assets\\\\saved_configurations.csv\")\n\ndef csvToDicts(path): # used\n \"\"\"\n Iterates through a csv file with an arbitrary number of columns and creates a list of dictionaries\n where the key is the column name and the value is the corresponding value for that column in that row.\n The csv file is passed as the PATH parameter.\n returns the list of dictionaries\n \"\"\"\n headers = [] # initialize a list for the header\n list = [] # initialize a list for the rows in the csv file. Indices are dictionaries with the rows contents\n with open(path, ) as csvfile:\n reader = csv.reader(csvfile)\n row_count = 0\n for row in reader: # iterates through the rows in the csv file\n if row_count == 0: # checks if the current row is the header row\n for i in row:\n headers.append(i) # appends the list with header names\n row_count += 1\n else:\n dict = {} # initializes a dictionary to hold the contents of the csv row\n column_count = 0\n for i in row: # iterates through the columns of the current row\n dict[headers[column_count]] = row[column_count] # appends the dictionary with the header of the column and the value of the associated column in this row \n column_count += 1\n list.append(dict) # appends this row dictionary to the list of rows\n row_count += 1\n if not list:\n list = headers\n return list # returns the csv file as a list of dictionaries of the rows contents\n\ndef getCurrentAdapter(): # used; csv file will change to just have a single adapter name. update logic to handle that ***\n \"\"\"\n Opens the text file with the adapter name stored in it and returns that name as a string\n \"\"\"\n with open (pathToAdapter, 'r') as theFile:\n reader = theFile.read()\n return reader\n\ndef getNextIndex(path): # used\n \"\"\"\n Takes a file path to a csv file as input\n Assumes there is a header item called 'index'\n iterates through the csv file to find the next index\n returns that index as a string\n \"\"\"\n listOfIndeces = [] #initialize a list to hold the current indices in the csv file\n for i in csvToDicts(path): # get a a list dictionaries of the rows in the csv file and iterate through it\n if type(i) == dict:\n for k, v in i.items(): # iterate through the dictionary containing the rows contents\n if k == 'index': # checks if the column in the row is 'index'\n listOfIndeces.append(v) # appends the list to include the index for that row\n else:\n return '0'\n \n count = 0 # create a vairable to count the number of indices\n while True:\n if str(count) in listOfIndeces: # check if the current count number already exists as an inex in the csv file\n count += 1\n else:\n nextIndex = str(count) # if the count number doesn't exist already it is set as nextIndex as astring\n break\n return nextIndex # returns the next index as a string\n\n\n \ndef saveNewConfig(data, path): #used; find out how to put the entry in numerical order if there is a gap in indices\n \"\"\"\n Takes a dictionary (data) and a file path (path) as input\n data is a dicitonary containing the configuration details to be added as a new entry to path, a csv file\n Writes the data into the csv file as new entry\n \"\"\"\n formattedData = formatIPAddresses(data)\n\n with open(path, mode='a', newline='') as csvfile: # open the csv file\n fieldnames = [] # initialize a list to hold the header information\n for k, v in formattedData.items(): # iterate through the config dictionary\n fieldnames.append(k) # add the keys to the fieldnames list\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # create a csv object associating the header names with the csv file\n writer.writerow(formattedData) # append the csv file\n\ndef saveAdapter(adapterName): # used\n \"\"\"\n Takes in the network adapter name as a string\n opens the text file that stores the saved adapter name for the user\n replaces what name was in there with the name passed to this function\n \"\"\"\n with open(pathToAdapter, 'w') as theFile:\n theFile.write(adapterName)\n\ndef getConfig(index): # used\n \"\"\"\n takes a string of a integer as an input\n compares it to the indices in the save)configurations csv\n returns the ip address, subnet mask, and gateway from that entry in the csv file as three strings\n \"\"\"\n reader = csv.reader(open(pathToSavedConfigurations)) # open the csv file\n lines = list(reader) # create a list of lists of the rows in the csv file\n line_count = 0 # count the current line\n for line in lines: # iterate through the rows in the csv file\n if line[0] == index: # check if the index cell of the row matches the input\n return line[2], line[3], line[4] # if it does return the ip address, sunbnet mask and gateway fromt hat row\n line_count += 1 # increment the row count\n\ndef formatIPAddresses(data):\n \"\"\"\n formats a dictionary of network information so that all octets have three digits including zeros if necessary\n \"\"\"\n newData = {}\n for k, v in data.items():\n if k == 'index':\n newData[k] = v\n elif k == 'name':\n newData[k] = v\n elif k == 'primary':\n newData[k] = v\n elif not v:\n newData[k] = ' '\n else:\n octets = v.split('.')\n formattedIPList = []\n formattedIP = ''\n for i in octets:\n if int(i) < 10:\n i = '00' + i\n elif int(i) < 100:\n i = '0' + i\n formattedIPList.append(i)\n formattedIP = '.'.join(formattedIPList)\n newData[k] = formattedIP\n return newData\n\ndef unformatOctets(octets):\n \"\"\"\n takes a 4 octet string such as an ip address and strips any unnecessary preceeding zeros from each octet\n \"\"\"\n if not octets.strip():\n return ''\n listOfOctets = octets.split('.')\n formattedIPList = []\n for i in listOfOctets:\n i = str(int(i))\n formattedIPList.append(i)\n return '.'.join(formattedIPList)\n\ndef recountList(path):\n data = csvToDicts(path)\n count = 0\n for i in data:\n i['index'] = count\n count += 1\n \n fieldnames = []\n for k, v in data[0].items():\n fieldnames.append(k)\n \n with open (path, 'w', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(data)\n\ndef deleteRow(index, path):\n lines = []\n with open(path, 'r') as readFile:\n reader = csv.reader(readFile)\n for row in reader:\n lines.append(row)\n for field in row:\n if field == index:\n lines.remove(row)\n \n \n with open(path, 'w', newline='') as writeFile:\n writer = csv.writer(writeFile)\n writer.writerows(lines)\n\ndef initailizeFiles():\n fieldnames = ['index', 'name', 'ip address', 'subnet', 'gateway', 'primary']\n with open(pathToSavedConfigurations, 'w', newline='') as configs:\n writer = csv.writer(configs)\n writer.writerow(fieldnames)\n\n saveAdapter('no saved adapter')\n\ndef getIndeces(path):\n dicts = csvToDicts(path)\n list = []\n for i in dicts:\n list.append(i['index'])\n \n return list\n\n\n \n","sub_path":"file_handler.py","file_name":"file_handler.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"233126468","text":"import os\nroot_dir = \"/media/ps/Data_disk_2/yuan_space/kinetics-400-jpg/train_256\"\n# root_dir = \"/media/ps/Data_disk_2/yuan_space/kinetics-400-data/raw-part/compress/train_256\"\nmin =99999999999\nmax = -1\nfor action_name in os.listdir(root_dir):\n action_dir = os.path.join(root_dir,action_name)\n for file_name in os.listdir(action_dir):\n file_path = os.path.join(action_dir,file_name)\n file_len = len(os.listdir(file_path))\n if min>file_len:\n min = file_len\n if max= mu):\n if k == 0:\n c1_abv_1 = np.hstack((c1_abv_1, cost[t]))\n else:\n c2_abv_1 = np.hstack((c2_abv_1, cost[t]))\n \n if (v[k,t] > mu - p) & (v[k,t] < mu):\n if k == 0:\n c1_blo_p = np.hstack((c1_blo_p, cost[t]))\n else:\n c2_blo_p = np.hstack((c2_blo_p, cost[t]))\n blothr[k] += 1\n if bt[k] == False:\n ahat = np.array([1, 0, -(v[k,t]-mu)])\n #ahat = np.array([1, 0, 0])\n dV[k,:] += (np.dot(V[k,:], ahat)+cost[t])*ahat \n bt[k] = True\n elif (v[k,t] < mu + p) & (v[k,t] >= mu):\n if k == 0:\n c1_abv_p = np.hstack((c1_abv_p, cost[t]))\n else:\n c2_abv_p = np.hstack((c2_abv_p, cost[t]))\n abvthr[k] += 1\n #Only do the update when firing...\n if bt[k] == True:\n ahat = np.array([1, (v[k,t]-mu), 0])\n #ahat = np.array([1, 0, 0])\n dV[k,:] += (np.dot(V[k,:], ahat)-cost[t])*ahat \n count[k] += 1\n V_mean[k,:] = (V_mean[k,:]*count[k] - dV[k,:])/(count[k]+1)\n V[k,:] = V[k,:] - eta*dV[k,:]/(count[k]+1)\n dV[k,:] = np.zeros((1,q))\n bt[k] = False\n \n beta_rd[i,j,k,t,ksim] = V[k,0]\n beta_rd_mean[i,j,k,t,ksim] = V_mean[k,0]\n \n beta_rd_true[i,j,0,t,ksim] = np.mean(c1_abv_p)-np.mean(c1_blo_p)\n beta_rd_true[i,j,1,t,ksim] = np.mean(c2_abv_p)-np.mean(c2_blo_p)\n beta_fd_true[i,j,0,t,ksim] = np.mean(c1_abv_1)-np.mean(c1_blo_1)\n beta_fd_true[i,j,1,t,ksim] = np.mean(c2_abv_1)-np.mean(c2_blo_1) \n \n #Save the results\n np.savez(fn_out, wvals = wvals, beta_rd = beta_rd, beta_rd_true = beta_rd_true, beta_fd_true = beta_fd_true,\\\n beta_sp = beta_sp, beta_rd_mean = beta_rd_mean)","sub_path":"scripts/learningbeta_counterfactual_fixedx_sweepw_banana_linear.py","file_name":"learningbeta_counterfactual_fixedx_sweepw_banana_linear.py","file_ext":"py","file_size_in_byte":8549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"130552616","text":"import json\nfrom datetime import datetime\nfrom test.test_const import CONST_BASE_URL, CONST_PORT, CONST_SSL\nfrom unittest import TestCase\n\nfrom pygrocydm.entities.battery import BATTERIES_ENDPOINT, Battery\nfrom pygrocydm.grocy_api_client import GrocyApiClient\n\n\nclass TestBattery(TestCase):\n\n def setUp(self):\n self.api = GrocyApiClient(CONST_BASE_URL, \"demo_mode\", verify_ssl=CONST_SSL, port=CONST_PORT)\n self.endpoint = BATTERIES_ENDPOINT + '/1'\n\n def test_battery_data_diff_valid(self):\n battery = self.api.do_request(\"GET\", self.endpoint)\n battery_keys = battery.keys()\n moked_battery_json = \"\"\"{\n \"id\": \"1\",\n \"name\": \"Battery1\",\n \"description\": \"Warranty ends 2023\",\n \"used_in\": \"TV remote control\",\n \"charge_interval_days\": \"0\",\n \"row_created_timestamp\": \"2020-03-01 00:50:25\"\n }\"\"\"\n moked_keys = json.loads(moked_battery_json).keys()\n self.assertCountEqual(list(battery_keys), list(moked_keys))\n\n def test_parse_json(self):\n battery = Battery(self.api, BATTERIES_ENDPOINT, self.api.do_request(\"GET\", self.endpoint))\n assert isinstance(battery.id, int)\n assert isinstance(battery.description, str) or battery.description is None\n assert isinstance(battery.name, str)\n assert isinstance(battery.used_in, (str, None))\n assert isinstance(battery.charge_interval_days, int)\n assert isinstance(battery.row_created_timestamp, datetime)\n","sub_path":"test/test_battery.py","file_name":"test_battery.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"532952908","text":"from django.contrib import admin\nfrom .models import Message, Chat\n\n\nclass MassageInline(admin.TabularInline):\n model = Message\n extra = 0\n\n\n@admin.register(Chat)\nclass ChatAdmin(admin.ModelAdmin):\n list_display = ('id', 'student')\n inlines = [MassageInline]\n","sub_path":"chat/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"138305744","text":"class TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def height(self, root):\n return -1 if not root else 1 + self.height(root.left)\n\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n nodes = 0\n h = self.height(root)\n\n while root:\n # last node is in the right subtree\n # add root and 2**h-1 of the left subtree, and add the right subtree recursively\n if self.height(root.right) == h - 1:\n nodes += 1 << h\n root = root.right\n # last node is in the left subtree\n # add root and 2**(h-1)-1 of the right subtree, and add the left subtree recursively\n else:\n nodes += 1 << h - 1\n root = root.left\n h -= 1\n\n return nodes\n","sub_path":"2/count_complete_tree_node.py","file_name":"count_complete_tree_node.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232871108","text":"# -*- coding: cp1252 -*-\r\nfrom Tkinter import *\r\nclass Application(Frame):\r\n def __init__(self, master):\r\n Frame.__init__(self)\r\n self.grid()\r\n self.create_widgets()\r\n self.chars=0\r\n\r\n def create_widgets(self):\r\n '''create widgets and buttons'''\r\n self.display_ent=Entry(self)\r\n self.display_ent.grid(row=0, column=0)\r\n self.bttn1=Button(self, text=\"A\")\r\n self.bttn1[\"command\"]=self.updateA\r\n self.bttn1.grid(row=1,column=1)\r\n self.bttn2=Button(self, text=\"B\")\r\n self.bttn2[\"command\"]=self.updateB\r\n self.bttn2.grid(row=1,column=2)\r\n self.bttn3=Button(self, text=\"Backspace\")\r\n self.bttn3[\"command\"]=self.updateBack\r\n self.bttn3.grid(row=1,column=3)\r\n\r\n def updateA(self):\r\n self.display_ent.insert(END,\"A\")\r\n self.chars+=1\r\n def updateB(self):\r\n self.display_ent.insert(END,\"B\")\r\n self.chars+=1\r\n def updateBack(self):\r\n self.display_ent.delete(self.chars-1,END)\r\n if self.chars > 0:\r\n self.chars-=1\r\n \r\n \r\n \r\n \r\nroot=Tk()\r\nroot.title(\"Word\")\r\nroot.geometry(\"600x600\")\r\napp=Application(root)\r\nroot.mainloop()\r\n","sub_path":"Tkinter/GUI5.py","file_name":"GUI5.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"493925742","text":"# prep_train_tts.py\n# author: Diego Magaleno\n# General script that prepares all audio and text files to train on\n# tacotron 2. The model is then trained and saved appropriately.\n# Python 3.7\n# Tensorflow 2.4\n# Windows/MacOS/Linux\n\n\nimport os\nimport subprocess\nfrom shutil import copyfile\n\n\ndef main():\n\t# Start by check to see if the tacotron 2 github repo has been downloaded.\n\t# Download it if it has not.\n\tprint(\"Checking for Tacotron2...\")\n\tif \"tacotron2\" not in os.listdir():\n\t\tprint(\"Could not find Tacotron2. Downloading from github.\")\n\t\tdownload = subprocess.Popen(\"git clone https://github.com/NVIDIA/tacotron2\", \n\t\t\tshell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n\t\t)\n\t\toutput, error = download.communicate()\n\n\t\t# If there are any unexpected error messages, print them and exit.\n\t\tif error.decode(\"utf-8\") != \"Cloning into 'tacotron2'...\\n\":\n\t\t\tprint(error.decode(\"utf-8\"))\n\t\t\tprint(\"Failed to download Tacotron2. Exiting program.\")\n\t\t\texit(1)\n\n\t\t# Output expected error and output messages.\n\t\tif output.decode(\"utf-8\") != \"\":\n\t\t\tprint(output)\n\t\tprint(error.decode(\"utf-8\"))\n\t\tprint(\"Tacotron2 has been successfully downloaded.\")\n\tprint(\"Tacotron2 found.\")\n\n\tcharacters = [\"GLaDOS\", \"Wheatley\"]\n\tcharacter = characters[0]\n\n\t# Go through the character audio and text for that character.\n\tcharacter_path = \"./\" + character + \"/\"\n\taudio_files = [character_path + wav for wav in os.listdir(character_path)\n\t\t\t\t\tif wav.endswith(\".wav\")]\n\ttext_files = [character_path + txt for txt in os.listdir(character_path)\n\t\t\t\t\tif txt.endswith(\".txt\")]\n\n\t# Create a folder to store the wav files for the character in the tacotron\n\t# repository if it doesn't already exist. Remove any files in there from\n\t# the last one.\n\ttaco_wavs_folder = \"./tacotron2/wavs/\"\n\tif not os.path.exists(taco_wavs_folder):\n\t\tos.mkdir(taco_wavs_folder)\n\tif len(os.listdir(taco_wavs_folder)) != 0:\n\t\tcontents = os.listdir(taco_wavs_folder)\n\t\tfor obj in contents:\n\t\t\tos.remove(taco_wavs_folder + obj)\n\n\t# Copy over character wav files to the wav folder in tacotron\n\t# repository.\n\t#for audio_file in audio_files:\n\t#\tcopyfile(audio_file, taco_wavs_folder + \"/\" + audio_file.split(\"/\")[-1])\n\tfor audio_file_idx in range(len(audio_files)):\n\t\tcopyfile(audio_files[audio_file_idx], \n\t\t\ttaco_wavs_folder + str(audio_file_idx) + \".wav\"\n\t\t)\n\n\t# Format the corresponding transcript text files accordingly. Add\n\t# that text to a string to write the filelist txt file.\n\tfilelist_save = \"./tacotron2/filelists/\" + character + \"_filelist.txt\"\n\tfilelist_text = \"\"\n\tfor text_file_idx in range(len(text_files)):\n\t\tformatted_text = clean_text(text_files[text_file_idx])\n\t\theader = \"wavs/\" + str(text_file_idx) + \".wav|\"\n\t\tfilelist_text += header + formatted_text + \"\\n\"\n\twith open(filelist_save, \"w+\") as filelist:\n\t\tfilelist.write(filelist_text)\n\n\t# Run training script train.py in tacotron2 repository to train\n\t# model.\n\toutput_dir = character + \"_saved_checkpoints\"\n\tlog_dir = character + \"_logs\"\n\tn_gpus = 0\n\tn\n\ttrain = subprocess.Popen(\"python ./tacotron2/train.py -o\")\n\n\t# Exit the program.\n\texit(0)\n\n\ndef clean_text(file):\n\twith open(file, \"r\", encoding=\"cp1252\") as read_file:\n\t\tfile_text = read_file.read()\n\tfile_text = file_text.replace(\"\\n\", \" \").encode(\"utf-8\").decode(\"utf-8\")\n\tif not file_text.endswith(\".\"):\n\t\tfile_text += \".\"\n\treturn file_text\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"prep_train_tts.py","file_name":"prep_train_tts.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432094147","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Functions\n\ndef whereAmI(player):\n print(f\"You are at the {player.current_room.name}.\\n\")\n print(f\"{player.current_room.description} \\n\")\n\ndef badPath(player):\n print(f\"You're not able to move in that direction from the {player.current_room.name}.\\n\")\n\ndef checkIfItems(room, player):\n if len(room.items) > 0:\n print(\"The room has the following items:\\n\")\n for item in room.items:\n print(f\"A {item.capitalize()}\\n\")\n\n else: \n print(\"There's nothing of interest in here...\\n\")\n \n # command = input(\"[Take 'item_name] [Drop 'item_name'] [Leave]\\n\").lower()\n # commands = command.split(\" \")\n\n # if len(commands) == 1 and commands[0] == \"leave\":\n # print(\"\\nYou decided to leave the items alone.\\n\")\n \n # elif len(commands) == 2:\n # if commands[0] == \"take\":\n # taken_item = room.items.pop(str(commands[1]))\n # player.items.update({str(commands[1]) : taken_item})\n\n # if commands[0] == \"drop\":\n # dropped_item = player.items.pop(str(commands[1]))\n # room.items.update({str(commands[1]) : dropped_item})\n \n \n # else:\n # print('No items')\n\n\ndef manipulateItems(room, player):\n command = input(\"[Take 'item_name] [Drop 'item_name'] [Leave]\\n\").lower()\n commands = command.split(\" \")\n if commands[0] == \"take\":\n taken_item = room.items.pop(str(commands[1]))\n player.items.update({str(commands[1]) : taken_item})\n \n elif commands[0] == \"drop\":\n dropped_item = player.items.pop(str(commands[1]))\n room.items.update({str(commands[1]) : dropped_item})\n\n else:\n print('No items.\\n')\n# Items\n\n# sword = Item('Sword', 'A sword with a dull blade, looks like it could barely cut skin.')\n# rock = Item(\"Rock\", \"A simple rock that's the size of the palm of your hand.\")\n\nitemList = {\n 'sword': Item('Sword', 'A sword with a dull blade, looks like it could barely cut skin.'),\n\n 'rock': Item(\"Rock\", \"A simple rock that's the size of the palm of your hand.\"),\n\n 'lantern': Item('Lantern', \"A lantern that's not lit.\")\n}\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n# assign items via arrays and spread itemList into them\nroom[\"outside\"].items = dict(itemList)\nroom['foyer'].items = {}\nroom['foyer'].items = {}\nroom['foyer'].items = {}\nroom['overlook'].items = {}\nroom['narrow'].items = {}\nroom['narrow'].items = {}\nroom['treasure'].items = {}\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\n\nplayer_name = \"\"\nset_name = False\n\nwhile not set_name:\n player_name = input('Please enter a name for your character:\\n')\n\n if len(player_name) > 10:\n print(\"Sorry, that name is too long! 10 characters is the limit.\")\n\n else:\n player = Player(str(player_name), room['outside'], {})\n print(\"Welcome to the Adventure Game!\")\n print(f\"Your name is {player.name}.\\n\")\n whereAmI(player)\n checkIfItems(player.current_room, player)\n set_name = True\n\n\n\n# Make a new player object that is currently in the 'outside' room.\nuser = input(\"[n] Move north [e] Move east [s] Move south [w] Move west [c] Check Items \\n [q] Quit\\n \").lower()\n\n\n\nwhile not user == \"q\":\n \n if user == \"n\":\n print(\"\")\n print(\"\")\n print(\"You move towards the north.\\n\")\n\n if player.current_room == room[\"outside\"]:\n player.current_room = room[\"outside\"].n_to\n \n \n elif player.current_room == room[\"foyer\"]:\n player.current_room = room[\"foyer\"].n_to\n \n elif player.current_room == room[\"overlook\"]:\n badPath(player)\n\n elif player.current_room == room[\"narrow\"]:\n player.current_room = room[\"narrow\"].n_to\n\n elif player.current_room == room[\"treasure\"]:\n badPath(player)\n \n elif user == \"e\":\n print(\"\")\n print(\"\")\n print(\"You move towards the east. \\n\")\n\n if player.current_room == room[\"outside\"]:\n badPath(player)\n \n \n elif player.current_room == room[\"foyer\"]:\n player.current_room = room[\"foyer\"].e_to\n \n elif player.current_room == room[\"overlook\"]:\n badPath(player)\n\n elif player.current_room == room[\"narrow\"]:\n badPath(player)\n\n elif player.current_room == room[\"treasure\"]:\n badPath(player)\n\n elif user == \"w\":\n print(\"\")\n print(\"\")\n print(\"You move towards the west. \\n\")\n\n if player.current_room == room[\"outside\"]:\n badPath(player)\n \n elif player.current_room == room[\"foyer\"]:\n badPath(player)\n \n elif player.current_room == room[\"overlook\"]:\n badPath(player)\n\n elif player.current_room == room[\"narrow\"]:\n player.current_room = room[\"narrow\"].w_to\n\n elif player.current_room == room[\"treasure\"]:\n badPath(player)\n \n elif user == \"s\":\n print(\"\")\n print(\"\")\n print(\"You move towards the south. \\n\")\n\n if player.current_room == room[\"outside\"]:\n badPath(player)\n \n elif player.current_room == room[\"foyer\"]:\n player.current_room = room[\"foyer\"].s_to\n \n elif player.current_room == room[\"overlook\"]:\n player.current_room = room[\"overlook\"].s_to\n\n elif player.current_room == room[\"narrow\"]:\n badPath(player)\n\n elif player.current_room == room[\"treasure\"]:\n player.current_room = room[\"treasure\"].s_to\n\n elif user == \"c\":\n print(\"\")\n print(\"\")\n print(\"You look through your backpack. \\n\")\n if len(player.items) > 0:\n print(\"You see the following items: \\n\")\n for item in player.items:\n print(f\"A {player.items[item].name} -- {player.items[item].description} \\n\")\n \n else:\n print('You have no items! \\n')\n \n manipulateItems(player.current_room, player)\n \n else:\n print(\"\")\n print(\"\")\n print(\"Invalid input.\")\n\n whereAmI(player)\n checkIfItems(player.current_room, player)\n print(\"\\nPlease choose to continue...\\n\")\n user = input(\"[n] Move north [e] Move east [s] Move south [w] Move west [c] Check Items \\n [q] Quit\\n \").lower()\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"499434678","text":"from regression_framework.functions.base_function import Base_function\r\nfrom numpy import cos,sqrt,prod\r\nimport numpy as np\r\nimport random\r\n\r\nclass Generalized_griewank_function(Base_function):\r\n def __init__(self,name = 'Generalized_griewank_function',lower_bound = -600,upper_bound = 600,dimension = 30):\r\n super().__init__(name,lower_bound,upper_bound,dimension)\r\n\r\n def get_fitness(self,value, fr=4000):\r\n x = np.asarray_chkfinite(value)\r\n n = len(x)\r\n j = np.arange(1., n+1 )\r\n s = sum(x**2)\r\n p = prod(cos(x / sqrt(j)))\r\n return s/fr - p + 1\r\n\r\n def random_solution(self):\r\n randomSolution = random.random()*(2*self.upper_bound) - self.lower_bound\r\n return randomSolution","sub_path":"regression_framework/functions/generalized_griewank_function.py","file_name":"generalized_griewank_function.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"250551797","text":"class Solution(object):\n def rotateString(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n if not all([A, B]):\n return A == B\n if len(A) != len(B):\n return False\n pos = B.rfind(A[0])\n while pos != -1:\n if self.isRotate(A, B, pos):\n return True\n pos = B.rfind(A[0],0, pos-1)\n\n def isRotate(A, B, pos):\n pass\n\n def rotateString01(self, A, B):\n if not all([A, B]):\n return A == B\n if len(A) != len(B):\n return False\n for i in range(0, len(A)):\n head = A[0]\n A = A[1:] + head\n if A == B:\n return True\n return False\n\n","sub_path":"RotateString.py","file_name":"RotateString.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"619030083","text":"#from math import sqrt\nfrom random import randint\n\n# ==== RSA auth block =====\nclass HashGen(object):\n @staticmethod\n def gen_hash(msg:str) -> int:\n # generating super dummy hash digest\n return 17\n\nclass RSAUserA(object):\n def __init__(self, msg):\n self.__msg = msg\n\n def generate_keys(self):\n self.__open_key = (5, 91) # dummy generetion of open key (e,n)\n print('User A: generated open key ({}, {})'.format(self.__open_key[0], self.__open_key[1]))\n self.__private_key = 29 # also\n print('User A: generated private key ({})'.format(self.__private_key))\n return self.__open_key\n \n def calculate_signature(self):\n # generating message digest\n h = HashGen.gen_hash(self.__msg)\n print('User A: generated digest h ({})'.format(h))\n # calculating signature\n self.__sign = (h ** self.__private_key) % self.__open_key[1] \n \n def send_msg_and_signature(self) -> tuple:\n print('User A: sent a digest signature to user B')\n return self.__msg, self.__sign\n\n\nclass RSAUserB(object):\n def check_user_signature(self, user_a: RSAUserA):\n open_key = user_a.generate_keys()\n user_a.calculate_signature()\n msg, sign = user_a.send_msg_and_signature()\n msg_h = HashGen.gen_hash(msg)\n print('User B: calculated msg digest ({})'.format(msg_h))\n sign_h = (sign ** open_key[0]) % open_key[1]\n print('User B: calculated digest based on user A\\'s signature ({})'.format(sign_h))\n if sign_h == msg_h:\n print('User B: claimed that msg was sent by user A')\n else:\n print('User B: seems like msg was NOT sent by user A')\n\n\ndef try_RSA_signature():\n user_a = RSAUserA('Dummy message...')\n user_b = RSAUserB()\n user_b.check_user_signature(user_a)\n\n# ==== Standart 34.10-94 signature block ====\nclass ShnorUserA(object):\n def __init__(self, msg):\n self.__msg = msg\n\n def generate_keys(self) -> tuple:\n self.__p, self.__q = 79,13\n self.__a = 2\n while((self.__a ** self.__q) % self.__p != 1):\n self.__a += 1\n if self.__a >= self.__p - 1:\n self.__p = self.__a + 2\n print('User A: generated simple nums (p,q) ({},{})'.format(self.__p, self.__q))\n print('User A: generated num a ({})'.format(self.__a))\n self.__x = randint(1, self.__q-1)\n print('User A: generated secret key x ({})'.format(self.__x))\n self.__y = (self.__a ** self.__x) % self.__p\n print('User A: generated open key y ({})'.format(self.__y))\n return self.__p, self.__q, self.__a, self.__y\n \n def calculate_signature(self):\n h = HashGen.gen_hash(self.__msg)\n print('User A: generated msg digest ({})'.format(h))\n success_gen = False\n while(not success_gen):\n k = randint(1, self.__q-1)\n w1 = (self.__a ** k) % self.__p\n self.__w2 = w1 % self.__q\n if self.__w2 == 0:\n continue\n self.__s = ((self.__x * self.__w2) + (k * h)) % self.__q\n if self.__s == 0:\n continue\n success_gen = True\n print('User A: chose k ({})'.format(k))\n print('User A: calculated w\\' ({})'.format(self.__w2))\n print('User A: calculated signature s ({})'.format(self.__s))\n\n def send_msg_and_sign(self) -> tuple:\n print('User A: sent msg and signature to User B')\n return self.__msg, self.__w2, self.__s\n\n\nclass ShnorUserB(object):\n def check_user_signature(self, user_a: ShnorUserA):\n p, q, a, y = user_a.generate_keys()\n user_a.calculate_signature()\n msg, w2, s = user_a.send_msg_and_sign()\n h = HashGen.gen_hash(msg)\n print('User B: calculated msg digest ({})'.format(h))\n v = (h ** (q-2)) % q\n print('User B: calculated v ({})'.format(v))\n z1 = (s * v) % q\n z2 = ((q - w2) * v) % q\n print('User B: calculated z1, z2 ({},{})'.format(z1, z2))\n u = (((a ** z1) * (y ** z2)) % p) % q\n print('User B: calculated u ({})'.format(u))\n if u == w2:\n print('User B: claimed that msg was sent by user A')\n else:\n print('User B: seems like msg was NOT sent by user A')\n\n\ndef try_Shnor_signature():\n user_a = ShnorUserA('Dummy message...')\n user_b = ShnorUserB()\n user_b.check_user_signature(user_a)\n\n# ======== Standart 34.10-2001 signature block ============\n\nclass Standart34UserA(object):\n def __init__(self, msg:str):\n self.__msg = msg\n \n def generate_keys(self):\n self.__n = 41\n self.__A = 3\n self.__B = 7\n self.__xp = 7\n self.__yp = 17\n self.__q = 47\n self.__d = 10\n self.__xq = 36\n self.__yq = 20\n return self.__A, self.__B, (self.__xp, self.__yp), self.__n, (self.__xq, self.__yq), self.__q\n\n def calculate_sign(self):\n h = 7#HashGen.gen_hash(self.__msg)\n print('User A: generated digest ({})'.format(h))\n e = h % self.__q\n print('User A: calculated e ({})'.format(e))\n k = 11#randint(1, self.__q - 1)\n print('User A: generated k ({})'.format(k))\n cx, cy = Standart34UserA.multiply_point((self.__xp, self.__yp), k, self.__A)\n print('User A: calculated C(x,y) ({},{})'.format(cx, cy))\n self.__r = int(cx) % self.__q\n print('User A: calculated r ({})'.format(self.__r))\n self.__s = (self.__r * self.__d + k * e) % self.__q\n print('User A: calculated s ({})'.format(self.__s))\n\n def send_msg_and_sign(self):\n return self.__msg, self.__r, self.__s\n \n @staticmethod\n def multiply_point(p:tuple, n:int, A:int) -> tuple:\n pk = None\n q = p\n for i in range(len(bin(n))-2):\n if n and (1 << i) == (1 << i):\n if pk == None:\n pk = q\n else:\n pk = Standart34UserA.add_points(pk, q, A)\n q = Standart34UserA.add_points(q, q, A)\n return pk\n\n @staticmethod\n def add_points(p1:tuple, p2:tuple, A:int) -> tuple:\n if p1[0] != p2[0]:\n k = (p2[1] - p1[1]) / (p2[0] - p1[0])\n else:\n k = (3 * p1[0]**2 + A) / (2 * p1[1])\n x3 = k**2 - p1[0] - p2[0]\n y3 = k * (p1[0] - x3) - p1[1]\n return (x3, y3)\n\nclass Standart34UserB(object):\n def check_user_signature(self, user_a: Standart34UserA):\n A, B, P, n, Q, q = user_a.generate_keys()\n user_a.calculate_sign()\n msg, r, s = user_a.send_msg_and_sign()\n h = 7#HashGen.gen_hash(msg)\n print('User B: generated msg digest ({})'.format(h))\n e = h % q\n print('User B: calculated e\\' ({})'.format(e))\n e_reverse = Standart34UserB.xgcd(q, e)[2]\n if e_reverse < 0:\n e_reverse += q\n v = e_reverse % q\n print('User B: calculated v ({})'.format(v))\n z1 = (s * v) % q\n z2 = ((q - r) * v) % q \n print('User B: calculated (z1,z2) ({}, {})'.format(z1,z2))\n c = Standart34UserA.add_points(Standart34UserA.multiply_point(P, z1, A), Standart34UserA.multiply_point(Q, z2, A), A)\n print('User B: calculated C\\'(x,y) ({}, {})'.format(c[0], c[1]))\n r2 = c[0] % q\n print('User B: calculated r\\' ({})'.format(r2))\n if r2 == r:\n print('User B: claimed that msg was sent by user A')\n else:\n print('User B: seems like msg was NOT sent by user A')\n\n\n @staticmethod\n def xgcd(a, b):\n \"\"\"return (g, x, y) such that a*x + b*y = g = gcd(a, b)\"\"\"\n x0, x1, y0, y1 = 0, 1, 1, 0\n while a != 0:\n q, b, a = b // a, a, b % a\n y0, y1 = y1, y0 - q * y1\n x0, x1 = x1, x0 - q * x1\n return b, x0, y0\n\n\ndef try_standart34_10_2001():\n user_a = Standart34UserA('Dummy message...')\n user_b = Standart34UserB() \n user_b.check_user_signature(user_a)\n\nif __name__ == '__main__':\n print('======== RSA based signature ========')\n try_RSA_signature()\n print('======== Standart 34.10-94 based signature =========')\n try_Shnor_signature()\n print('======== Standart 34.10-2001 based signature =========')\n try_standart34_10_2001()\n","sub_path":"CryptoLab9/CryptoLab9.py","file_name":"CryptoLab9.py","file_ext":"py","file_size_in_byte":8308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382389197","text":"# 659. Split Array into Consecutive Subsequences\n\n# You are given an integer array sorted in ascending order (may contain duplicates), \n# you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers.\n# Return whether you can make such a split.\n\n# Example 1:\n# Input: [1,2,3,3,4,5]\n# Output: True\n# Explanation:\n# You can split them into two consecutive subsequences : \n# 1, 2, 3\n# 3, 4, 5\n\n# Example 2:\n# Input: [1,2,3,3,4,4,5,5]\n# Output: True\n# Explanation:\n# You can split them into two consecutive subsequences : \n# 1, 2, 3, 4, 5\n# 3, 4, 5\n# Example 3:\n# Input: [1,2,3,4,4,5]\n# Output: False\n\nimport collections\n\nclass isPossible:\n\n\n def doit(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n left = collections.Counter(nums)\n end = collections.Counter()\n\n for num in nums:\n\n if left[num] == 0:\n continue\n\n left[num] -= 1\n\n if end[num-1] > 0:\n end[num - 1] -= 1\n end[num] += 1\n\n elif left[num+1] and left[num+2]:\n left[num+1] -= 1\n left[num+2] -= 1\n end[num+2] += 1\n\n else:\n return False\n \n return True\n\n\n def doit2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n cur = 0\n pre = float('inf')\n \n p1 = p2 = p3 = 0\n c1 = c2 = c3 = 0\n i = j = 0\n n = len(nums)\n \n cnt = 0\n \n while i 2 for s in buff])","sub_path":"PythonLeetcode/Leetcode/659_SplitArrayintoConsecutiveSubsequences.py","file_name":"659_SplitArrayintoConsecutiveSubsequences.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"480531378","text":"import os\nimport numpy as np\nimport cv2\n\ndef listDirectory(directory, fileExtList):\n u\"zwraca listę obiektów zawierających metadane dla plików o podanych rozszerzeniach\"\n fileList = os.listdir(directory)\n fileList = [os.path.join(directory, f) for f in fileList \\\n if os.path.splitext(f)[1] in fileExtList]\n return fileList\n\nfindText = 'log2.tif' #nazwa szukanego pliku\nfileList = listDirectory('E:/ZIARNA/NoweStanowisko/180919/', '.tif')# 180708 180919\nfile = open('c:/180708.txt','w') #otwarcie pliku do zapisu (nadpisuje wczesniej istjenijący plik)\nfor oneFile in fileList: #przeglądanie katalogu głównego - podkatalogi\n print(oneFile) #wyświetlanie bierzącego katalogu\n if os.path.isdir(oneFile): #przeglądanie plików w poszczególnych katalogach\n fileList2 = listDirectory(oneFile+'/', '.tif') \n for oneFile2 in fileList2:\n if findText in oneFile2:\n\n #print(oneFile2[-5:-4]) #znak pomiędzy 5 a 4 od końca\n dirPath, fileName = os.path.split(oneFile2) #podzielenie stringu na ścieżkę i nazwę pliku\n\n srcImgPath = oneFile2\n srcMaskPath = oneFile2[:-5] + \"3\" + oneFile2[-4:]\n\n srcImage = cv2.imread(srcImgPath,1) # 0-grayscale 1-rgb -1-alpha channel\n maskImage = cv2.imread(srcMaskPath,0) #maska pliku (odcienie szarosci w tym przypadku czarno białe)\n if srcImage is not None and maskImage is not None:\n th, result = cv2.threshold(maskImage,10,255,cv2.THRESH_BINARY)\n result2 = cv2.cvtColor(result,cv2.COLOR_GRAY2BGR )\n # Now black-out the area of logo in ROI\n height,width = srcImage.shape[:2]\n\n file.write(dirPath + ',' + fileName + ',' + str(height)+ ',' + str(width) + '\\n' )\n\n roi = srcImage[0:height, 0:width ]\n srcImage2 = cv2.bitwise_and(roi,roi,mask = result) #Usunięcie czerni z wykorzystaniem maski\n\n newDirectory = 'C'+dirPath[1:]\n #print(newDirectory)\n if not os.path.exists(newDirectory):\n os.makedirs(newDirectory)\n cv2.imwrite(newDirectory+ '/'+fileName[:-3]+'png',srcImage2)\n else:\n print(srcImgPath)\n file.write(dirPath+'/'+fileName +',0,0\\n' )\n \nfile.close()","sub_path":"removeBackground.py","file_name":"removeBackground.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277206031","text":"\"\"\"\nThe Python standard library's 'calendar' module allows you to\nrender a calendar to your terminal.\nhttps://docs.python.org/3.6/library/calendar.html\n\nWrite a program that accepts user input of the form\n `14_cal.py month [year]`\nand does the following:\n - If the user doesn't specify any input, your program should\n print the calendar for the current month. The 'datetime'\n module may be helpful for this.\n - If the user specifies one argument, assume they passed in a\n month and render the calendar for that month of the current year.\n - If the user specifies two arguments, assume they passed in\n both the month and the year. Render the calendar for that\n month and year.\n - Otherwise, print a usage statement to the terminal indicating\n the format that your program expects arguments to be given.\n Then exit the program.\n\"\"\"\n\nimport sys\nimport calendar\nfrom datetime import datetime\nfrom datetime import date\n\n\ndef print_calendar(m, y):\n d = date.today()\n cal = calendar.TextCalendar(calendar.SUNDAY)\n output = None\n\n print(\"month\", month)\n print(\"year\", year)\n if not m and not y:\n output = cal.formatmonth(d.year, d.month)\n print(output)\n if m and not y:\n output = cal.formatmonth(d.year, int(m))\n print(output)\n if m and y:\n output = cal.formatmonth(int(y), int(m))\n print(output)\n\n\n\nmonth = input(\"Month: \")\nyear = input(\"Year: \")\n\nprint_calendar(month, year)\n","sub_path":"src/14_cal.py","file_name":"14_cal.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343625400","text":"from django.urls import path\n\nfrom core.cache import cache_per_user\nfrom annuaire import views\n\nANNUAIRE_CACHE_TTL = 60 * 60\n\n\nurlpatterns = [\n path(\"\", cache_per_user(ANNUAIRE_CACHE_TTL)(views.home), name=\"annuaire_home\"),\n path(\n \"/\",\n cache_per_user(ANNUAIRE_CACHE_TTL)(views.departement),\n name=\"annuaire_departement\",\n ),\n]\n","sub_path":"annuaire/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"536772750","text":"#FASTA to PHYLIP + NAMES\n#This program simplifies names to 10 characters and creates a cross reference file.\n#It then returns a PHYLIP sequential formatted sequence file. \n#This program allows multiple file names to be called as arguments.\n\n#imports os to create file directories\nimport os\n#imports sys to help with file input\nimport sys\n\n\n#Function for removing the directory of a file name\ndef getFilename(whole_name):\n reversed_name = whole_name[::-1]\n trun_rev=\"\"\n for i in range(len(whole_name)):\n if reversed_name[i] == \"/\":\n break\n else:\n trun_rev = trun_rev + reversed_name[i]\n new_name = trun_rev[::-1]\n return (new_name)\n\n#takes a string and fills up the front until it is 7 characters long. Then appends 'SEQ' to the front. \ndef makeTen(num_string):\n num_list = list(num_string)\n while len(num_list) < 7:\n num_list.insert(0,'0')\n return('SEQ' + \"\".join(num_list)) \n \ndef createNames(refFile):\n\n #NEED TO GO THROUGH ALL THE LINES OF THE REFERENCE FILE AND WRITE THE HEADER LINE TO A NEW LIST\n with open (refFile, 'r') as f:\n \n #opens a new file name for names\n file_name_names = getFilename(refFile)\n file_name_names = directory+\"/\"+file_name_names+ \".names\"\n namesFile = open(file_name_names,'w')\n \n \n #open a new file to hold phylip document\n file_name_phylip = getFilename(refFile)\n file_name_phylip = directory+\"/\"+file_name_phylip+ \".phylips\"\n phylipFile = open(file_name_phylip,'w')\n\n names_number = 0\n\n #create phylip header (count number of sequences and the number of characters in first sequence)\n sequence_number = 0\n character_number = 0\n first_line_trigger = True\n second_line_trigger = True\n for line in f:\n if line [0] == \">\":\n sequence_number = sequence_number + 1\n else:\n if sequence_number == 1:\n character_number = character_number + len(''.join(line.split()))\n\n phylipFile.write(str(sequence_number) + \" \" + str(character_number))\n\n with open (refFile, 'r') as f: \n for line in f:\n if line[0] == \">\":\n #write new name to name file and phylip document\n new_name = makeTen(str(int(names_number)))\n namesFile.write(new_name + \"\\n\")\n phylipFile.write(\"\\n\" + new_name + \" \")\n names_number = names_number + 1\n #write this line to name file (minus >)\n namesFile.write(line.strip('>'))\n else:\n phylipFile.write(''.join(line.split()))\n \n\n phylipFile.close()\n namesFile.close()\n \n return()\n\n\n#creates the \"Output\" file on the desktop if it does not already exist\ndirectory = \"Desktop/Output\"\nif not os.path.exists(directory):\n os.makedirs(directory)\n\n#MAIN CONTROL BLOCK- ALLOWS FOR CALLING MULTIPLE FILES AS ARGUMENTS\n \nif len(sys.argv) > 1: #the first argument in sys.argv is always the script name\n file_names = sys.argv[1:]\n #run the changeToFasta command on every file name if other commands are given\n for filename in file_names:\n createNames(filename)\n\nelse:\n file_name = str(raw_input('Enter the file to be changed: '))\n createNames(file_name)\n\n","sub_path":"FASTAtoPHYLIPandNAMES.py","file_name":"FASTAtoPHYLIPandNAMES.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"454399863","text":"import tkinter\nimport tkinter.messagebox\n\nclass TelephoneGUI:\n def __init__(self):\n self.main_window = tkinter.Tk()\n\n #Create two frames\n self.top_frame = tkinter.Frame(self.main_window)\n self.mid_frame = tkinter.Frame(self.main_window)\n self.bottom_frame = tkinter.Frame(self.main_window)\n \n #Create variable rpm for radio buttons\n self.radio_var = tkinter.IntVar()\n self.radio_var.set(1)\n\n #Create top_frame radio buttons\n self.rb1 = tkinter.Radiobutton(self.top_frame, text='Daytime (6:00 A.M. \\\n through 5:59P.M.) $0.07', variable=self.radio_var, value=1)\n self.rb2 = tkinter.Radiobutton(self.top_frame, text='Evening (6:00 P.M. \\\n through 11:59P.M.) $0.12', variable=self.radio_var, value=2)\n self.rb3 = tkinter.Radiobutton(self.top_frame, text='Off-Peak (midnight \\\n through 5:59 A.M.) $0.05', variable=self.radio_var, value=3)\n\n #Pack the buttons\n self.rb1.pack()\n self.rb2.pack()\n self.rb3.pack()\n\n #Create user input of time for call\n self.prompt_label = tkinter.Label(self.mid_frame, text = 'Enter total time of phone call:')\n self.minute_entry = tkinter.Entry(self.mid_frame, width = 10)\n\n #Create ok and quit buttons\n self.ok_button = tkinter.Button(self.bottom_frame, text='Calculate', command=self.calculate)\n \n #Pack ok and Quit button\n self.ok_button.pack(side='left')\n \n #Pack Frames\n self.top_frame.pack()\n self.bottom_frame.pack()\n\n #Start loop\n tkinter.mainloop()\n\n def calculate(self):\n tkinter.messagebox.showinfo('Selection', 'You selected option ' + str(self.radio_var.get()))\n\n \ntelephone_gui = TelephoneGUI()\n","sub_path":"201/Testing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"597966884","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.views.decorators.csrf import csrf_exempt\nfrom account.resources import POSAuthResource\nfrom account.resources import POSPinResource\nfrom slot import views as slot_views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^api/pos/auth/(?P[a-f0-9]+)/?',\n csrf_exempt(POSAuthResource.as_view('delete')), name='pos_logout'),\n url(r'^api/pos/auth/?', include(POSAuthResource.urls())),\n url(r'^api/pos/pin/location/(?P\\d+)/?',\n POSPinResource.as_list(), name='pos_pin_list'),\n url(r'^api/pos/pin/(?P\\d+)/?',\n POSPinResource.as_detail(), name='pos_pin_detail'),\n url(r'^api/pos/pin/cashout/(?P\\d+)/?',\n POSPinResource.as_view('cashout'), name='pos_pin_cashout'),\n url(r'^api/pos/pin/?', include(POSPinResource.urls())),\n url(r'^api/pos/pin/?', include(POSPinResource.urls())),\n # Slot API\n url(r'^slot/play/(?P\\d+\\.?\\d+?)/(?P\\d+\\.\\d{1,2})/(?P\\w+)',\n slot_views.slot_play, name='play'),\n url(r'^slot/reveal/(?P\\d+)/(?P\\d+\\.\\d{2})/(?P\\w+)',\n slot_views.slot_view_prize, name='view_prize'),\n url(r'^slot/last_result/(?P\\w+)',\n slot_views.slot_last_response, name='last_response'),\n # Account API\n url(r'^account/login/(?P\\d+)',\n slot_views.login, name='login'),\n url(r'^account/cashout/(?P\\w+)',\n slot_views.cashout, name='cashout'),\n url(r'^account/(?P\\w+)',\n slot_views.get_credits, name='get_credits'),\n]\n","sub_path":"rgs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"177843837","text":"from metax_api.models import DatasetCatalog\nfrom django.http import Http404\nfrom .common_view import CommonViewSet\nfrom ..serializers import DatasetCatalogSerializer\nfrom rest_framework.decorators import detail_route\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nimport logging\n_logger = logging.getLogger(__name__)\nd = logging.getLogger(__name__).debug\n\nclass DatasetCatalogViewSet(CommonViewSet):\n\n authentication_classes = ()\n permission_classes = ()\n\n # note: override get_queryset() to get more control\n queryset = DatasetCatalog.objects.filter(active=True, removed=False)\n serializer_class = DatasetCatalogSerializer\n object = DatasetCatalog\n\n lookup_field = 'pk'\n\n def __init__(self, *args, **kwargs):\n self.set_json_schema(__file__)\n super(DatasetCatalogViewSet, self).__init__(*args, **kwargs)\n\n def get_object(self):\n try:\n return super(DatasetCatalogViewSet, self).get_object()\n except Http404:\n pass\n except Exception:\n raise\n\n return self._search_using_other_dataset_catalog_identifiers()\n\n def _search_using_other_dataset_catalog_identifiers(self):\n \"\"\"\n URN-lookup from self.lookup_field failed. Look from catalog json\n identifiers, if there are matches\n \"\"\"\n\n lookup_value = self.kwargs.pop(self.lookup_field)\n try:\n obj = self._search_from_catalog_json({'identifier': lookup_value}, True)\n except Exception:\n raise\n\n return obj\n\n def _search_from_catalog_json(self, search_json, raise_on_404):\n try:\n return super(DatasetCatalogViewSet, self).get_object(\n search_params={'catalog_json__contains': search_json})\n except Http404:\n if raise_on_404:\n raise\n else:\n return None\n except Exception:\n raise\n\n @detail_route(methods=['get'], url_path=\"exists\")\n def dataset_catalog_exists(self, request, pk=None):\n try:\n self.get_object()\n except Exception:\n return Response(data=False, status=status.HTTP_404_NOT_FOUND)\n\n return Response(data=True, status=status.HTTP_200_OK)\n","sub_path":"src/metax_api/api/base/views/dataset_catalog_view.py","file_name":"dataset_catalog_view.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"327205228","text":"# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\nimport sys\nsys.path.insert( 0, '../../' )\n\nfrom pqu.PQU import valueOrPQ, _findUnit, PQU, floatToShortestString\n\ndoRaise = False\n\ndef a( v, unitFrom, unitTo ) :\n\n def b( v, unitFrom, unitTo, asPQU ) :\n\n vv = valueOrPQ( v, unitFrom, unitTo, asPQU )\n\n if( isinstance( vv, PQU ) ):\n print(vv)\n else:\n print(floatToShortestString(vv))\n\n print()\n print('---------')\n try :\n b( v, unitFrom, unitTo, False )\n except :\n if( doRaise ) : raise\n print(\"FAILED:\", v, \"'%s'\" % unitFrom, \"'%s'\" % unitTo)\n return\n b( v, unitFrom, unitTo, True )\n\ndl = _findUnit( \"\" )\nmm = _findUnit( \"mm\" )\npqu_m = PQU( \"3.14 m\" )\n\na( 3.14, None, None )\na( 3.14, \"\", None )\na( 3.14, None, \"\" )\na( 3.14, \"\", \"\" )\n\na( 3.14, dl, None )\na( 3.14, None, dl )\na( 3.14, dl, dl )\n\na( 3.14, \"m\", None )\na( 3.14, \"m\", \"cm\" )\na( 3.14, \"cm\", \"m\" )\n\ndoRaise = True\na( pqu_m, None, None )\na( pqu_m, None, \"cm\" )\na( pqu_m, None, \"km\" )\ntry :\n a( pqu_m, \"\", None )\n print('========= FAILED =========')\nexcept :\n pass\n","sub_path":"pqu/Check/t05.py","file_name":"t05.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"251140594","text":"T = int(input())\n\nfor test_case in range(1, T+1):\n N, M = map(int, input().split())\n arr = list(map(int, input().split()))\n\n temp = []\n for i in range(M):\n temp.append([arr[i], i+1])\n\n q = []\n for i in range(N):\n q.append(temp.pop(0))\n\n while q:\n p, k = q.pop(0)\n p //= 2\n if p == 0:\n if temp:\n q.append(temp.pop(0))\n else:\n q.append([p, k])\n\n print('#{} {}'.format(test_case, k))","sub_path":"SW-Expert-Academy/D3/5099. 피자 굽기.py","file_name":"5099. 피자 굽기.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"251770065","text":"import matplotlib.pyplot as plt \nimport numpy as np\n\nclass map:\n def __init__(self,taille_x=30,taille_y=20,largeur_route=10):\n self.taille_x=taille_x\n self.taille_y=taille_y\n self.largeur_route=largeur_route\n self.segments={}\n \n class segment :\n def __init__(self,point1=(0,0), point2=(0,0)):\n self.pt1=point1 \n self.pt2=point2 \n def trace(self):\n plt.plot([self.pt1[0],self.pt2[0]],[self.pt1[1],self.pt2[1]],color='r')\n\n def create_map(self):\n L=self.taille_x; l=self.taille_y; m=self.largeur_route\n exte=[[0,0],[L,0],[L,-l],[L+3*m,-l],[L+3*m,L+2*m-l],[L+m,L+4*m-l],[L,L+4*m-l],[L,L+3*m-l],[L-m,L+3*m-l],[L-m,L+3*m-l-m/5],[L-2*m,L+3*m-l-m/5],[L-2*m,L+3*m-l],[-m,L+3*m-l],[-m,0]]\n inte=[[m,m],[m+L,m],[m+L,m-l],[2*m+L,m-l],[2*m+L,L+m-l],[m+L,L+2*m-l],[-m+L,L+2*m-l],[-m+L,L+2*m-l-m/5],[-2*m+L,L+2*m-l-m/5],[-2*m+L,L+2*m-l],[0,L+2*m-l],[0,m]]\n obst=[[0.8*m+L,L+2.6*m-l],[0.8*m+L,L+3*m-l],[1.2*m+L,L+3*m-l],[1.2*m+L,L+2.6*m-l]]\n\n for i in range(len(exte)):\n self.segments[2*i] = self.segment(point1=exte[i-1],point2=exte[i])\n for i in range(len(inte)):\n self.segments[2*i+1] = self.segment(point1=inte[i-1],point2=inte[i])\n for i in range(len(obst)):\n self.segments[\"obs\",i] = self.segment(point1=obst[i-1],point2=obst[i])\n \n def trace_map(self):\n for i in self.segments.values():\n i.trace() \n \n\n\n\n \n","sub_path":"simuSaphir/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"72902743","text":"\"\"\"\n Module name: btc_data_collector\n Description: Module for collecting day level Bitcoin specific data\n like, price, number of tweets, volume of buy and sell transactions.\n\"\"\"\n\nfrom datetime import datetime, timedelta\nimport logging\n\nimport pandas as pd\nimport requests\nimport quandl\nfrom forex_python.bitcoin import BtcConverter\n\n\nDATE_FORMAT = \"%Y-%m-%d\"\nINDEX = 'Date'\nEXCHANGE = \"BCHAIN/ETRVU\"\nCURRENCY = \"USD\"\n\n\nclass BtcDataCollector(object):\n\n \"\"\"\n The object for retrieving daily data for bitcoin specific\n factors.The prices are retreived once a day at a predefined\n time. If the current for the current day is not available,\n latest available data is used.\n :member attributes: logger: logger instance\n api_key: Quandl API key\n tweet_count_url: Url to retrieve\n tweets count\n\n :member functions: fetch_btc_price\n fetch_tweet_counts\n fetch_transaction_volume\n \"\"\"\n\n def __init__(self, params):\n self.logger = logging.getLogger('simpleExample')\n self.api_key = params['Quandl']['quandl-key']\n self.tweet_count_url = params['Twitter']['tweet-count-url']\n\n def fetch_btc_price(self):\n \"\"\"\n Method to fetch the current bitcoin price.\n The price is in USD and is retreived from\n the CoinDesk index.\n : param self\n : return btc_price(float)\n error_val(int)\n \"\"\"\n error_val = -1\n try:\n day_count = 1\n today = datetime.now()\n start_date = today - timedelta(days=day_count)\n btc_price = pd.DataFrame([{\n 'Date': start_date.strftime(DATE_FORMAT),\n 'btc_price': BtcConverter(\n ).get_previous_price(CURRENCY, start_date)}])\n return btc_price.set_index(INDEX)\n except Exception as e:\n # self.logger.error(e)\n print(e)\n return error_val\n\n def fetch_tweet_counts(self):\n \"\"\"\n Method to fetch the daily estimated number of tweets\n with bitcoin related hastags. The function parses the\n HTML page to retrieve the tweet counts.\n\n : param self\n : return tweet_count(pandas Dataframes)\n error_val(int)\n \"\"\"\n error_val = -1\n try:\n day_count = 1\n today = datetime.now()\n start_date = today - timedelta(days=day_count)\n url = self.tweet_count_url\n page = requests.get(url)\n first = '[new Date(\"' + start_date.strftime(DATE_FORMAT) + '\"),'\n last = ']'\n start = page.text.rindex(first) + len(first)\n end = page.text.find(last, start)\n val = page.text[start:end]\n if val == 'null':\n count = 0\n else:\n count = int(page.text[start:end])\n tweet_count = pd.DataFrame({\n 'Date': [start_date.strftime(DATE_FORMAT)],\n 'tweet_count': [count]})\n return tweet_count.set_index(INDEX)\n except Exception as e:\n # self.logger.error(e)\n print(e)\n return error_val\n\n def fetch_transaction_volume(self):\n \"\"\"\n Method to fetch the daily bitcoin transaction\n volume in USD.\n : param self\n : return nyse_index(pandas Dataframe)\n error_val(int)\n \"\"\"\n error_val = -1\n try:\n\n day_count = 5\n today = datetime.now()\n start_date = today - timedelta(days=day_count)\n volume = quandl.get(EXCHANGE,\n start_date=start_date.strftime(DATE_FORMAT),\n api_key=self.api_key)\n volume.index = pd.to_datetime(volume.index).date\n volume.index.name = INDEX\n return volume.tail(n=1)\n except Exception as e:\n # self.logger.error(e)\n print(e)\n return error_val\n","sub_path":"pybcoin/DataCollector/btc_data_collector.py","file_name":"btc_data_collector.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"371009692","text":"import colorama, os\nfrom colorama import Fore, Back, Style\nclass Console:\n\tdef __init__(self):\n\t\tcolorama.init()\n\t\tos.system('cls')\n\n\tdef redraw(self, queue, properties, controllers):\n\t\tos.system('cls')\n\t\tself.print_list(\"QUEUE\", queue)\n\t\tfor k, v in properties.items():\n\t\t\tself.print_property(k, v)\n\t\tself.print_list(\"SCENES\", controllers)\n\t\tself.print_keymap({\"A\":\"twirl\"})\n\t\n\tdef print_list(self, title, _list, current=None):\n\t\tt = Fore.WHITE + Back.YELLOW + Style.BRIGHT + \"\\n%s:%s \" % (title, Style.RESET_ALL )\n\t\tfor k, v in enumerate(_list):\n\t\t\tif v.is_running:\n\t\t\t\tstyle = Fore.RED + Back.GREEN + Style.BRIGHT\n\t\t\telse:\n\t\t\t\tstyle = Fore.YELLOW + Back.BLUE + Style.BRIGHT\n\t\t\tt += style + \"#%s %s\" % (k+1, v) + Style.RESET_ALL + \" \"\n\t\tprint(t)\n\n\tdef print_property(self, name, value):\n\t\tif value in [None, False, 0]:\n\t\t\tstyle = Fore.RED\n\t\telse:\n\t\t\tstyle = Fore.GREEN\n\t\tprint(Style.RESET_ALL + Fore.YELLOW + Style.BRIGHT +\"\\n%s = %s%s\" % (name, style, str(value)))\n\n\tdef print_keymap(self, scene_map):\n\t\tt = Fore.WHITE + Back.YELLOW + Style.BRIGHT + \"\\n%s\\n\" % (\"KEYMAP\" )\n\t\tt += Style.RESET_ALL + Fore.CYAN + Back.CYAN + Style.BRIGHT +\"QUEUE [MOD=CTRL]\"\n\t\tprint(t)\n\t\tqueue_map = {\n\t\t\"SPACE\"\t\t: \"toggle change_scenes\",\n\t \"A\"\t\t\t: \"increment change_interval\",\n\t \"B\"\t\t\t: \"decrement change_interval\",\n\t \"[\"\t\t\t: \"previous scene\",\n\t \"]\"\t\t\t: \"next scene\",\n\t \"ENTER\"\t\t: \"push scene to queue\",\n\t \"BACKSPACE\"\t: \"remove scene\",\n\t \"#scene_id\" : \"add scene to_remove\"\n\t\t}\n\t\tfor k, v in queue_map.items():\n\t\t\tself.print_property(k, v)\n\n\t\tt = Style.RESET_ALL + Fore.CYAN + Back.CYAN + Style.BRIGHT +\"\\nSCENES [MOD=ALT]\"\n\t\tprint(t)\n\t\tself.print_property(\"#scene_id\", \"add scene to_queue\")\n\nconsole = Console()","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"252565207","text":"import os\nimport pickle\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nos.environ[\"SDL_VIDEODRIVER\"] = \"dummy\"\n\nrng = np.random.default_rng()\n\n\ndef init_population(population_size, num_inputs, num_ouputs, num_hidden_nodes, initial_species):\n individual_length = (num_inputs + 1)*num_hidden_nodes + num_ouputs*(num_hidden_nodes + 1)\n population = rng.normal(size=(population_size, individual_length))\n return np.array_split(population, initial_species)\n\n\ndef get_fitness(individual_index, species_index, individual, env):\n fitness = evaluate(individual, env)\n result = {\n \"individual_index\": individual_index,\n \"species_index\": species_index,\n \"fitness\": fitness\n }\n print(result)\n return result\n\n\ndef evaluate(individual, env):\n f, p, e, t = env.play(pcont=individual)\n return f\n\n\ndef generate_children(parents, num_children, mutation_params):\n children = []\n\n for _ in range(num_children):\n # future: maybe add custom p-dist based on fitness\n parent_1, parent_2 = rng.choice(parents, size=2, replace=False)\n child = uniform_crossover(parent_1, parent_2)\n mutate(child, mutation_params)\n children.append(child)\n\n return children\n\n\ndef uniform_crossover(parent_1, parent_2):\n proportions = rng.random(len(parent_1))\n child = parent_1 * proportions + parent_2 * (1 - proportions)\n return child\n\n\ndef mutate(individual, mutation_params):\n mutation_replace_rate = mutation_params[\"mutation_replace_rate\"]\n mutation_rate = mutation_params[\"mutation_rate\"]\n mutation_power = mutation_params[\"mutation_power\"]\n\n for i in range(len(individual)):\n if rng.random() < mutation_replace_rate:\n individual[i] = rng.normal()\n else:\n if rng.random() < mutation_rate:\n individual[i] = rng.normal(loc=individual[i], scale=mutation_power)\n return individual\n\n\nif __name__ == \"__main__\":\n sys.path.insert(0, 'evoman')\n from environment import Environment\n\n from demo_controller import player_controller\n\n experiment_name = 'neuro_evolution'\n if not os.path.exists(experiment_name):\n os.makedirs(experiment_name)\n\n df = pd.DataFrame(columns=['value', 'metric', 'gen', 'run', 'enemy_group'])\n\n enemy_groups = [[1, 2, 4, 7], [3, 6, 7, 8]]\n num_runs = 10\n num_hidden_nodes = 10\n\n # EA parameters\n max_generations = 20\n population_size = 50\n \n # per species\n survival_rate = 0.2\n num_elites = 1\n \n initial_species = 10\n min_species = 3\n min_species_size = 2\n max_stagnation = 10\n \n mutation_params = {\n \"mutation_rate\": 0.7,\n \"mutation_power\": 0.5,\n \"mutation_replace_rate\": 0.1\n }\n\n for e, enemies in enumerate(enemy_groups):\n\n env = Environment(experiment_name=experiment_name,\n enemies=enemies,\n multiplemode='yes',\n player_controller=player_controller(num_hidden_nodes))\n\n for r in range(num_runs):\n\n population = init_population(population_size, 20, 5, num_hidden_nodes, initial_species)\n num_species = initial_species\n stagnation_array = [[0, -99] for _ in range(num_species)] # [stagnation counter, max_fitness]\n winner = [None, 0] # [genome, fitness]\n\n # evaluate all individuals\n for g in range(max_generations):\n\n print(\"GENERATION\", g)\n \n generation_results = []\n elites = []\n parents = []\n max_fitnesses = np.zeros(num_species)\n\n for s, sub_population in enumerate(population):\n species_generation_results = [get_fitness(i, s, individual, env) for i, individual in enumerate(sub_population)]\n generation_results.append(species_generation_results)\n\n # sort by fitness\n sorted_results = sorted(\n species_generation_results,\n key=lambda result: result[\"fitness\"],\n reverse=True\n )\n\n species_max_fitness = sorted_results[0][\"fitness\"]\n max_fitnesses[s] = species_max_fitness\n if species_max_fitness > winner[1]:\n winner_index = sorted_results[0][\"individual_index\"]\n winner = [sub_population[winner_index], species_max_fitness]\n \n # keep elites\n species_elites = [sub_population[result[\"individual_index\"]]\n for result in sorted_results[:num_elites]]\n elites.append(species_elites)\n \n # determine parents which will create children\n num_survivors = max(int(len(sub_population) * survival_rate), min_species_size)\n num_children = len(sub_population) - num_elites\n species_parents = [sub_population[result[\"individual_index\"]]\n for result in sorted_results[:num_survivors]]\n parents.append(species_parents)\n\n max_fitness = max(max_fitnesses)\n sum_fitnesses = 0\n for i in range(num_species):\n sum_species_fitness = 0\n for j in range(len(population[i])):\n fitness = generation_results[i][j][\"fitness\"]\n sum_fitnesses += fitness\n sum_species_fitness += fitness\n \n print(\"species {}: max fit {}, mean fit {}, stag {},{}\".format(i, max_fitnesses[i], sum_species_fitness / len(population[i]), stagnation_array[i][0], stagnation_array[i][1]))\n\n mean_fitness = sum_fitnesses / sum([len(sp) for sp in population])\n print(\"overal: max fit: {}, mean fit {}\".format(max_fitness, mean_fitness))\n\n df = df.append([{'value': max_fitness,\n 'metric': 'max',\n 'gen': g,\n 'run': r,\n 'enemy_group': e\n },\n {'value': mean_fitness,\n 'metric': 'mean',\n 'gen': g,\n 'run': r,\n 'enemy_group': e\n }], ignore_index=True)\n \n # keep track of stagnation\n stagnated_species = []\n population_lost = 0\n argsort = np.argsort(np.argsort(-max_fitnesses)) # double argsort is intented\n for i in range(len(population)):\n if stagnation_array[i][1] < max_fitnesses[i]:\n stagnation_array[i][1] = max_fitnesses[i]\n stagnation_array[i][0] = 0\n else:\n stagnation_array[i][0] += 1\n if stagnation_array[i][0] > max_stagnation and argsort[i] > min_species:\n print(\"species\", i, \"stagnated\")\n stagnated_species.append(i)\n population_lost += len(population[i])\n num_species -= 1\n \n # delete stagnated species\n for i in reversed(stagnated_species):\n del population[i]\n del stagnation_array[i]\n del elites[i]\n del parents[i]\n max_fitnesses = np.delete(max_fitnesses, i)\n \n # grow other species based on their fitness to keep total population the same\n for _ in range(population_lost):\n # choose a random sub population based on their population fitness\n max_fitnesses_shifted = max_fitnesses - min(max_fitnesses) # shift array to make min value 0 (all positive)\n p = max_fitnesses_shifted/sum(max_fitnesses_shifted) # normalize array to make sum(p) = 1\n sub_population = rng.choice(population, p=p)\n np.vstack((sub_population, sub_population[-1])) # sub_population[-1] is just a placeholder to keep track of sub pop size\n\n\n # new population\n for i in range(num_species):\n num_children = len(population[i]) - num_elites\n children = generate_children(parents[i], num_children, mutation_params)\n population[i] = elites[i] + children\n \n print(\"winner:\", winner)\n pickle.dump(winner[0], open('winners/neuro-winner-e{}-r{}'.format(e, r), 'wb'))\n\n df.to_csv('neuro-results.csv', index=False)\n","sub_path":"neuro_evolution.py","file_name":"neuro_evolution.py","file_ext":"py","file_size_in_byte":8986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"542518148","text":"#!/usr/bin/env python\n\n'''\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\nimport logging\nfrom scripts import Script\n\nlogger = logging.getLogger(__name__)\n\nclass EnvReport(Script):\n def execute(self):\n user = self.context.get('user')\n if user is None:\n logger.debug(\"No user found for service '%s' for running env report.\", self.service)\n return\n\n logger.debug(\"Capturing environment for user '%s'\", user)\n cmd = \"su - %s -c 'env' > ${output_dir}/%s_env.txt 2>&1 ;\" % (user, user)\n code, out = self.run_command(cmd)\n if code == 0:\n # Success\n return\n logger.info('Getting user environment command %s returned code=%s, out=%s', cmd, code, out)\n\n","sub_path":"global/python/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"308935662","text":"import inspect\nimport itertools\nimport logging\nimport random\nfrom typing import Collection, List, Optional, TYPE_CHECKING, Tuple, Union\n\nimport discord.ext.commands\n\nfrom . import PokestarBotCog\nfrom ..const import color_str_set, css_colors, discord_colors, role_template_role, user_template_role\nfrom ..converters import ColorConverter, MemberRolesConverter, RolesConverter\nfrom ..utils import Embed, rgb_string_from_int, send_embeds_fields\n\nif TYPE_CHECKING:\n from ..bot import PokestarBot\n\nlogger = logging.getLogger(__name__)\n\n\nclass Roles(PokestarBotCog):\n USER_TEMPLATE = user_template_role\n ROLE_TEMPLATE = role_template_role\n DISCORD_COLORS = discord_colors\n CSS_COLORS = css_colors\n VALID_NAMES = list(DISCORD_COLORS) + list(CSS_COLORS)\n\n @classmethod\n def contains_color_roles(cls, item: Union[discord.Guild, discord.Member]):\n roles = []\n for role in item.roles:\n role: discord.Role\n name = str(role)\n if name in cls.VALID_NAMES or (len(name) == 7 and color_str_set.issuperset(set(name))):\n roles.append(role)\n return roles\n\n def __init__(self, bot: \"PokestarBot\"):\n super().__init__(bot)\n self._last_operation_members = {}\n\n @discord.ext.commands.group(invoke_without_command=True,\n brief=\"Deals with role management\",\n usage=\"subcommand [subcommand_arg_1] [subcommand_arg_2] [...]\")\n @discord.ext.commands.guild_only()\n async def role(self, ctx: discord.ext.commands.Context):\n \"\"\"Manage the roles of members in the Guild. This command itself does nothing, but instead has subcommands.\"\"\"\n await self.bot.generic_help(ctx)\n\n async def _base(self, remove: bool, ctx: discord.ext.commands.Context, role: discord.Role,\n members: List[discord.Member]):\n members = list(set(members))\n embed = Embed(ctx, title=\"Role \" + (\"Removal\" if remove else \"Addition\"), color=discord.Color.green())\n fields = [(\"Role\", role.mention), (\"Number of Users\", len(members))]\n done = []\n async with ctx.typing():\n for member in members:\n method = member.add_roles if not remove else member.remove_roles\n await method(role, reason=\"Mass Role Operation triggered by {}\".format(ctx.author))\n done.append(member.mention)\n fields.append((\"Users Modified\", \"\\n\".join(done)))\n await send_embeds_fields(ctx, embed, fields)\n\n @role.group(invoke_without_command=True,\n brief=\"Assign a role en-masse to users.\",\n usage=\"role_to_assign user_or_role_1 [user_or_role_2] [...]\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def add(self, ctx: discord.ext.commands.Context, role: discord.Role, *member_or_roles: MemberRolesConverter):\n \"\"\"Add a role to all users that are part of the provided user(s) and role(s).\"\"\"\n members = list(itertools.chain(*member_or_roles))\n logger.info(\"Running a role addition operation on %s members with the %s role\", len(members), role)\n self._last_operation_members[\"add\"] = {\"role\": role, \"members\": members}\n await self._base(False, ctx, role, members)\n\n @role.command(brief=\"Create a role and assign members/roles to the created role\",\n usage=\"\\\"role_name\\\" [user_or_role_1] [user_or_role_2] [...]\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def create(self, ctx: discord.ext.commands.Context, role_name: str, *member_or_roles: MemberRolesConverter):\n \"\"\"Creates a role and then assigns members to it.\"\"\"\n logger.info(\"Running role creation operation with role name %s\", role_name)\n role = await ctx.guild.create_role(name=role_name, reason=\"Role creation by {}\".format(ctx.author),\n permissions=ctx.guild.default_role.permissions)\n embed = Embed(ctx, title=\"Role Creation Successful\", color=discord.Color.green())\n embed.add_field(name=\"Role\", value=role.mention)\n await ctx.send(embed=embed)\n await self.add(ctx, role, *member_or_roles)\n\n @role.command(brief=\"List the members of a role or list all roles\",\n usage=\"[role]\")\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def list(self, ctx: discord.ext.commands.Context, *roles: RolesConverter):\n \"\"\"List data about all roles or an individual role.\"\"\"\n roles: Collection[discord.Role]\n if len(roles) == 0: # All roles\n logger.info(\"Requested information on all roles\")\n requested_roles = ctx.guild.roles[1:]\n embed = Embed(ctx, title=\"All Roles\",\n description=\"Each field, with the exception of **Total Roles**, represents the amount of members with that role.\")\n embed.add_field(name=\"Total Roles\", value=str(len(requested_roles)))\n fields = []\n for role in requested_roles:\n fields.append((str(role), str(len(role.members))))\n await send_embeds_fields(ctx, embed, fields)\n else:\n for role in roles:\n embed = Embed(ctx, title=\"Role \" + str(role), color=role.color)\n fields = [(str(key), str(value)) for key, value in\n [(\"Position From Top\", len(role.guild.roles) - (role.position + 1)), (\"Position From Bottom\", role.position),\n (\"Hoisted\", role.hoist), (\"Mentionable By @everyone\", role.mentionable)]]\n members = []\n for permission in (\n \"administrator\", \"manage_guild\", \"manage_roles\", \"manage_channels\", \"kick_members\", \"ban_members\", \"manage_nicknames\",\n \"manage_webhooks\", \"manage_messages\", \"mute_members\", \"deafen_members\", \"move_members\", \"priority_speaker\"):\n value = getattr(role.permissions, permission)\n fields.append((permission.replace(\"_\", \" \").title(), str(value)))\n for member in role.members:\n members.append(member.mention)\n fields.append((\"Members (**{}**)\".format(len(role.members)), \"\\n\".join(members)))\n await send_embeds_fields(ctx, embed, fields)\n\n @role.group(invoke_without_command=True,\n brief=\"Unassign a role en-masse to users.\",\n usage=\"role_to_unassign user_or_role_1 [user_or_role_2] [...]\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def remove(self, ctx: discord.ext.commands.Context, role: discord.Role,\n *member_or_roles: MemberRolesConverter):\n \"\"\"Remove a role to all users that are part of the provided user(s) and role(s).\"\"\"\n members = list(itertools.chain(*member_or_roles))\n logger.info(\"Running a role removal operation on %s members with the %s role\", len(members), role)\n self._last_operation_members[\"remove\"] = {\"role\": role, \"members\": members}\n await self._base(True, ctx, role, members)\n\n @add.command(name=\"reverse\", brief=\"Reverse the last mass role addition\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def add_reverse(self, ctx: discord.ext.commands.Context):\n \"\"\"Reverse the last role addition. Will not reverse role additions that occurred before the bot started up (such as roles added before the\n bot restarted).\"\"\"\n try:\n role = self._last_operation_members[\"add\"][\"role\"]\n members = self._last_operation_members[\"add\"][\"members\"]\n logger.info(\"Running an addition role reversal for the %s role, impacting %s members\", role, len(members))\n await self._base(True, ctx, role, members)\n except KeyError:\n logger.warning(\"No roles have been added since bot startup\")\n await ctx.send(embed=Embed(ctx, color=discord.Color.red(), title=\"No Role Additions So Far\",\n description=\"There have been no role additions since bot startup.\"))\n\n @remove.command(name=\"reverse\", brief=\"Reverse the last mass role addition\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def remove_reverse(self, ctx: discord.ext.commands.Context):\n \"\"\"Reverse the last role removal. Will not reverse role removals that occurred before the bot started up (\n such as roles removed before the bot restarted).\"\"\"\n try:\n role = self._last_operation_members[\"remove\"][\"role\"]\n members = self._last_operation_members[\"remove\"][\"members\"]\n logger.info(\"Running an removal role reversal for the %s role, impacting %s members\", role, len(members))\n await self._base(False, ctx, role, members)\n except KeyError:\n logger.warning(\"No roles have been removed since bot startup\")\n await ctx.send(embed=Embed(ctx, color=discord.Color.red(), title=\"No Role Removals So Far\",\n description=\"There have been no role removals since bot startup.\"))\n\n @role.command(brief=\"Distribute role permissions so that they all have the same permissions as the default role.\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def distribute(self, ctx: discord.ext.commands.Context):\n default = ctx.guild.default_role.permissions.value\n for role in ctx.guild.roles:\n perms = role.permissions.value\n new_perms = discord.Permissions(perms | default)\n if new_perms.value != perms:\n logger.info(\"Copied perms from @everyone onto %s role\", role)\n try:\n await role.edit(permissions=new_perms, reason=\"Copying permissions from @everyone\")\n except discord.Forbidden:\n logger.warning(\"Bot unable to edit any roles from here on out.\")\n embed = Embed(ctx, color=discord.Color.red(), title=\"Unable to edit Role\",\n description=\"The bot is unable to edit the role due to permissions.\")\n embed.add_field(name=\"Role\", value=role.mention)\n await ctx.send(embed=embed)\n break\n else:\n embed = Embed(ctx, color=discord.Color.green(), description=\"The role was updated to have the same permissions as @everyone.\",\n title=\"Role Updated\")\n embed.add_field(name=\"Role\", value=role.mention)\n await ctx.send(embed=embed)\n\n async def pre_create(self):\n async with self.bot.conn.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS SNAPSHOTS(ID INTEGER PRIMARY KEY AUTOINCREMENT, GUILD_ID BIGINT NOT NULL, ROLE BOOLEAN NOT NULL \n DEFAULT TRUE, KEY_ID BIGINT NOT NULL, VALUE_ID BIGINT NOT NULL, UNIQUE (GUILD_ID, KEY_ID, VALUE_ID))\"\"\"):\n pass\n\n async def add_user_snapshot(self, user: discord.Member):\n roles = user.roles[1:]\n async with self.bot.conn.execute(\"\"\"DELETE FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [user.guild.id, user.id]), self.bot.conn.executemany(\n \"\"\"INSERT INTO SNAPSHOTS(GUILD_ID, ROLE, KEY_ID, VALUE_ID) VALUES(?, ?, ?, ?)\"\"\",\n [(user.guild.id, False, user.id, role.id) for role in roles]):\n pass\n return roles\n\n async def add_role_snapshot(self, role: discord.Role):\n members = role.members\n async with self.bot.conn.execute(\"\"\"DELETE FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [role.guild.id, role.id]), self.bot.conn.executemany(\n \"\"\"INSERT INTO SNAPSHOTS(GUILD_ID, ROLE, KEY_ID, VALUE_ID) VALUES(?, ?, ?, ?)\"\"\",\n [(role.guild.id, True, role.id, member.id) for member in members]):\n pass\n return members\n\n @discord.ext.commands.group(brief=\"Manage the Role Snapshots system.\", invoke_without_command=True, aliases=[\"role_snapshot\", \"rolesnapshot\"])\n async def snapshot(self, ctx: discord.ext.commands.Context):\n await self.bot.generic_help(ctx)\n\n @snapshot.command(name=\"add\", brief=\"Add a Role Snapshot.\", usage=\"user_or_role\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n async def snapshot_add(self, ctx: discord.ext.commands.Context, user_or_role: Union[discord.Member, discord.Role]):\n await self.pre_create()\n if isinstance(user_or_role, discord.Role):\n l_item_name = \"Provided Role\"\n r_item_name = \"Members\"\n r_item = await self.add_role_snapshot(user_or_role)\n else:\n l_item_name = \"Provided Member\"\n r_item_name = \"Roles\"\n r_item = await self.add_user_snapshot(user_or_role)\n embed = Embed(ctx, title=\"Snapshot Saved\", description=\"The snapshot has been saved.\", color=discord.Color.green())\n await send_embeds_fields(ctx, embed,\n [(l_item_name, user_or_role.mention), (r_item_name, \"\\n\".join(item.mention for item in r_item) or \"None\")])\n\n @snapshot.command(name=\"list\", brief=\"List all Guild Role Snapshots.\", usage=\"[user_or_role]\")\n async def snapshot_list(self, ctx: discord.ext.commands.Context, user_or_role: Optional[Union[discord.Member, discord.Role]] = None):\n await self.pre_create()\n if user_or_role is None:\n async with self.bot.conn.execute(\"\"\"SELECT DISTINCT KEY_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND ROLE==TRUE\"\"\", [ctx.guild.id]) as cursor:\n role_ids = {role async for role, in cursor}\n async with self.bot.conn.execute(\"\"\"SELECT DISTINCT KEY_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND ROLE==FALSE\"\"\", [ctx.guild.id]) as cursor:\n member_ids = {member async for member, in cursor}\n roles = [ctx.guild.get_role(role_id) for role_id in role_ids]\n members = [ctx.guild.get_member(member_id) for member_id in member_ids]\n embed = Embed(ctx, title=\"Role Snapshots For Current Guild\")\n fields = [(\"Roles\", \"\\n\".join(role.mention if role else \"[Deleted Role]\" for role in roles) or \"None\"),\n (\"Members\", \"\\n\".join(member.mention if member else \"[Not in Guild/Deleted User]\" for member in members) or \"None\")]\n await send_embeds_fields(ctx, embed, fields)\n else:\n if isinstance(user_or_role, discord.Role):\n async with self.bot.conn.execute(\"\"\"SELECT VALUE_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [ctx.guild.id, user_or_role.id]) as cursor:\n member_ids = {member async for member, in cursor}\n if len(member_ids) == 0: # Not Found or Empty Snapshot\n embed = Embed(ctx, title=\"Snapshot Not Found\",\n description=\"The Snapshot for the provided role does not exist. This can also occur if a Snapshot was saved for a \"\n \"role that contained no users.\",\n color=discord.Color.red())\n embed.add_field(name=\"Role\", value=user_or_role.mention)\n return await ctx.send(embed=embed)\n members = [ctx.guild.get_member(member_id) for member_id in member_ids]\n embed = Embed(ctx, title=\"Snapshot\", description=f\"The Snapshot for role {user_or_role.mention} contains **{len(members)}** members.\",\n color=discord.Color.green())\n await send_embeds_fields(ctx, embed, [\"\\n\".join(member.mention if member else \"[Not in Guild/Deleted User]\" for member in members)])\n else:\n async with self.bot.conn.execute(\"\"\"SELECT VALUE_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [ctx.guild.id, user_or_role.id]) as cursor:\n role_ids = {role async for role, in cursor}\n if len(role_ids) == 0: # Not Found or Empty Snapshot\n embed = Embed(ctx, title=\"Snapshot Not Found\",\n description=\"The Snapshot for the provided Member does not exist. This can also occur if a Snapshot was saved for \"\n \"a \"\n \"Member that contained no roles.\",\n color=discord.Color.red())\n embed.add_field(name=\"Member\", value=user_or_role.mention)\n return await ctx.send(embed=embed)\n roles = [ctx.guild.get_role(role_id) for role_id in role_ids]\n embed = Embed(ctx, title=\"Snapshot\", description=f\"The Snapshot for Member {user_or_role.mention} contains **{len(roles)}** roles.\",\n color=discord.Color.green())\n await send_embeds_fields(ctx, embed, [\"\\n\".join(role.mention if role else \"[Deleted Role]\" for role in roles)])\n\n @snapshot.command(name=\"use\", aliases=[\"release\", \"replay\", \"apply\", \"copy\"], brief=\"Copy the members or roles in a Snapshot back to the guild.\",\n usage=\"user_or_role\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def snapshot_use(self, ctx: discord.ext.commands.Context, user_or_role: Union[discord.Member, discord.Role]):\n await self.pre_create()\n if isinstance(user_or_role, discord.Role):\n async with self.bot.conn.execute(\"\"\"SELECT VALUE_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [ctx.guild.id, user_or_role.id]) as cursor:\n member_ids = {member async for member, in cursor}\n if len(member_ids) == 0: # Not Found or Empty Snapshot\n embed = Embed(ctx, title=\"Snapshot Not Found\",\n description=\"The Snapshot for the provided role does not exist. This can also occur if a Snapshot was saved for a \"\n \"role that contained no users.\",\n color=discord.Color.red())\n embed.add_field(name=\"Role\", value=user_or_role.mention)\n return await ctx.send(embed=embed)\n members = [ctx.guild.get_member(member_id) for member_id in member_ids]\n failed = []\n success = []\n for member in members:\n member: Optional[discord.Member]\n if member:\n try:\n await member.add_roles(user_or_role, reason=f\"Replaying of Snapshot for Role {user_or_role}\")\n except discord.Forbidden:\n failed.append(member)\n else:\n success.append(member)\n else:\n failed.append(member)\n embed = Embed(ctx, title=\"Snapshot Used\",\n description=f\"The Snapshot for role {user_or_role.mention} was added to **{len(members)}** members.\",\n color=discord.Color.green())\n await send_embeds_fields(ctx, embed, [\n (\"Succeeded\", \"\\n\".join(member.mention if member else \"[Not in Guild/Deleted User]\" for member in success) or None),\n (\"Failed\", \"\\n\".join(member.mention if member else \"[Not in Guild/Deleted User]\" for member in failed) or None)])\n else:\n async with self.bot.conn.execute(\"\"\"SELECT VALUE_ID FROM SNAPSHOTS WHERE GUILD_ID==? AND KEY_ID==?\"\"\",\n [ctx.guild.id, user_or_role.id]) as cursor:\n role_ids = {role async for role, in cursor}\n if len(role_ids) == 0: # Not Found or Empty Snapshot\n embed = Embed(ctx, title=\"Snapshot Not Found\",\n description=\"The Snapshot for the provided Member does not exist. This can also occur if a Snapshot was saved for a \"\n \"Member that contained no roles.\",\n color=discord.Color.red())\n embed.add_field(name=\"Member\", value=user_or_role.mention)\n return await ctx.send(embed=embed)\n roles = [ctx.guild.get_role(role_id) for role_id in role_ids]\n failed = []\n success = []\n for role in roles:\n if role:\n try:\n await user_or_role.add_roles(role, reason=f\"Replaying of Snapshot for User {user_or_role}\")\n except discord.Forbidden:\n failed.append(role)\n else:\n success.append(role)\n else:\n failed.append(role)\n embed = Embed(ctx, title=\"Snapshot Used\",\n description=f\"The Snapshot for Member {user_or_role.mention} was used to add **{len(roles)}** roles.\",\n color=discord.Color.green())\n await send_embeds_fields(ctx, embed, [(\"Succeeded\", \"\\n\".join(role.mention if role else \"[Deleted Role]\" for role in success) or None),\n (\"Failed\", \"\\n\".join(role.mention if role else \"[Deleted Role]\" for role in failed) or \"None\")])\n\n @snapshot.command(name=\"all\", brief=\"Generate a Snapshot for all users and all roles.\")\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n async def snapshot_all(self, ctx: discord.ext.commands.Context):\n await ctx.send(embed=Embed(ctx, title=\"Starting Generation Of All Snapshots.\", color=discord.Color.green()))\n for member in ctx.guild.members:\n await self.snapshot_add(ctx, member)\n for role in ctx.guild.roles[1:]:\n await self.snapshot_add(ctx, role)\n await ctx.send(embed=Embed(ctx, title=\"Finished Generation Of All Snapshots.\", color=discord.Color.green()))\n\n @discord.ext.commands.group(brief=\"Give yourself a role with the specified color\", usage=\"[member] color\", invoke_without_command=True, significant=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def color(self, ctx: discord.ext.commands.Context, member: Optional[discord.Member], color: ColorConverter):\n member = member or ctx.author\n if member != ctx.author:\n if not ctx.author.guild_permissions.manage_roles:\n raise discord.ext.commands.MissingPermissions([\"manage_roles\"])\n color: Tuple[Optional[str], int]\n if color[0]:\n search_str = color[0]\n else:\n search_str = rgb_string_from_int(color[1])\n existing_role = None\n for role in ctx.guild.roles:\n role: discord.Role\n if str(role) == search_str:\n existing_role = role\n break\n user_has_roles = self.contains_color_roles(member)\n if user_has_roles:\n embed = Embed(ctx, title=\"Removed Existing Roles\", description=\"The existing color roles that the user had has been removed.\",\n color=discord.Color.green())\n embed.add_field(name=\"User\", value=member.mention)\n await member.remove_roles(*(role for role in user_has_roles if role != existing_role), reason=\"Removing Duplicate Color Roles\")\n await send_embeds_fields(ctx, embed, [(\"Role(s)\", \"\\n\".join(role.mention for role in user_has_roles if role != existing_role))])\n if existing_role:\n role = existing_role\n if existing_role in member.roles:\n embed = Embed(ctx, title=\"Already Has Role\",\n description=f\"{member.mention} already has the color role, so they will not be assigned the role again.\",\n color=discord.Color.green())\n embed.add_field(name=\"Role\", value=existing_role.mention)\n return await ctx.send(embed=embed)\n try:\n await member.add_roles(existing_role, reason=f\"Assigning Color by {ctx.author}\")\n except discord.Forbidden:\n embed = Embed(ctx, title=\"Cannot Assign\",\n description=\"The bot could not assign the role as the color role is higher than the bot's role.\",\n color=discord.Color.red())\n embed.add_field(name=\"Role\", value=existing_role.mention)\n return await ctx.send(embed=embed)\n else:\n role = await ctx.guild.create_role(name=search_str, color=discord.Color(color[1]), permissions=ctx.guild.default_role.permissions,\n reason=f\"Assigning Color by {ctx.author}\")\n await member.add_roles(role, reason=f\"Assigning Color by {ctx.author}\")\n embed = Embed(ctx, title=\"Assigned Color Role\", description=f\"Assigned role to {member.mention}\", color=discord.Color(color[1]))\n embed.add_field(name=\"Role\", value=role.mention)\n await ctx.send(embed=embed)\n\n @color.group(name=\"list\", brief=\"Get the color names that can be used.\", invoke_without_command=True)\n async def color_list(self, ctx: discord.ext.commands.Context):\n discord_colors_str = \"\\n\".join(f\"{key}: {value}\" for key, value in self.DISCORD_COLORS.items())\n css_colors_str = \"\\n\".join(f\"{key}: {value}\" for key, value in self.CSS_COLORS.items())\n fields = [(\"Discord Colors\", discord_colors_str), (\"Other Colors\", css_colors_str)]\n await send_embeds_fields(ctx, Embed(ctx, title=\"Valid Colors\"), fields)\n\n @color_list.command(name=\"existing\", brief=\"Get the list of color roles that currently exist on the server.\")\n @discord.ext.commands.guild_only()\n async def color_existing(self, ctx: discord.ext.commands.Context):\n roles = self.contains_color_roles(ctx.guild)\n await send_embeds_fields(ctx, Embed(ctx, title=\"Existing Color Roles\"), [(\"Count\", str(len(roles))), (\n \"Roles\", \"\\n\".join(f\"{role}: {' '.join(member.mention for member in role.members) or 'No Members'}\" for role in roles))])\n\n @color.command(name=\"info\", brief=\"Get information about a color\", usage=\"color [color] [...]\", significant=True)\n async def color_info(self, ctx: discord.ext.commands.Context, *colors: ColorConverter):\n if len(colors) == 0:\n raise discord.ext.commands.MissingRequiredArgument(inspect.Parameter(\"color\", inspect.Parameter.POSITIONAL_ONLY))\n for color in colors:\n color: Tuple[Optional[str], int]\n if color[0]:\n title = color[0]\n hex_str = rgb_string_from_int(color[1])\n else:\n title = hex_str = rgb_string_from_int(color[1])\n embed = Embed(ctx, title=title, color=discord.Color(color[1]))\n embed.add_field(name=\"Hex Value\", value=hex_str)\n await ctx.send(embed=embed)\n\n @color.command(name=\"remove\", brief=\"Remove your color role\", usage=\"[member]\")\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n async def color_remove(self, ctx: discord.ext.commands.Context, member: Optional[discord.Member]):\n member = member or ctx.author\n if member != ctx.author:\n if not ctx.author.guild_permissions.manage_roles:\n raise discord.ext.commands.MissingPermissions([\"manage_roles\"])\n user_has_roles = self.contains_color_roles(member)\n if user_has_roles:\n embed = Embed(ctx, title=\"Removed Existing Roles\", description=\"The existing color roles that the user had has been removed.\",\n color=discord.Color.green())\n embed.add_field(name=\"User\", value=member.mention)\n await member.remove_roles(*(role for role in user_has_roles), reason=\"Removing Duplicate Color Roles\")\n await send_embeds_fields(ctx, embed, [\"\\n\".join(role.mention for role in user_has_roles)])\n else:\n embed = Embed(ctx, title=\"Had No Roles\", description=\"The user had no color roles.\", color=discord.Color.green())\n embed.add_field(name=\"User\", value=member.mention)\n await ctx.send(embed=embed)\n\n @color.command(name=\"clean\", brief=\"Cleans all other roles of color.\", significant=True)\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n async def color_clean_all(self, ctx: discord.ext.commands.Context):\n roles = self.contains_color_roles(ctx.guild)\n cleaned = []\n for role in ctx.guild.roles:\n role: discord.Role\n if role not in roles and role.color != discord.Color.default():\n await role.edit(color=discord.Color.default(), reason=\"Cleaning all non-color roles of color.\")\n cleaned.append(role)\n await send_embeds_fields(ctx, Embed(ctx, title=\"Cleaned Roles\", description=\"All non-color roles are now cleaned of color.\",\n color=discord.Color.green()), [(\"Roles Cleaned\", \"\\n\".join(role.mention for role in cleaned) or \"None\")])\n\n @color.command(name=\"prune\", brief=\"Prunes all color roles that aren't being used.\")\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n async def color_prune(self, ctx: discord.ext.commands.Context):\n roles = self.contains_color_roles(ctx.guild)\n cleaned = []\n for role in roles:\n if len(role.members) < 1:\n await role.delete(reason=\"Pruning Unused Roles\")\n cleaned.append(role)\n await send_embeds_fields(ctx, Embed(ctx, title=\"Pruned Roles\", description=\"All color roles without any members are now pruned.\",\n color=discord.Color.green()),\n [(\"Roles Pruned\", \"\\n\".join(str(role) + \" (\" + role.mention + \")\" for role in cleaned) or \"None\")])\n\n @color.command(brief=\"Give every user without a color a randomized color.\")\n @discord.ext.commands.bot_has_guild_permissions(manage_roles=True)\n @discord.ext.commands.has_guild_permissions(manage_roles=True)\n async def random(self, ctx: discord.ext.commands.Context):\n converter = ColorConverter()\n for member in ctx.guild.members:\n roles = self.contains_color_roles(member)\n if not roles:\n color = random.choice(list(self.DISCORD_COLORS) + list(self.CSS_COLORS))\n await self.color(ctx, member, await converter.convert(ctx, color))\n await ctx.send(embed=Embed(ctx, title=\"Completed\", color=discord.Color.green()))\n\n\ndef setup(bot: \"PokestarBot\"):\n bot.add_cog(Roles(bot))\n logger.info(\"Loaded the Roles extension.\")\n\n\ndef teardown(_bot: \"PokestarBot\"):\n logger.warning(\"Unloading the Roles extension.\")\n","sub_path":"bot_data/extensions/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":31723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"441772049","text":"from .mlp import MLP\nfrom collections import OrderedDict\nfrom itertools import count\nimport torch\n\n\nclass MLPEnsemble:\n def __init__(self, layers, n_models, reduction='mean', **kwargs):\n self.n_models = n_models\n self.models = [MLP(layers, **kwargs) for i in range(n_models)]\n self.reduction = reduction\n\n def fit(self, train_set, val_set, verbose=True, **kwargs):\n for i, model in enumerate(self.models): \n self._print_fit_status(i+1, self.n_models)\n model.fit(train_set, val_set, verbose=verbose, **kwargs)\n \n def state_dict(self):\n state_dict = OrderedDict({'{} model'.format(n): m.state_dict() \n for n, m in zip(count(), self.models)})\n return state_dict\n \n def load_state_dict(self, state_dict):\n for n, m in enumerate(self.models):\n m.load_state_dict(state_dict['{} model'.format(n)])\n \n def train(self):\n [m.train() for m in self.models]\n \n def eval(self):\n [m.eval() for m in self.models]\n \n def __call__(self, x, reduction='default', **kwargs):\n if 'dropout_mask' in kwargs and isinstance(kwargs['dropout_mask'], list):\n masks = kwargs.pop('dropout_mask')\n res = torch.stack([m(x, dropout_mask = dpm, **kwargs) for m, dpm in zip(self.models, masks)])\n else:\n res = torch.stack([m(x, **kwargs) for m in self.models])\n\n if reduction == 'default':\n reduction = self.reduction\n\n if reduction is None:\n res = res\n elif reduction == 'mean':\n res = res.mean(dim=0)\n elif reduction == 'nll':\n means = res[:, :, 0]\n sigmas = res[:, :, 1]\n res = torch.stack([means.mean(dim=0), sigmas.mean(dim=0) +\n (means**2).mean(dim=0) - means.mean(dim=0)**2], dim=1)\n return res\n \n def _print_fit_status(self, n_model, n_models):\n print('Fit [{}/{}] model:'.format(n_model, n_models))\n","sub_path":"2020/alpaca-master stat-mlalpaca/alpaca/model/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"180684206","text":"from django.conf import settings\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Ussd, Management\nimport requests\n\n\n@csrf_exempt\ndef index(request):\n try:\n call = request.GET.get('call')\n sessionid = request.GET['sessionid']\n phone = request.GET['phone']\n Ussd.objects.create(call=call, sessionid=sessionid, phone=phone)\n has_admin = Management.objects.filter(phone=phone)\n if has_admin.exists():\n return HttpResponse('خوش آمدید', content_type='text/plain')\n else:\n return HttpResponse('سامانه در حال بروزرسانی است. لطفا شکیبا باشید.', content_type='text/plain')\n except Exception as e:\n return HttpResponse('سلام', content_type='text/plain')\n\n\n\n\n\ndef get_customer(request):\n phone = '09360245484'\n url = settings.BARSHIC_WEB_SERVICE + f'get_customer?celphone={phone}&sh_kart=0&sal=1399&date_today=0&ramz=CRM5682&karbar=1'\n customer = requests.get(url)\n data = customer.json()\n request.session[phone] = data\n request.session[phone]['name_masraf'] = request.session[phone]['name_masraf'].replace('-', ' ')\n return HttpResponse(request.session[phone]['name_masraf'])\n\n\ndef get_charge(request):\n phone = '09360245484'\n sh_kart = request.session[phone]['sh_kart']\n url = settings.BARSHIC_WEB_SERVICE + f'get_charge?celphone={phone}&sh_kart={sh_kart}&sal=1399&ramz=CRM5682&karbar=1'\n charge = requests.get(url)\n data = charge.json()\n return HttpResponse(data)\n\n\ndef get_sum_forosh(request):\n pass\n","sub_path":"ussd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554166700","text":"def oType (assembly):\n zero = \"00000000\"\n zeroOfInstruction = \"000000000000000000000\"\n temp_inst = assembly.split('\\t')\n inst = (str(temp_inst[1])).split('\\n')\n if ( inst[0] == 'halt'):\n opcode = '110'\n elif ( inst[0] == 'noop'):\n opcode = '111'\n else:\n opcode = 'error'\n MachineCode = zero + opcode + zeroOfInstruction\n return MachineCode\n\n\n\n","sub_path":"O_type.py","file_name":"O_type.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"33041918","text":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw\nimport numpy as np\nfrom tqdm import tqdm\n\nvolunteers = pd.read_csv(\"resolution.tsv\",sep=\"\\t\",index_col=\"id\")\n\nos.makedirs('../masks', exist_ok=True)\nImage.new('I', (472,512), 0).save('../masks/empty_472x512.png')\nImage.new('I', (512,472), 0).save('../masks/empty_512x472.png')\n\nfor volunteerId,volunteer in tqdm(volunteers.iterrows()):\n contour = pd.read_csv(\"{}.tsv\".format(volunteerId),sep=\" \",names=[\"x\",\"y\",\"z\",\"t\",\"c\"],usecols=range(5))\n iters = contour.iloc[:,2:4].drop_duplicates().to_numpy()\n for i in tqdm(iters, leave=False):\n z = i[0]\n t = i[1]\n poly = [(x[0],x[1]) for x in contour[contour.z==z][contour.t==t][contour.c==1].to_numpy()[:,0:2]]\n img = Image.new('L', (volunteer[\"columns\"], volunteer[\"rows\"]), 0)\n if(len(poly)>1):\n ImageDraw.Draw(img).polygon(poly, outline=1, fill=1)\n mask = np.array(img)\n poly2 = [(x[0],x[1]) for x in contour[contour.z==z][contour.t==t][contour.c==0].to_numpy()[:,0:2]]\n img = Image.new('L', (volunteer[\"columns\"], volunteer[\"rows\"]), 0)\n if(len(poly2)>1):\n ImageDraw.Draw(img).polygon(poly2, outline=1, fill=1)\n mask2 = np.array(img)\n im_array = 2*mask.astype(np.int32)-mask2\n im = Image.fromarray(im_array, 'I')\n im.save('../masks/{}_slice{:03d}_frame{:03d}-mask.png'.format(volunteerId,z,t))\n","sub_path":"code/7T/con2png.py","file_name":"con2png.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"504776724","text":"#This is what will actually create the iCalendar\nimport random\n\ndef iCalWrite(times, yearmonth,endyearmonthdaytime, sdates, dnames, filename):\n\n ical = open(filename,'w')\n ical.write('BEGIN:VCALENDAR\\nPRODID:-//Olin iCalCreation//Python//EN\\nVERSION:2.0\\n')\n\n# NOW WE GET INTO THE MEATY BUSINESS\n\n\n for i in range(len(times)):\n for j in range(len(times[i][0])):\n if times[i][1] != '0000':\n # This essentially just writes a new event for each time slot\n ical.write('BEGIN:VEVENT\\n')\n day = sdates[times[i][0][j]]\n ical.write('UUID:'+ yearmonth + day + str( random.randint(100000000,999999999))+'\\n')\n ical.write('DTSTART:' + yearmonth + day +'T' + times[i][1] +'00\\n')\n ical.write('DTEND:' + yearmonth + day + 'T' + times[i][2] + '00\\n')\n ical.write('SUMMARY:' + dnames[i] + '\\n')\n ical.write('RRULE:FREQ=WEEKLY;UNTIL='+endyearmonthdaytime + '\\n')\n ical.write('END:VEVENT\\n')\n\n\n\n # Ending up the ical file with all the business of ending an .ics file.\n ical.write('END:VCALENDAR')\n\n\n","sub_path":"app/iCalCreation.py","file_name":"iCalCreation.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"332027835","text":"__author__ = 'yinjun'\n\nclass Solution:\n \"\"\"\n @param triangle: a list of lists of integers.\n @return: An integer, minimum path sum.\n \"\"\"\n def minimumTotal(self, triangle):\n # write your code here\n\n if triangle == None or triangle == []:\n return 0\n\n n = len(triangle)\n\n path=[[0 for j in range(n)] for i in range(n)]\n\n\n path[0][0] = triangle[0][0]\n\n for i in range(1, n):\n path[i][0] =path[i-1][0]+ triangle[i][0]\n\n for i in range(1, n):\n for j in range(1, i+1):\n\n if i == j:\n path[i][j] = path[i-1][j-1] + triangle[i][j]\n else:\n path[i][j] = min(path[i-1][j-1], path[i-1][j]) + triangle[i][j]\n\n #print path\n return min(path[n-1])","sub_path":"LeetCode/python/091-120/120-triangle/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"586459955","text":"class CustomerProject(object):\n\n\tdef __init__(self, customer_project_item):\n\t\t# , contract_number, customer_id, customer_name, project_id, project_subsegment, project_name, account_manager, segment_manager, project_coordinator):\n\t\t# self.contract_number = contract_number\n\t\t# self.customer_id = customer_id\n\t\t# self.customer_name = customer_name\n\t\t# self.project_id = project_id\n\t\t# self.project_subsegment = project_subsegment\n\t\t# self.project_name = project_name\n\t\t# self.account_manager = account_manager\n\t\t# self.segment_manager = segment_manager\n\t\t# self.project_coordinator = project_coordinator\n\n\t\tself.contract_number = customer_project_item['contract_number']\n\t\tself.customer_id = str(customer_project_item['customer_id'])\n\t\tself.customer_name = customer_project_item['customer_name']\n\t\tself.project_id = str(customer_project_item['project_id'])\n\t\tself.project_subsegment = customer_project_item['project_subsegment']\n\t\tself.project_name = customer_project_item['project_name']\n\t\tself.account_manager = customer_project_item['account_manager']\n\t\tself.segment_manager = customer_project_item['segment_manager']\n\t\tself.project_coordinator = \"DESMOND TOH AEN BEE\"\n\t\t# self.project_coordinator = customer_project_item['project_coordinator']\n\n\tdef values(self):\n\t\tvalue_array = []\n\t\tvalue_array.append(self.contract_number)\n\t\tvalue_array.append(self.customer_id)\n\t\tvalue_array.append(self.customer_name)\n\t\tvalue_array.append(self.project_id)\n\t\tvalue_array.append(self.project_subsegment)\n\t\tvalue_array.append(self.project_name)\n\t\tvalue_array.append(self.account_manager)\n\t\tvalue_array.append(self.segment_manager)\n\t\tvalue_array.append(self.project_coordinator)\n\t\t\n\n\tdef __str__(self):\n\t\treturn(\"Customer_Project:\\n\"\n\t\t\t\"\tContract Number = {0}\\n\"\n\t\t\t\"\tCustomer ID = {1}\\n\"\n\t\t\t\"\tCustomer Name = {2}\\n\"\n\t\t\t\"\tProject ID = {3}\\n\"\n\t\t\t\"\tProject Subsegment = {4}\\n\"\n\t\t\t\"\tProject Name = {5}\\n\"\n\t\t\t\"\tAccount Manager = {6}\\n\"\n\t\t\t\"\tSegment Manager = {7}\\n\"\n\t\t\t\"\tProject Coordinator = {8}\\n\"\n\t\t\t.format(self.contract_number, self.customer_id, self.customer_name, self.project_id, \n\t\t\t\tself.project_subsegment, self.project_name, self.account_manager, self.segment_manager, self.project_coordinator))\n","sub_path":"support_classes/customerproject.py","file_name":"customerproject.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"451333719","text":"#\n# @lc app=leetcode id=95 lang=python3\n#\n# [95] Unique Binary Search Trees II\n#\n# https://leetcode.com/problems/unique-binary-search-trees-ii/description/\n#\n# algorithms\n# Medium (37.80%)\n# Likes: 1650\n# Dislikes: 134\n# Total Accepted: 163K\n# Total Submissions: 430.7K\n# Testcase Example: '3'\n#\n# Given an integer n, generate all structurally unique BST's (binary search\n# trees) that store values 1 ... n.\n#\n# Example:\n#\n#\n# Input: 3\n# Output:\n# [\n# [1,null,3,2],\n# [3,2,null,1],\n# [3,1,null,null,2],\n# [2,1,3],\n# [1,null,2,null,3]\n# ]\n# Explanation:\n# The above output corresponds to the 5 unique BST's shown below:\n#\n# ⁠ 1 3 3 2 1\n# ⁠ \\ / / / \\ \\\n# ⁠ 3 2 1 1 3 2\n# ⁠ / / \\ \\\n# ⁠ 2 1 2 3\n#\n#\n#\n\n# @lc code=start\n# Definition for a binary tree node.\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n return self.dp_soln(n)\n\n def dp_soln(self, n: int) -> List[TreeNode]:\n \"\"\"\n DP Solution\n \"\"\"\n if n == 0:\n return []\n\n def helper(i: int, n: int) -> None:\n res = []\n if i > n:\n res.append(None)\n return res\n if i == n:\n res.append(TreeNode(i))\n return res\n for j in range(i, n + 1):\n left_trees = helper(i, j - 1)\n right_trees = helper(j + 1, n)\n\n for left_node in left_trees:\n for right_node in right_trees:\n curr_node = TreeNode(j)\n curr_node.left = left_node\n curr_node.right = right_node\n res.append(curr_node)\n return res\n\n return helper(1, n)\n# @lc code=end\n\n\nif __name__ == \"__main__\":\n soln = [\n [1, None, 3, 2],\n [3, 2, None, 1],\n [3, 1, None, None, 2],\n [2, 1, 3],\n [1, None, 2, None, 3]\n ]\n\n print(Solution().generateTrees(3))\n print(soln)\n","sub_path":"Python/95.unique-binary-search-trees-ii.py","file_name":"95.unique-binary-search-trees-ii.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"410198012","text":"import time\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom .models import ChatBase, Client\n\n\n# Create your views here.\n\n\ndef index(request):\n return render(request, 'chatapp/index.html', {})\n\n\ndef list_chat_to(request, chat_from):\n clients_list = ChatBase.objects.filter(chat_from__client_name = chat_from).values(\"chat_to__client_name\",\"chat_from__client_name\").distinct()\n print(clients_list)\n\n context = {\n \"clients_list\": clients_list,\n \"chat_from\" : chat_from\n }\n return render(request, 'chatapp/list_chat_to.html', context)\n\n\ndef get_chats(request, chat_from, chat_to):\n chat_texts_list = ChatBase.objects.filter(chat_from__client_name = chat_from, chat_to__client_name = chat_to) | ChatBase.objects.filter(chat_to__client_name = chat_from, chat_from__client_name = chat_to)\n chat_texts_list = chat_texts_list.order_by(\"chat_date\")\n context = {\n \"chat_texts_list\": chat_texts_list,\n \"chat_from\": chat_from,\n \"chat_to\": chat_to\n }\n return render(request, 'chatapp/chat_texts.html', context)\n\n\ndef send_text(request):\n chat_from = request.POST[\"chat_from\"]\n chat_to = request.POST[\"chat_to\"]\n chat_text = request.POST[\"chat_text\"]\n cf = Client.objects.get(client_name=chat_from)\n ct = Client.objects.get(client_name=chat_to)\n chatbase = ChatBase(chat_from= cf, chat_text= chat_text, chat_to= ct)\n chatbase.save()\n return HttpResponseRedirect(reverse('get_chats', args=(chat_from,chat_to)))\n\ndef reload(request, chat_from, chat_to):\n chat_from = request.POST[\"chat_from\"]\n chat_to = request.POST[\"chat_to\"]\n req_time = request.POST[\"req_time\"]\n req_time = timezone.datetime.strptime(req_time, \"%a, %d %b %Y %H:%M:%S %Z\")\n req_time = req_time.replace(tzinfo=timezone.utc)\n\n for i in range(0, 30):\n chatbase = ChatBase.objects.filter(chat_date__gte=req_time)\n if chatbase:\n return HttpResponseRedirect(reverse('get_chats', args=(chat_from, chat_to)))\n time.sleep(3)\n return HttpResponseRedirect(reverse('get_chats', args=(chat_from, chat_to)))","sub_path":"chatapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"9268738","text":"# You are given a number of sticks of varying\n# lengths. You will iteratively cut the sticks\n# into smaller sticks, discarding the shortest pieces\n# until there are none left. At each iteration you will\n# determine the length of the shortest stick remaining,\n# cut that length from each of the longer sticks and then\n# discard all the pieces of that shortest length. When all\n# the remaining sticks are the same length, they cannot be\n# shortened so discard them.\n# Given the lengths of n sticks, print the number of sticks that\n# are left before each iteration until there are none left.\n\n\ndef cut_the_sticks(arr):\n li = []\n while len(arr) >= 1:\n li.append(len(arr))\n minimum = min(arr)\n arr = [i - minimum for i in arr if i != minimum]\n return li\n\n\nar = [5, 4, 4, 2, 2, 8]\nli = cut_the_sticks(ar)\nprint(li)\n","sub_path":"cut_the_sticks.py","file_name":"cut_the_sticks.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"151725160","text":"\nimport tensorflow as tf\nimport dlib\nimport cv2\nimport argparse\nimport face_recognition\nfrom tensorflow.keras import datasets, layers, models,callbacks,preprocessing\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import Normalizer\nfrom scipy.ndimage import zoom\nfrom scipy.spatial import distance\nimport imutils\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\nimport time\nimport pickle\nfrom imutils import face_utils\nimport os\nimport h5py\nap = argparse.ArgumentParser()\nap.add_argument(\"-m\", \"--model\", required=True,\n\thelp=\"path to input video\")\nap.add_argument(\"-i\", \"--input\", type=str,\n\thelp=\"path to output video\")\nap.add_argument(\"-o\", \"--output\", type=str,\n\thelp=\"path to output video\")\nap.add_argument(\"-p\",\"--pickle\",type=str)\nap.add_argument(\"-l\",\"--landmark\",type=str)\nargs = vars(ap.parse_args())\n## in_encoder = Normalizer()\n# out_encoder = LabelEncoder()\nshape_x = 48\nshape_y = 48\ninput_shape = (shape_x, shape_y, 1)\nnClasses = 7\n\nthresh = 0.25\nframe_check = 20\ndata_faces = pickle.loads(open(args[\"pickle\"], \"rb\").read())\ne_model = models.load_model(args[\"model\"])\n# f_model = pickle.load(open(face_model_path, 'rb'))\n# print(e_model.summary())\nobjects = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']\n(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n\n(nStart, nEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"nose\"]\n(mStart, mEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"mouth\"]\n(jStart, jEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"jaw\"]\n\n(eblStart, eblEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eyebrow\"]\n(ebrStart, ebrEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eyebrow\"]\n\nface_detect = dlib.get_frontal_face_detector()\npredictor_landmarks = dlib.shape_predictor(args['landmark'])\n#faceCascade = cv2.CascadeClassifier(args['landmark'])\ndef rec_face(rgb):\n boxes = boxes = face_recognition.face_locations(rgb,model='cnn')\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n\n # loop over the facial embeddings\n for encoding in encodings:\n # attempt to match each face in the input image to our known\n # encodings\n matches = face_recognition.compare_faces(data_faces[\"encodings\"],encoding)\n name = \"Unknown\"\n\n # check to see if we have found a match\n if True in matches:\n # find the indexes of all matched faces then initialize a\n # dictionary to count the total number of times each face\n # was matched\n matchedIdxs = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n\n # loop over the matched indexes and maintain a count for\n # each recognized face face\n for i in matchedIdxs:\n name = data_faces[\"names\"][i]\n counts[name] = counts.get(name, 0) + 1\n\n # determine the recognized face with the largest number\n # of votes (note: in the event of an unlikely tie Python\n # will select first entry in the dictionary)\n name = max(counts, key=counts.get)\n\n # update the list of names\n return name\n\ndef detect_face(frame):\n\n # Cascade classifier pre-trained model\n # BGR -> Gray conversion\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Cascade MultiScale classifier\n detected_faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=6,\n minSize=(shape_x, shape_y),\n flags=cv2.CASCADE_SCALE_IMAGE)\n coord = []\n\n for x, y, w, h in detected_faces:\n if w > 100:\n sub_img = frame[y:y + h, x:x + w]\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 1)\n coord.append([x, y, w, h])\n\n return gray, detected_faces, coord\n\n# def facecrop(imagepath):\n# facedata = \"/content/drive/My Drive/Camera_detection/haarcascade_frontalface_alt.xml\"\n# cascade = cv2.CascadeClassifier(facedata)\n# print(cascade.empty())\n# img = cv2.imread(imagepath)\n# print(img.shape)\n#\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# print(gray.shape)\n#\n# faces = cascade.detectMultiScale(gray)\n# for f in faces:\n# x, y, w, h = [v for v in f]\n# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n#\n# sub_face = gray[y:y + h, x:x + w]\n# img_resized = cv2.resize(sub_face, (48, 48))\n# x = preprocessing.image.img_to_array(img_resized)\n# x = np.expand_dims(x, axis=0)\n# print(x.shape)\n# # x= np.array(x, dtype=np.float)\n# # a = a.flatten()\n# x /= 255\n# custom = model.predict(x)\n# # print (\"Writing: \" + custom[0])\n# emotion_analysis(custom[0])\n# plt.imshow(img)\n# plt.show()\n#\ndef eye_aspect_ratio(eye):\n A = distance.euclidean(eye[1], eye[5])\n B = distance.euclidean(eye[2], eye[4])\n C = distance.euclidean(eye[0], eye[3])\n ear = (A + B) / (2.0 * C)\n return ear\ndef detect_face(frame):\n\n # Cascade classifier pre-trained model\n cascPath = 'models/face_landmarks.dat'\n faceCascade = cv2.CascadeClassifier(cascPath)\n\n # BGR -> Gray conversion\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Cascade MultiScale classifier\n detected_faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=6,\n minSize=(shape_x, shape_y),\n flags=cv2.CASCADE_SCALE_IMAGE)\n coord = []\n\n for x, y, w, h in detected_faces:\n if w > 100:\n sub_img = frame[y:y + h, x:x + w]\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 1)\n coord.append([x, y, w, h])\n\n return gray, detected_faces, coord\ndef extract_face_features(faces, offset_coefficients=(0.075, 0.05)):\n gray = faces[0]\n detected_face = faces[1]\n\n new_face = []\n\n for det in detected_face:\n # Region dans laquelle la face est détectée\n x, y, w, h = det\n # X et y correspondent à la conversion en gris par gray, et w, h correspondent à la hauteur/largeur\n\n # Offset coefficient, np.floor takes the lowest integer (delete border of the image)\n horizontal_offset = np.int(np.floor(offset_coefficients[0] * w))\n vertical_offset = np.int(np.floor(offset_coefficients[1] * h))\n\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # gray transforme l'image\n extracted_face = gray[y + vertical_offset:y + h, x + horizontal_offset:x - horizontal_offset + w]\n\n # Zoom sur la face extraite\n new_extracted_face = zoom(extracted_face,\n (shape_x / extracted_face.shape[0], shape_y / extracted_face.shape[1]))\n # cast type float\n new_extracted_face = new_extracted_face.astype(np.float32)\n # scale\n new_extracted_face /= float(new_extracted_face.max())\n # print(new_extracted_face)\n\n new_face.append(new_extracted_face)\n\n return new_face\n\n\ndef On_camera_detection():\n# vs = cv2.VideoCapture(0)\n# time.sleep(1.0)\n cap = cv2.VideoCapture(0)\n ret, frame = cap.read()\n print(ret)\n while cap.isOpened() and ret == True:\n ret, frame = cap.read()\n # Load an image to entity from file\n img = frame.copy()\n facedata = \"C:/Users/Admin/PycharmProjects/face-recognition-opencv/models/haarcascade_frontalface_alt.xml\"\n cascade = cv2.CascadeClassifier(facedata)\n print(cascade.empty())\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = cascade.detectMultiScale(gray)\n x= y= w= h = None\n # try:\n for f in faces:\n x, y, w, h = [v for v in f]\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n sub_face = gray[y:y + h, x:x + w]\n # img_resized = cv2.resize(sub_face, (48, 48))\n # x = preprocessing.image.img_to_array(img_resized)\n # x = np.expand_dims(x, axis=0)\n sub_face_norm = in_encoder.transform(sub_face)\n samples = np.expand_dims(sub_face_norm, axis=0)\n yhat_class = f_model.predict(samples)\n # get name\n print(yhat_class)\n class_index = yhat_class[0]\n print('class:',class_index)\n predict_names = out_encoder.inverse_transform(yhat_class)\n print(predict_names)\n # all_names = out_encoder.inverse_transform([0, 1, 2, 3, 4])\n # print('Predicted: %s (%.3f)' % (predict_names[0], class_probability))\n # print('Predicted: \\n%s \\n%s' % (all_names, yhat_prob[0] * 100))\n # print('Expected: %s' % random_face_name[0])\n # x= np.array(x, dtype=np.float)\n # a = a.flatten()\n # x /= 255\n # custom = e_model.predict(x)\n # # print(custom[1])\n # prob = custom[0].max()\n # clas = objects[custom[0].argmax()]\n # print(prob,clas)\n # label = emotion_analysis(custom[0])\n # cv2.putText(img, f'{str(clas)}', (int(50),int(50)), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0))\n # except:\n # pass\n cv2.imshow('feed',img)\n\n # the 'q' button is set as the\n # quitting button you may use any\n # desired button of your choice\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n\n\ndef video_detection(in_path,out_path):\n\n stream = cv2.VideoCapture(in_path)\n writer = None\n\n # loop over frames from the video file stream\n while True:\n #grab the next frame\n (grabbed, frame) = stream.read()\n # if the frame was not grabbed, then we have reached the\n # end of the stream\n if not grabbed:\n break\n rgb = cv2.resize(frame, (960,600))\n #boxes = face_recognition.face_locations(rgb,\n # model='cnn')\n #gray,face,boxes = detect_face(rgb)\n gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)\n rects = face_detect(gray, 1)\n name = rec_face(rgb)\n draw_and_detect(rgb,gray,rects,name)\n\n if writer is None and out_path is not None:\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(out_path, fourcc, 24,\n (rgb.shape[1], rgb.shape[0]), True)\n\n # if the writer is not None, write the frame with recognized\n # faces t odisk\n if writer is not None:\n writer.write(rgb)\n # close the video file pointers\n stream.release()\n\n # check to see if the video writer point needs to be released\n if writer is not None:\n writer.release()\ndef draw_and_detect(frame,gray,rects,name):\n for (i, rect) in enumerate(rects):\n\n shape = predictor_landmarks(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n # Identify face coordinates\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n face = gray[y:y + h, x:x + w]\n\n # Zoom on extracted face\n face = zoom(face, (shape_x / face.shape[0], shape_y / face.shape[1]))\n\n # Cast type float\n face = face.astype(np.float32)\n\n # Scale\n face /= float(face.max())\n face = np.reshape(face.flatten(), (1, 48, 48, 1))\n\n # Make Prediction\n prediction = e_model.predict(face)\n prediction_result = np.argmax(prediction)\n label = objects[prediction_result]\n # Rectangle around the face\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n cv2.putText(frame, \"Face {}\".format(name), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0),\n 2)\n\n for (j, k) in shape:\n cv2.circle(frame, (j, k), 1, (0, 0, 255), -1)\n\n # 1. Add prediction probabilities\n cv2.putText(frame, \"----------------\", (40, 100 + 180 * i), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 0)\n cv2.putText(frame, \"Emotional report : Face #\" + str(i + 1), (40, 120 + 180 * i), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, 155, 0)\n cv2.putText(frame, \"Angry : \" + str(round(prediction[0][0], 3)), (40, 140 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 0)\n cv2.putText(frame, \"Disgust : \" + str(round(prediction[0][1], 3)), (40, 160 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 0)\n cv2.putText(frame, \"Fear : \" + str(round(prediction[0][2], 3)), (40, 180 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 1)\n cv2.putText(frame, \"Happy : \" + str(round(prediction[0][3], 3)), (40, 200 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 1)\n cv2.putText(frame, \"Sad : \" + str(round(prediction[0][4], 3)), (40, 220 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 1)\n cv2.putText(frame, \"Surprise : \" + str(round(prediction[0][5], 3)), (40, 240 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 1)\n cv2.putText(frame, \"Neutral : \" + str(round(prediction[0][6], 3)), (40, 260 + 180 * i),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, 155, 1)\n\n # 2. Annotate main image with a label\n\n cv2.putText(frame, label, (x + w - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n\n # 3. Eye Detection and Blink Count\n leftEye = shape[lStart:lEnd]\n rightEye = shape[rStart:rEnd]\n\n # Compute Eye Aspect Ratio\n leftEAR = eye_aspect_ratio(leftEye)\n rightEAR = eye_aspect_ratio(rightEye)\n ear = (leftEAR + rightEAR) / 2.0\n\n # And plot its contours\n leftEyeHull = cv2.convexHull(leftEye)\n rightEyeHull = cv2.convexHull(rightEye)\n cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)\n cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)\n\n # 4. Detect Nose\n nose = shape[nStart:nEnd]\n noseHull = cv2.convexHull(nose)\n cv2.drawContours(frame, [noseHull], -1, (0, 255, 0), 1)\n\n # 5. Detect Mouth\n mouth = shape[mStart:mEnd]\n mouthHull = cv2.convexHull(mouth)\n cv2.drawContours(frame, [mouthHull], -1, (0, 255, 0), 1)\n\n # 6. Detect Jaw\n jaw = shape[jStart:jEnd]\n jawHull = cv2.convexHull(jaw)\n cv2.drawContours(frame, [jawHull], -1, (0, 255, 0), 1)\n\n # 7. Detect Eyebrows\n ebr = shape[ebrStart:ebrEnd]\n ebrHull = cv2.convexHull(ebr)\n cv2.drawContours(frame, [ebrHull], -1, (0, 255, 0), 1)\n ebl = shape[eblStart:eblEnd]\n eblHull = cv2.convexHull(ebl)\n cv2.drawContours(frame, [eblHull], -1, (0, 255, 0), 1)\nvideo_detection(args['input'],args['output'])\n","sub_path":"Deploying-ML-Models/src/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":14779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"406901943","text":"import os\nfrom setuptools import setup, find_packages\n\nbase_dir = os.path.dirname(os.path.abspath(__file__))\n\nwith open(os.path.join(base_dir, 'requirements.txt')) as source:\n requirements = source.read().splitlines()\n\n__about__ = {}\nwith open(os.path.join(base_dir, 'binstar_client', '__about__.py')) as source:\n exec(source.read(), __about__)\n\nsetup(\n name='anaconda-client',\n version=__about__['__version__'],\n author='Sean Ross-Ross',\n author_email='srossross@gmail.com',\n url='http://github.com/Anaconda-Platform/anaconda-client',\n description='Anaconda Cloud command line client library',\n packages=find_packages(),\n install_requires=requirements,\n entry_points={\n 'console_scripts': [\n 'anaconda = binstar_client.scripts.cli:main',\n 'binstar = binstar_client.scripts.cli:main',\n 'conda-server = binstar_client.scripts.cli:main'\n ]\n },\n license='BSD License',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490385099","text":" # Creating tree and preorder traversal\n\n\nclass Node(object):\n def __init__(self,data):\n self.lc = None\n self.rc = None\n self.data = data\n\nclass Binary_tree(object):\n def __init__(self):\n self.root = None\n\n def insert(self, data):\n new_node = Node(data)\n if self.root is None:\n self.root = new_node\n else:\n self.insert1(self.root, data)\n\n def insert1(self, node, data):\n if data > node.data:\n if node.rc is None:\n new_node = Node(data)\n node.rc = new_node\n else:\n self.insert1(node.rc, data)\n else:\n if node.lc is None:\n new_node = Node(data)\n node.lc = new_node\n else:\n self.insert1(node.lc, data)\n\n\n def preorder_traversal(self):\n if self.root is None:\n print('Tree is empty')\n else:\n self.preorder1(self.root)\n\n def preorder1(self, node):\n print(node.data)\n if node.lc is not None:\n self.preorder1(node.lc)\n if node.rc is not None:\n self.preorder1(node.rc)\n\n\n\n\nbt = Binary_tree()\nbt.insert(12)\nbt.insert(6)\nbt.insert(14)\nbt.insert(3)\nbt.preorder_traversal()","sub_path":"preorder.py","file_name":"preorder.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"305475201","text":"from collections import defaultdict\nfrom threading import Lock\n\nfrom nio.block.terminals import input\nfrom nio.block.base import Block\nfrom nio.signal.base import Signal\nfrom nio.properties import VersionProperty, TimeDeltaProperty, \\\n BoolProperty\nfrom nio.modules.scheduler import Job\nfrom nio.block.mixins.group_by.group_by import GroupBy\nfrom nio.block.mixins.persistence.persistence import Persistence\n\n\n@input('input_2')\n@input('input_1', default=True)\nclass MergeStreams(Persistence, GroupBy, Block):\n\n \"\"\" Take two input streams and combine signals together. \"\"\"\n\n expiration = TimeDeltaProperty(default={}, title=\"Stream Expiration\")\n notify_once = BoolProperty(default=True, title=\"Notify Once?\")\n version = VersionProperty('0.1.0')\n\n def _default_signals_dict(self):\n return {\"input_1\": {}, \"input_2\": {}}\n\n def _default_expiration_jobs_dict(self):\n return {\"input_1\": None, \"input_2\": None}\n\n def __init__(self):\n super().__init__()\n self._signals = defaultdict(self._default_signals_dict)\n self._signals_lock = defaultdict(Lock)\n self._expiration_jobs = defaultdict(self._default_expiration_jobs_dict)\n\n def persisted_values(self):\n \"\"\"Persist signals only when no expiration (ttl) is configured.\n\n Signals at each input will be persisted between block restarts except\n when an expiration is configured. TODO: Improve this feature so signals\n are always persisted and then properly removed after loaded and the\n expiration has passed.\n \"\"\"\n if self.expiration():\n return []\n else:\n return [\"_signals\"]\n\n def process_group_signals(self, signals, group, input_id):\n merged_signals = []\n with self._signals_lock[group]:\n for signal in signals:\n self._signals[group][input_id] = signal\n signal1 = self._signals[group][\"input_1\"]\n signal2 = self._signals[group][\"input_2\"]\n if signal1 and signal2:\n merged_signal = self._merge_signals(signal1, signal2)\n merged_signals.append(merged_signal)\n if self.notify_once():\n self._signals[group][\"input_1\"] = {}\n self._signals[group][\"input_2\"] = {}\n if self.expiration():\n self._schedule_signal_expiration_job(group, input_id)\n return merged_signals\n\n def _merge_signals(self, signal1, signal2):\n \"\"\" Merge signals 1 and 2 and clear from memory if only notify once \"\"\"\n sig_1_dict = signal1.to_dict()\n sig_2_dict = signal2.to_dict()\n\n self._fix_to_dict_hidden_attr_bug(sig_1_dict)\n self._fix_to_dict_hidden_attr_bug(sig_2_dict)\n merged_signal_dict = {}\n merged_signal_dict.update(sig_1_dict)\n merged_signal_dict.update(sig_2_dict)\n return Signal(merged_signal_dict)\n\n def _fix_to_dict_hidden_attr_bug(self, signal_dict):\n \"\"\" Remove special attributes from dictionary\n\n n.io has a bug when using Signal.to_dict(hidden=True). It should\n include private attributes (i.e. attributes starting withe '_') but not\n special attributes (i.e. attributes starting with '__').\n\n \"\"\"\n for key in list(signal_dict.keys()):\n if key.startswith('__'):\n del signal_dict[key]\n\n def _schedule_signal_expiration_job(self, group, input_id):\n \"\"\" Schedule expiration job, cancelling existing job first \"\"\"\n if self._expiration_jobs[group][input_id]:\n self._expiration_jobs[group][input_id].cancel()\n self._expiration_jobs[group][input_id] = Job(\n self._signal_expiration_job, self.expiration(), False,\n group, input_id)\n\n def _signal_expiration_job(self, group, input_id):\n self._signals[group][input_id] = {}\n self._expiration_jobs[group][input_id] = None\n","sub_path":"blocks/merge_streams/merge_streams_block.py","file_name":"merge_streams_block.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"457591605","text":"'''\r\n给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。\r\n'''\r\n'''\r\nexample1:\r\n输入: \"babad\"\r\n输出: \"bab\"\r\n注意: \"aba\"也是一个有效答案。\r\nexample2:\r\n输入: \"cbbd\"\r\n输出: \"bb\"\r\n'''\r\n\r\n\r\nclass Solution:\r\n def longestPalindrome(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: str\r\n \"\"\"\r\n if(s==\"\"): return \"\"\r\n longestPalindrome = \"\"\r\n length = 1\r\n for i in range(len(s)):\r\n tmp = s[:i + 1][::-1]\r\n for j in range(length + 1, i + 2):\r\n slice = tmp[:j]\r\n if (self.isPalindrome(slice) and len(slice) >= length):\r\n length = len(slice)\r\n longestPalindrome = slice\r\n if(length == 1):\r\n return s[0]\r\n else:\r\n return longestPalindrome\r\n\r\n def isPalindrome(self, s):\r\n return s[::-1] == s","sub_path":"a005Mine_LongestPalindrome.py","file_name":"a005Mine_LongestPalindrome.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"124121259","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'Django settings for labman2 project.'\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n#ALLOWED_HOSTS = ['127.0.0.1', 'localhost',]\n\nimport os\nfrom os.path import join, abspath, dirname, sep\n\nPROJECT_ROOT = abspath(join(dirname(__file__), \".\"))\n\ndef root(*x):\n \"Absolute path to a subdir of the project\"\n return abspath(join(PROJECT_ROOT, *x))\n\ndef get_env(var_name):\n \"Read an ENV variable, e.g. password\"\n try:\n return os.environ[var_name]\n except KeyError:\n print(\"Environment variable '%s' is not set, cannot continue.\" %\n var_name)\n raise\n\nADMINS = [\n # ('Your Name', 'your_email@example.com'),\n]\nADMINS += (get_env(\"LABMAN2_ADMIN_NAME\"), get_env(\"LABMAN2_ADMIN_EMAIL\"))\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n #Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'labman2', # Or path to database file if using sqlite3.\n 'USER': 'www', # Not used with sqlite3.\n# 'PASSWORD': 'Y5t2KUII', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n #'OPTIONS': {'autocommit': True}, # Needed for tests with psycopg2 v.2.4.2\n }\n}\nDATABASES['default']['PASSWORD'] = get_env(\"LABMAN2_DB_PASSWD\")\n\n#New in Django 1.6.\n#Default:False,\n#ATOMIC_REQUESTS = True # wrap each HTTP request in a transaction\n # on this database\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\n#TIME_ZONE = 'America/Chicago'\n#TIME_ZONE = None\nTIME_ZONE = 'Europe/Helsinki'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nLANGUAGES = (\n ('en', (u'English')),\n ('fi', (u'Suomi')),\n ('ru', (u'Русский')),\n# ('sv', (u'Svenska')),\n)\n\n#SITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n#django 1.4\n# If you set this to False, Django will not use timezone-aware datetimes.\n#USE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = root('uploads')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = '/uploads/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\n#for Svetlana\n#STATIC_ROOT = 'C:/Users/Svetlana/labman2/labman2/static/'\n#for Vova\nSTATIC_ROOT = root('static')\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/static/'\n\n#STATIC_DOC_ROOT = '/home/chu/progs/labman2/labman2/static'\nSTATIC_DOC_ROOT = STATIC_ROOT\n\nLOGIN_URL = '/accounts/login/'\n\n#The URL where requests are redirected after login\nLOGIN_REDIRECT_URL = '/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\n#SECRET_KEY = 'qgpjbmj(vup)e5s4oy*-f(84o-04ck%pxvbpi3hj^w%%41%d@-'\nSECRET_KEY = get_env(\"LABMAN2_SECRET_KEY\")\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n #'django.middleware.transaction.TransactionMiddleware', is deprecated\n #and replaced by ATOMIC_REQUESTS\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'labman2.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'labman2.wsgi.application'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or\n # \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nSUBDIRS = [name[0].split(sep)[-1]\n for name in os.walk(abspath(join(\"labman2\", \"data\", \"subdata\")))\n if name[0].split(sep)[-1] not in ('sql', 'subdata')]\n\n\n# django-registration from\n# http://www.bitbucket.org/ubernostrum/django-registration/\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n# 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n# 'registration',\n 'labman2',\n 'labman2.data',\n 'labman2.data.subdata',\n 'allauth',\n ]\n\nINSTALLED_APPS.extend(['labman2.data.subdata.%s' % name for name in SUBDIRS])\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console': {\n # logging handler that outputs log messages to terminal\n 'class': 'logging.StreamHandler',\n 'level': 'DEBUG', # message level to be written to console\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['mail_admins', 'console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# Tests for registration need the following.\nACCOUNT_ACTIVATION_DAYS = 3\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"228998271","text":"\"\"\"J. Стек - MaxEffective\nРеализуйте класс StackMaxEffective, поддерживающий операцию\nопределения максимума среди элементов в стеке.\nСложность операции должна быть O(1).\nДля пустого стека операция должна возвращать None.\nПри этом push и pop также должны выполняться за константное время.\n\"\"\"\n\nwith open(\"input.txt\") as f:\n n = int(f.readline())\n commands = []\n for i in range(n):\n commands.append(f.readline().split())\n\n\nclass StackMaxEffective:\n def __init__(self):\n self.items = []\n self.max_items = []\n\n def isEmpty(self):\n return self.items == []\n\n def push(self, item):\n if self.isEmpty():\n self.items.append(item)\n self.max_items.append(item)\n else:\n self.items.append(item)\n if item > self.max_items[-1]:\n self.max_items.append(item)\n else:\n self.max_items.append(self.max_items[-1])\n\n def pop(self):\n if not self.isEmpty():\n return self.items.pop(), self.max_items.pop()\n print(\"error\")\n\n def get_max(self):\n if not self.isEmpty():\n print(self.max_items[-1])\n else:\n print(None)\n\n\nstack = StackMaxEffective()\n\nfor command in commands:\n if command[0] == \"get_max\":\n stack.get_max()\n if command[0] == \"push\":\n stack.push(int(command[1]))\n if command[0] == \"pop\":\n stack.pop()\n","sub_path":"j.py","file_name":"j.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"634991696","text":"\"\"\"\nowtf is an OWASP+PTES-focused try to unite great tools and facilitate pen testing\nCopyright (c) 2011, Abraham Aranguren Twitter: @7a_ http://7-a.org\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the copyright owner nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY 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\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY 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\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nimport time\nimport logging\n\nDESCRIPTION = \"Runs a chain of commands on an agent server via SBD -i.e. for IDS testing-\"\ndef run(Core, PluginInfo):\n\t#Core.Config.Show()\n\tContent = DESCRIPTION + \" Results:
\"\n\tIteration = 1 # Iteration counter initialisation\n\tfor Args in Core.PluginParams.GetArgs( { \n'Description' : DESCRIPTION,\n'Mandatory' : { \n\t\t'RHOST' : Core.Config.Get('RHOST_DESCRIP'),\n\t\t'SBD_PORT' : Core.Config.Get('SBD_PORT_DESCRIP'),\n\t\t'SBD_PASSWORD' : Core.Config.Get('SBD_PASSWORD_DESCRIP'),\n\t\t'COMMAND_PREFIX' : 'The command string to be pre-pended to the tests (i.e. /usr/lib/firefox... http...)',\n\t\t}, \n'Optional' : {\n\t\t'TEST' : 'The test to be included between prefix and suffix',\n\t\t'COMMAND_SUFIX' : 'The URL to be appended to the tests (i.e. ...whatever)',\n\t\t'ISHELL_REUSE_CONNECTION' : Core.Config.Get('ISHELL_REUSE_CONNECTION_DESCRIP'),\n\t\t'ISHELL_EXIT_METHOD' : Core.Config.Get('ISHELL_EXIT_METHOD_DESCRIP'),\n\t\t'ISHELL_DELAY_BETWEEN_COMMANDS' : Core.Config.Get('ISHELL_DELAY_BETWEEN_COMMANDS_DESCRIP'),\n\t\t'ISHELL_COMMANDS_BEFORE_EXIT' : Core.Config.Get('ISHELL_COMMANDS_BEFORE_EXIT_DESCRIP'),\n\t\t'ISHELL_COMMANDS_BEFORE_EXIT_DELIM' : Core.Config.Get('ISHELL_COMMANDS_BEFORE_EXIT_DELIM_DESCRIP'),\n\t\t'REPEAT_DELIM' : Core.Config.Get('REPEAT_DELIM_DESCRIP')\n\t\t} }, PluginInfo):\n\t\tCore.PluginParams.SetConfig(Args) # Sets the aux plugin arguments as config\n\t\tREUSE_CONNECTION = (Args['ISHELL_REUSE_CONNECTION'] == 'yes')\n\t\t#print \"REUSE_CONNECTION=\" + str(REUSE_CONNECTION)\n\t\tDELAY_BETWEEN_COMMANDS = Args['ISHELL_DELAY_BETWEEN_COMMANDS']\n\t\t#print \"Args=\"+str(Args)\n\t\t#print \"'ISHELL_COMMANDS_BEFORE_EXIT_DELIM'=\" + Args['ISHELL_COMMANDS_BEFORE_EXIT_DELIM']\n\t\t#break\n\t\tif Iteration == 1 or not REUSE_CONNECTION:\n\t\t\tCore.InteractiveShell.Open({\n\t\t\t\t'ConnectVia' : Core.Config.GetResources('RCE_SBD_Connection')\n\t\t\t\t, 'InitialCommands' : None #[ Args['BROWSER_PATH'] + ' about:blank']\n\t\t\t\t, 'ExitMethod' : Args['ISHELL_EXIT_METHOD']\n\t\t\t\t, 'CommandsBeforeExit' : Args['ISHELL_COMMANDS_BEFORE_EXIT']\n\t\t\t\t, 'CommandsBeforeExitDelim' : Args['ISHELL_COMMANDS_BEFORE_EXIT_DELIM']\n\t\t\t\t, 'RHOST' : Args['RHOST']\n\t\t\t\t, 'RPORT' : Args['SBD_PORT']\n\t\t\t\t\t\t\t }, PluginInfo)\n\t\telse:\n\t\t\tCore.log(\"Reusing initial connection..\")\n\t\tCore.InteractiveShell.Run(Args['COMMAND_PREFIX']+Args['TEST']+Args['COMMAND_SUFIX'])\n\t\tCore.log(\"Sleeping \" + DELAY_BETWEEN_COMMANDS + \" second(s) (increases reliability)..\")\n\t\ttime.sleep(int(DELAY_BETWEEN_COMMANDS))\n\t\t#Core.RemoteShell.Run(\"sleep \" + str(WAIT_SECONDS))\n\t\tif not REUSE_CONNECTION:\n\t\t\tCore.InteractiveShell.Close(PluginInfo)\n\t\t#Content += Core.PluginHelper.DrawCommandDump('Test Command', 'Output', Core.Config.GetResources('LaunchExploit_'+Args['CATEGORY']+\"_\"+Args['SUBCATEGORY']), PluginInfo, \"\") # No previous output\n\t\tIteration += 1 # Increase Iteration counter\n\tif not Core.InteractiveShell.IsClosed(): # Ensure clean exit if reusing connection\n\t\tCore.InteractiveShell.Close(PluginInfo)\n\treturn Content","sub_path":"plugins/aux/rce/SBD_CommandChainer@OWTF-ARCE-003.py","file_name":"SBD_CommandChainer@OWTF-ARCE-003.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"338178074","text":"import sys\nimport base64\nfrom jsonrpc.proxy import ServiceProxy\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: {} \".format(sys.argv[0]))\n\n file_name = sys.argv[1]\n rpc_server = ServiceProxy('http://localhost:8080/api/')\n with open(file_name, 'rb') as input_content:\n content = base64.b64encode(input_content.read())\n res = rpc_server.file_upload(file_name, content.decode('utf-8'))\n print(res)\n","sub_path":"project/source/base64upload.py","file_name":"base64upload.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"62036847","text":"\"\"\"\nThe main pages for the site\n\"\"\"\nfrom flask import render_template, redirect, url_for\nfrom rvr.app import APP\nfrom rvr.forms.change import ChangeForm\nfrom rvr.core.api import API, APIError\nfrom rvr.app import AUTH\nfrom rvr.core.dtos import LoginRequest, ChangeScreennameRequest, \\\n GameItemUserRange, GameItemBoard, GameItemActionResult, \\\n GameItemRangeAction, GameItemTimeout\nimport logging\nfrom flask.helpers import flash\nfrom flask.globals import request, session, g\nfrom rvr.forms.action import action_form\nfrom rvr.core import dtos\nfrom rvr.poker.handrange import NOTHING, SET_ANYTHING_OPTIONS, \\\n HandRange, unweighted_options_to_description\nfrom flask_googleauth import logout\n\n# pylint:disable=R0911,R0912,R0914\n\ndef is_authenticated():\n \"\"\"\n Is the user authenticated with OpenID?\n \"\"\"\n return g.user and 'identity' in g.user\n\ndef is_logged_in():\n \"\"\"\n Is the user logged in (i.e. they've been to the database)\n \"\"\"\n return 'userid' in session and 'screenname' in session\n\ndef ensure_user():\n \"\"\"\n Commit user to database and determine userid\n \"\"\"\n # TODO: REVISIT: automagically hook this into AUTH.required \n if not is_authenticated():\n # user is not authenticated yet\n return\n if is_logged_in():\n # user is authenticated and authorised (logged in)\n return\n if 'screenname' in session:\n # user had changed screenname but not yet logged in\n screenname = session['screenname']\n else:\n # regular login\n screenname = g.user['name']\n api = API()\n req = LoginRequest(identity=g.user['identity'], # @UndefinedVariable\n email=g.user['email'], # @UndefinedVariable\n screenname=screenname)\n result = api.login(req)\n if result == API.ERR_DUPLICATE_SCREENNAME:\n session['screenname'] = g.user['name']\n # User is authenticated with OpenID, but not yet authorised (logged\n # in). We redirect them to a page that allows them to choose a\n # different screenname.\n if request.endpoint != 'change_screenname':\n flash(\"The screenname '%s' is already taken.\" % (screenname,))\n return redirect(url_for('change_screenname'))\n elif isinstance(result, APIError):\n flash(\"Error registering user details.\")\n logging.debug(\"login error: %s\", result)\n return redirect(url_for('error_page'))\n else:\n # If their Google name is \"Player \", they will not be able to have\n # their Google name as their screenname. Unless their login errors.\n session['userid'] = result.userid\n session['screenname'] = result.screenname\n req2 = ChangeScreennameRequest(result.userid,\n \"Player %d\" % (result.userid,))\n if not result.existed and result.screenname != req2.screenname:\n result2 = api.change_screenname(req2)\n if isinstance(result2, APIError):\n flash(\"Couldn't give you screenname '%s', \"\n \"you are stuck with '%s' until you change it.\" %\n (req2.screenname, result.screenname))\n else:\n session['screenname'] = req2.screenname\n flash(\"You have logged in as '%s'\" % (session['screenname'],))\n\ndef error(message):\n \"\"\"\n Flash error message and redirect to error page.\n \"\"\"\n flash(message)\n return redirect(url_for('error_page'))\n\n@APP.route('/change', methods=['GET','POST'])\n@AUTH.required\ndef change_screenname():\n \"\"\"\n Without the user being logged in, give the user the option to change their\n screenname from what Google OpenID gave us.\n \"\"\"\n alt = ensure_user()\n if alt:\n return alt\n form = ChangeForm()\n if form.validate_on_submit():\n new_screenname = form.change.data\n if 'userid' in session:\n # Having a userid means they're in the database.\n req = ChangeScreennameRequest(session['userid'],\n new_screenname)\n resp = API().change_screenname(req)\n if resp == API.ERR_DUPLICATE_SCREENNAME:\n flash(\"That screenname is already taken.\")\n elif isinstance(resp, APIError):\n logging.debug(\"change_screenname error: %s\", resp)\n flash(\"An error occurred.\")\n else:\n session['screenname'] = new_screenname\n flash(\"Your screenname has been changed to '%s'.\" %\n (new_screenname, ))\n return redirect(url_for('home_page'))\n else:\n # User is not logged in. Changing screenname in session is enough.\n # Now when they go to the home page, ensure_user() will create their\n # account.\n session['screenname'] = new_screenname\n return redirect(url_for('home_page'))\n current = session['screenname'] if 'screenname' in session \\\n else g.user['name']\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/change.html', title='Change Your Screenname',\n current=current, form=form, navbar_items=navbar_items,\n is_logged_in=is_logged_in(), is_account=True)\n\n@APP.route('/unsubscribe', methods=['GET'])\ndef unsubscribe():\n \"\"\"\n Record that the user does not want to receive any more emails, at least\n until they log in again and in so doing clear that flag.\n \n Note that authentication is not required.\n \"\"\"\n api = API()\n identity = request.args.get('identity', None)\n if identity is None:\n msg = \"Invalid request, sorry.\"\n else:\n response = api.unsubscribe(identity)\n if response is api.ERR_NO_SUCH_USER:\n msg = \"No record of you on Range vs. Range, sorry.\"\n elif isinstance(response, APIError):\n msg = \"An unknown error occurred unsubscribing you, sorry.\"\n else:\n msg = \"You have been unsubscribed. If you log in again, you will start receiving emails again.\" # pylint:disable=C0301\n flash(msg)\n return render_template('web/flash.html', title='Unsubscribe')\n\n@logout.connect_via(APP)\ndef on_logout(_source, **_kwargs):\n \"\"\"\n I prefer to be explicit about what we remove on logout. \n \"\"\"\n session.pop('userid', None)\n session.pop('screenname', None)\n\n@APP.route('/log-in', methods=['GET'])\n@AUTH.required\ndef log_in():\n \"\"\"\n Does what /login does, but in a way that I can get a URL for with url_for!\n \"\"\"\n # TODO: REVISIT: get a relative URL for /login, instead of this.\n return redirect(url_for('home_page'))\n\n@APP.route('/error', methods=['GET'])\ndef error_page():\n \"\"\"\n Unauthenticated page for showing errors to user.\n \"\"\"\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/flash.html', title='Sorry',\n navbar_items=navbar_items, is_logged_in=is_logged_in())\n\n@APP.route('/about', methods=['GET'])\ndef about_page():\n \"\"\"\n Unauthenticated information page.\n \"\"\"\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('active', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/about.html', title=\"About\",\n navbar_items=navbar_items,\n is_logged_in=is_logged_in())\n\n@APP.route('/faq', methods=['GET'])\ndef faq_page():\n \"\"\"\n Frequently asked questions (unauthenticated).\n \"\"\"\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('active', url_for('faq_page'), 'FAQ')]\n return render_template('web/faq.html', title=\"FAQ\",\n navbar_items=navbar_items,\n is_logged_in=is_logged_in())\n\n@APP.route('/', methods=['GET'])\ndef home_page():\n \"\"\"\n Generates the unauthenticated landing page. AKA the main or home page.\n \"\"\"\n if not is_authenticated():\n return render_template('web/landing.html')\n alt = ensure_user()\n if alt:\n return alt\n api = API()\n userid = session['userid']\n screenname = session['screenname']\n open_games = api.get_open_games()\n if isinstance(open_games, APIError):\n flash(\"An unknown error occurred retrieving your open games.\")\n return redirect(url_for(\"error_page\"))\n my_games = api.get_user_running_games(userid)\n if isinstance(my_games, APIError):\n flash(\"An unknown error occurred retrieving your running games.\")\n return redirect(url_for(\"error_page\"))\n selected_heading = request.cookies.get(\"selected-heading\", \"heading-open\")\n my_games.running_details.sort(\n key=lambda rg: rg.current_user_details.userid != userid)\n my_open = [og for og in open_games\n if any([u.userid == userid for u in og.users])]\n others_open = [og for og in open_games\n if not any([u.userid == userid for u in og.users])]\n form = ChangeForm()\n navbar_items = [('active', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/home.html', title='Home',\n screenname=screenname, userid=userid, change_form=form,\n r_games=my_games,\n my_open=my_open,\n others_open=others_open,\n my_finished_games=my_games.finished_details,\n navbar_items=navbar_items,\n selected_heading=selected_heading,\n is_logged_in=is_logged_in())\n\n@APP.route('/join', methods=['GET'])\n@AUTH.required\ndef join_game():\n \"\"\"\n Join game, flash status, redirect back to /home\n \"\"\"\n alt = ensure_user()\n if alt:\n return alt\n api = API()\n gameid = request.args.get('gameid', None)\n if gameid is None:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n try:\n gameid = int(gameid)\n except ValueError:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n userid = session['userid']\n response = api.join_game(userid, gameid)\n if response is api.ERR_JOIN_GAME_ALREADY_IN:\n msg = \"You are already registered in game %s.\" % (gameid,)\n elif response is api.ERR_JOIN_GAME_GAME_FULL:\n msg = \"Game %d is full.\" % (gameid,)\n elif response is api.ERR_NO_SUCH_OPEN_GAME:\n msg = \"Invalid game ID.\"\n elif response is api.ERR_NO_SUCH_USER:\n msg = \"Oddly, your account does not seem to exist. \" + \\\n \"Try logging out and logging back in.\"\n logging.debug(\"userid %d can't register for game %d, \" +\n \"because user doesn't exist.\",\n userid, gameid)\n elif isinstance(response, APIError):\n msg = \"An unknown error occurred joining game %d, sorry.\" % (gameid,)\n logging.debug(\"unrecognised error from api.join_game: %s\", response)\n else:\n msg = \"You have joined game %s.\" % (gameid,)\n flash(msg)\n return redirect(url_for('home_page'))\n flash(msg)\n return redirect(url_for('error_page'))\n\n@APP.route('/leave', methods=['GET'])\n@AUTH.required\ndef leave_game():\n \"\"\"\n Leave game, flash status, redirect back to /home\n \"\"\"\n alt = ensure_user()\n if alt:\n return alt\n api = API()\n gameid = request.args.get('gameid', None)\n if gameid is None:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n try:\n gameid = int(gameid)\n except ValueError:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n userid = session['userid']\n response = api.leave_game(userid, gameid)\n if response is api.ERR_USER_NOT_IN_GAME:\n msg = \"You are not registered in game %s.\" % (gameid,)\n elif response is api.ERR_NO_SUCH_OPEN_GAME:\n msg = \"Invalid game ID.\"\n elif isinstance(response, APIError):\n msg = \"An unknown error occurred leaving game %d, sorry.\" % (gameid,)\n else:\n msg = \"You have left game %s.\" % (gameid,)\n flash(msg)\n return redirect(url_for('home_page'))\n flash(msg)\n return redirect(url_for('error_page'))\n\ndef _handle_action(gameid, userid, api, form, can_check, can_raise):\n \"\"\"\n Handle response from an action form\n \"\"\"\n # pylint:disable=R0912,R0913\n fold = form.fold.data\n passive = form.passive.data\n aggressive = form.aggressive.data\n if aggressive != NOTHING:\n try:\n total = int(form.total.data)\n except ValueError:\n flash(\"Incomprehensible raise total.\")\n return False\n else:\n total = 0\n range_action = dtos.ActionDetails(fold_raw=fold, passive_raw=passive,\n aggressive_raw=aggressive,\n raise_total=total)\n try:\n range_name = \"Fold\"\n range_action.fold_range.validate()\n range_name = \"Check\" if can_check else \"Call\"\n range_action.passive_range.validate()\n range_name = \"Raise\" if can_raise else \"Bet\"\n range_action.aggressive_range.validate()\n except ValueError as err:\n flash(\"%s range is invalid. Reason: %s.\" % (range_name, err.message))\n return False\n logging.debug(\"gameid %r, performing action, userid %r, range_action %r\",\n gameid, userid, range_action)\n result = api.perform_action(gameid, userid, range_action)\n # why do validation twice...\n if isinstance(result, APIError):\n if result is api.ERR_INVALID_RAISE_TOTAL:\n msg = \"Invalid raise total.\"\n elif result is api.ERR_INVALID_RANGES:\n msg = \"Invalid ranges for that action.\"\n else:\n msg = \"An unknown error occurred performing action, sorry.\"\n logging.info('Unknown error from api.perform_action: %s', result)\n flash(msg)\n return False\n else:\n if result.is_fold:\n msg = \"You folded.\"\n elif result.is_passive:\n if result.call_cost == 0:\n msg = \"You checked.\"\n else:\n msg = \"You called for %d.\" % (result.call_cost,)\n elif result.is_aggressive:\n if result.is_raise:\n msg = \"You raised to %d.\" % (result.raise_total,)\n else:\n msg = \"You bet %d.\" % (result.raise_total,)\n elif result.is_terminate:\n msg = \"The game is finished.\"\n else:\n msg = \"I can't figure out what happened, eh.\"\n flash(msg)\n return True\n\ndef _board_to_vars(item, _index):\n \"\"\"\n Replace little images into it\n \"\"\"\n cards = [item.cards[i:i+2] for i in range(0, len(item.cards), 2)]\n return item.street, cards\n\ndef _range_action_to_vars(item, index):\n \"\"\"\n Convert to percentages (relative), and such.\n \n Returns (total_range, fold_range, passive_range, aggressive_range, username,\n fold_pct, passive_pct, aggressive_pct, raise_total)\n \"\"\"\n fold_options = item.range_action.fold_range \\\n .generate_options_unweighted()\n passive_options = item.range_action.passive_range \\\n .generate_options_unweighted()\n aggressive_options = item.range_action.aggressive_range \\\n .generate_options_unweighted()\n all_options = fold_options + passive_options + aggressive_options\n combined_range = unweighted_options_to_description(all_options)\n fold_total = len(fold_options)\n passive_total = len(passive_options)\n aggressive_total = len(aggressive_options)\n total = len(all_options)\n # NOTE: some of this is necessarily common with ACTION_SUMMARY\n return {\"screenname\": item.user.screenname,\n \"fold_pct\": 100.0 * fold_total / total,\n \"passive_pct\": 100.0 * passive_total / total,\n \"aggressive_pct\": 100.0 * aggressive_total / total,\n \"raise_total\": item.range_action.raise_total,\n \"is_check\": item.is_check,\n \"is_raise\": item.is_raise,\n \"original\": combined_range,\n \"fold\": item.range_action.fold_range.description,\n \"passive\": item.range_action.passive_range.description,\n \"aggressive\": item.range_action.aggressive_range.description,\n \"index\": index}\n\ndef _action_summary_to_vars(range_action, action_result, action_result_index,\n user_range, index):\n \"\"\"\n Summarise an action result and user range in the context of the most recent\n range action.\n \"\"\"\n new_total = len(HandRange(user_range.range_raw). \\\n generate_options_unweighted())\n fol = pas = agg = NOTHING\n if action_result.action_result.is_fold:\n original = fol = range_action.range_action.fold_range.description\n elif action_result.action_result.is_passive:\n original = pas = range_action.range_action.passive_range.description\n else:\n original = agg = range_action.range_action.aggressive_range.description\n # NOTE: some of this is necessarily common with RANGE_ACTION\n return {\"screenname\": user_range.user.screenname,\n \"action_result\": action_result.action_result,\n \"action_result_index\": action_result_index,\n \"percent\": 100.0 * new_total / len(SET_ANYTHING_OPTIONS),\n \"combos\": new_total,\n \"is_check\": range_action.is_check,\n \"is_raise\": range_action.is_raise,\n \"original\": original,\n \"fold\": fol,\n \"passive\": pas,\n \"aggressive\": agg,\n \"index\": index}\n \ndef _action_result_to_vars(action_result, index):\n \"\"\"\n Summarises action result for the case where the hand is in progress, and\n the user is not allowed to view the other players' ranges.\n \"\"\"\n return {\"screenname\": action_result.user.screenname,\n \"action_result\": action_result.action_result,\n \"index\": index}\n \ndef _timeout_to_vars(timeout, index):\n \"\"\"\n Summarises a timeout.\n \"\"\"\n return {\"screenname\": timeout.user.screenname,\n \"index\": index}\n\ndef _make_history_list(game_history):\n \"\"\"\n Hand history items provide a basic to-text function. This function adds a\n little extra HTML where necessary, to make them prettier.\n \"\"\"\n results = []\n # There is always a range action and an action before a user range\n most_recent_range_action = None\n most_recent_action_result = None\n pending_action_result = None\n for index, item in enumerate(game_history):\n if isinstance(item, GameItemUserRange):\n if pending_action_result is not None:\n results.remove(pending_action_result)\n action_result_index = pending_action_result[1]['index']\n pending_action_result = None\n results.append((\"ACTION_SUMMARY\",\n _action_summary_to_vars(most_recent_range_action,\n most_recent_action_result,\n action_result_index,\n item, index)))\n elif isinstance(item, GameItemRangeAction):\n most_recent_range_action = item\n results.append((\"RANGE_ACTION\",\n _range_action_to_vars(item, index)))\n elif isinstance(item, GameItemActionResult):\n most_recent_action_result = item\n pending_action_result = (\"ACTION_RESULT\",\n _action_result_to_vars(item, index))\n results.append(pending_action_result)\n # This will be removed if there is a following user range\n elif isinstance(item, GameItemBoard):\n results.append((\"BOARD\", _board_to_vars(item, index)))\n elif isinstance(item, GameItemTimeout):\n results.append((\"TIMEOUT\", _timeout_to_vars(item, index)))\n else:\n logging.debug(\"unrecognised type of hand history item: %s\", item)\n results.append((\"UNKNOWN\", (str(item),)))\n return results\n\ndef _running_game(game, gameid, userid, api):\n \"\"\"\n Response from game page when the requested game is still running.\n \"\"\"\n form = action_form(is_check=game.current_options.can_check(),\n is_raise=game.current_options.is_raise,\n can_raise=game.current_options.can_raise(),\n min_raise=game.current_options.min_raise,\n max_raise=game.current_options.max_raise)\n if form.validate_on_submit():\n if _handle_action(gameid, userid, api, form,\n game.current_options.can_check(),\n game.current_options.can_raise()):\n return redirect(url_for('game_page', gameid=gameid)) \n \n # First load, OR something's wrong with their data.\n range_editor_url = url_for('range_editor',\n rng_original=game.game_details.current_player.range_raw,\n board=game.game_details.board_raw,\n raised=\"true\" if game.current_options.is_raise else \"false\",\n can_check=\"true\" if game.current_options.can_check() else \"false\",\n can_raise=\"true\" if game.current_options.can_raise() else \"false\",\n min_raise=game.current_options.min_raise,\n max_raise=game.current_options.max_raise)\n title = 'Game %d' % (gameid,)\n history = _make_history_list(game.history)\n board_raw = game.game_details.board_raw\n board = [board_raw[i:i+2] for i in range(0, len(board_raw), 2)]\n is_me = (userid == game.game_details.current_player.user.userid)\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/game.html', title=title, form=form,\n board=board, game_details=game.game_details, history=history,\n current_options=game.current_options,\n is_me=is_me, is_running=True,\n range_editor_url=range_editor_url,\n navbar_items=navbar_items, is_logged_in=is_logged_in())\n\ndef _finished_game(game, gameid):\n \"\"\"\n Response from game page when the requested game is finished.\n \"\"\"\n title = 'Game %d' % (gameid,)\n history = _make_history_list(game.history)\n analyses = game.analysis.keys() \n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n return render_template('web/game.html', title=title,\n game_details=game.game_details, history=history, analyses=analyses,\n is_running=False,\n navbar_items=navbar_items, is_logged_in=is_logged_in())\n\ndef authenticated_game_page(gameid):\n \"\"\"\n Game page when user is not authenticated (i.e. the public view)\n \"\"\"\n alt = ensure_user()\n if alt:\n return alt\n userid = session['userid']\n\n api = API()\n response = api.get_private_game(gameid, userid)\n if isinstance(response, APIError):\n if response is api.ERR_NO_SUCH_RUNNING_GAME:\n msg = \"Invalid game ID.\"\n else:\n msg = \"An unknown error occurred retrieving game %d, sorry.\" % \\\n (gameid,)\n flash(msg)\n return redirect(url_for('error_page'))\n \n if response.is_finished():\n return _finished_game(response, gameid)\n else:\n return _running_game(response, gameid, userid, api)\n\ndef unauthenticated_game_page(gameid):\n \"\"\"\n Game page when user is authenticated (i.e. the private view)\n \"\"\"\n api = API()\n response = api.get_public_game(gameid)\n if isinstance(response, APIError):\n if response is api.ERR_NO_SUCH_RUNNING_GAME:\n msg = \"Invalid game ID.\"\n else:\n msg = \"An unknown error occurred retrieving game %d, sorry.\" % \\\n (gameid,)\n flash(msg)\n return redirect(url_for('error_page'))\n \n if response.is_finished():\n return _finished_game(response, gameid)\n else:\n return _running_game(response, gameid, None, api)\n\n@APP.route('/game', methods=['GET', 'POST'])\ndef game_page():\n \"\"\"\n View of the specified game, authentication-aware\n \"\"\"\n # TODO: 3: every position should have a name\n # TODO: 2: chat\n gameid = request.args.get('gameid', None)\n if gameid is None:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n try:\n gameid = int(gameid)\n except ValueError:\n flash(\"Invalid game ID.\")\n return redirect(url_for('error_page'))\n\n if is_authenticated():\n return authenticated_game_page(gameid)\n else:\n return unauthenticated_game_page(gameid) \n\n@APP.route('/analysis', methods=['GET'])\ndef analysis_page():\n \"\"\"\n Analysis of a particular hand history item.\n \"\"\"\n gameid = request.args.get('gameid', None)\n if gameid is None:\n return error(\"Invalid game ID.\")\n try:\n gameid = int(gameid)\n except ValueError:\n return error(\"Invalid game ID (not a number).\")\n\n api = API()\n response = api.get_public_game(gameid)\n if isinstance(response, APIError):\n if response is api.ERR_NO_SUCH_RUNNING_GAME:\n msg = \"Invalid game ID.\"\n else:\n msg = \"An unknown error occurred retrieving game %d, sorry.\" % \\\n (gameid,)\n return error(msg)\n game = response\n \n order = request.args.get('order', None)\n if order is None:\n return error(\"Invalid order.\")\n try:\n order = int(order)\n except ValueError:\n return error(\"Invalid order (not a number).\")\n\n try:\n item = game.history[order]\n except IndexError:\n return error(\"Invalid order (not in game).\")\n\n if not isinstance(item, dtos.GameItemActionResult):\n return error(\"Invalid order (not a bet or raise).\") \n\n if not item.action_result.is_aggressive:\n return error(\"Analysis only for bets right now, sorry.\")\n\n try:\n aife = game.analysis[order]\n except KeyError:\n return error(\"Analysis for this action is not ready yet.\")\n\n street = game.game_details.situation.current_round\n street_text = aife.STREET_DESCRIPTIONS[street]\n if item.action_result.is_raise:\n action_text = \"raises to %d\" % (item.action_result.raise_total,)\n else:\n action_text = \"bets %d\" % (item.action_result.raise_total,)\n\n navbar_items = [('', url_for('home_page'), 'Home'),\n ('', url_for('about_page'), 'About'),\n ('', url_for('faq_page'), 'FAQ')]\n items_aggressive = [i for i in reversed(aife.items) if i.is_aggressive]\n items_passive = [i for i in aife.items if i.is_passive]\n items_fold = [i for i in aife.items if i.is_fold]\n # Could also have a status column or popover or similar:\n # \"good bluff\" = +EV\n # \"bad bluff\" = -EV on river\n # \"possible semibluff\" = -EV on river\n return render_template('web/analysis.html', gameid=gameid,\n street_text=street_text, screenname=item.user.screenname,\n action_text=action_text,\n items_aggressive=items_aggressive,\n items_passive=items_passive,\n items_fold=items_fold,\n is_raise=aife.is_raise, is_check=aife.is_check,\n navbar_items=navbar_items, is_logged_in=is_logged_in())\n","sub_path":"rvr/views/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540685039","text":"import os\n# import work2\nimport pymongo\nimport re\nimport protocol\nfrom pprint import pprint\n# remove empty lines in the file\ndef remove_empty_lines(filename):\n if not os.path.isfile(filename):\n print(\"{} does not exist \".format(filename))\n return\n with open(filename) as filehandle:\n lines = filehandle.readlines()\n\n with open(filename, 'w') as filehandle:\n lines = filter(lambda x: x.strip(), lines)\n filehandle.writelines(lines)\n\n\nremove_empty_lines(\"m3files_14.txt\")\na = 0\nmylines, channel, listo, mylines2 = [], [], [], []\nwith open(\"problematic_m3files_txt\", 'rt') as myfile:\n for line in myfile:\n mylines2.append(line)\n\n# extract m3u8 links only. (flexible)\nfor i in range(len(mylines2)):\n if mylines2[i].startswith(protocol.extinf):\n if mylines2[i + 1].startswith(\"http\") and \".m3u8\" in mylines2[i + 1]:\n mylines.append(mylines2[i + 1])\n\nif mylines != []:\n for i in range(len(mylines)):\n grp = \"default_grp%d\" %(i)\n ch = \"default_ch%d\" %(i)\n m3u = mylines[i].rstrip()\n # print(ch)\n # print(ch, grp, m3u)\n array2 = [ch, grp, m3u]\n listo.append(array2)\nelse:\n\n print(\"Incorrect File format \")\n\ndef dicty(array1):\n new_dict = {}\n for m in range(len(array1)):\n if new_dict.get(array1[m][0]) == None:\n new_dict[array1[m][0]] = {}\n new_dict[array1[m][0]][array1[m][1]] = {}\n new_dict[array1[m][0]][array1[m][1]][array1[m][2]] = {}\n elif new_dict.get(array1[m][0]) != None:\n if new_dict.get(array1[m][0], {}).get(array1[m][1]) == None:\n new_dict[array1[m][0]][array1[m][1]] = {}\n new_dict[array1[m][0]][array1[m][1]][array1[m][2]] = {}\n else:\n # print(\"test\", new_dict[array1[m][0]][array1[m][1]])\n pass\n else:\n print(\"check again\")\n\n for cha, grpt in new_dict.items():\n for gt, m3 in grpt.items():\n for m31, m32 in m3.items():\n # print(new_dict[cha][gt])\n # print(m32)\n dicta = work2.M3dict(m31, set(), 0)\n new_dict[cha][gt][m31] = dicta.getfiles()\n print(m31)\n\n return new_dict\n\nm3u8l = dicty(listo)\nif m3u8l != {}:\n def convertdot(d):\n new = {}\n for k, v in d.items():\n if isinstance(v, dict):\n v = convertdot(v)\n new[k.replace('.', '__DOT__')] = v\n return new\n\n\n m3u8d = convertdot(m3u8l)\n print(m3u8d)\n\n myclient = pymongo.MongoClient(\"mongodb://192.168.5.157:27017/\")\n mydb = myclient[\"mydatabase\"]\n mycol = mydb[\"m3u8_files\"]\n x = mycol.insert_one(m3u8d)\n","sub_path":"testfile.py","file_name":"testfile.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"450365232","text":"# Sintannaverhuur\n#\n# mprog apps\n# Abel van Gennep\n#\n# Sintannaverhuur is a bookings application for a rental house.\n# De Calendar is synchronised with a google calendar and makes use of a javascript calendar, to\n# display the booking dates.\n# The website also gives an impression of the surroundings.\n# ================================================================================================\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.contrib import messages \nfrom apiclient.discovery import build\nfrom datetime import date, datetime\nfrom dateutil.relativedelta import relativedelta\nimport os\nimport pickle\nimport smtplib\n\ndef index(request):\n # Make a list, which exists out of the names of all the files in the folder sfeer\n path=\"/Users/abelvangennep/Desktop/Programmeren/project-sintanna/app/sintannaverhuur/bookings/static/bookings/afbeeldingen/sfeer\" # insert the path to your directory \n sfeer_afbeeldingen = os.listdir(path) \n sfeer_afbeeldingen.pop(0)\n \n context = {\n 'sfeer_afbeeldingen': sfeer_afbeeldingen,\n }\n return render(request, \"bookings/index.html\", context)\n\ndef indeling(request):\n # Make a list, which exists out of the names of all the files in the folder inrichting\n path=\"/Users/abelvangennep/Desktop/Programmeren/project-sintanna/app/sintannaverhuur/bookings/static/bookings/afbeeldingen/inrichting\" # insert the path to your directory \n inrichting_afbeeldingen = os.listdir(path) \n inrichting_afbeeldingen.pop(0)\n\n context = {\n 'inrichting_afbeeldingen': inrichting_afbeeldingen,\n }\n return render(request, \"bookings/indeling.html\", context)\n\ndef contact(request):\n return render(request, \"bookings/contact.html\")\n\ndef book(request):\n # If user submits a booking get their input\n if request.method == 'POST': \n arrival_date = request.POST[\"arrival_date\"]\n departure_date = request.POST.get(\"departure_date\")\n firstname = request.POST.get(\"firstname\")\n lastname = request.POST.get(\"lastname\")\n email = request.POST.get(\"email\")\n telefoonnummer = request.POST.get(\"telefoonnummer\")\n quest_number = request.POST.get(\"quest_number\")\n comment = request.POST.get(\"comment\")\n\n # Get the price of the stay\n price = pricecalculator(DateStringToObject(arrival_date), DateStringToObject(departure_date), quest_number)\n\n event = {\n 'summary': f\"{firstname} {lastname}\",\n 'description': f\"booking=website telefoonnummer: {telefoonnummer} aantal gasten: {quest_number} opmerking:{comment} prijs:{price}\",\n 'start': {\n 'date': arrival_date,\n },\n 'end': {\n 'date': departure_date,\n },\n 'attendees': [\n {'email': email},\n ], \n }\n\n # Check whether date is available\n if dateisavailable(get_booking(), arrival_date, departure_date):\n # login to Google api\n service = google_service()\n\n # Insert event in the calendar \"boekings\"\n event = service.events().insert(calendarId='uhtbefspsip0e23u07cspnj2r4@group.calendar.google.com', body=event).execute()\n \n # Sent bookings confirmation\n subject = \"Boekingsbevestiging\"\n msg = f\"U boeking is in goede orde ontvangen en verwerkt. De aankomst datum van u boeking is: {arrival_date} na 16:00. U vertrekdatum is: {departure_date} voor 10:00\"\n send_email(subject, msg, email)\n \n context = {\n \"prijs\": price,\n \"aankomst\": arrival_date,\n \"vertrek\": departure_date\n }\n\n return render(request, \"bookings/confirmation.html\", context)\n # Als datum niet beschikbaar is, verstuur error\n messages.error(request, \"De boeking is niet gelukt, neem contact op met de verhuurder.\")\n \n\n return render(request, \"bookings/book.html\")\n\ndef get_booking():\n # login to Google api\n service = google_service()\n\n # Get all events of the calendar \"boekings\"\n result = service.events().list(calendarId='uhtbefspsip0e23u07cspnj2r4@group.calendar.google.com', timeZone=\"Europe/Amsterdam\").execute()\n booking = []\n\n # Filter events which have booking=website in their description\n for item in result['items']:\n if 'booking=website' in item['description']:\n booking.append(item)\n return booking\n \ndef pricecalculator(arrival, departure, quest_number):\n # Calculate of nights of a specific stay \n days =(departure - arrival).days\n \n # Create a dictionary price and calculate the prices of all the components\n prijs = {}\n prijs[\"nachtprijs\"] = days * 70\n prijs[\"schoonmaakprijs\"] = 55\n prijs[\"linnengoedprijs\"] = 12.50 * int(quest_number)\n if int(quest_number) > 4:\n prijs[\"toeslag_exta\"] = (int(quest_number) - 4) * 10 * days \n else:\n prijs[\"toeslag_exta\"] = 0\n prijs[\"totaal\"] = prijs[\"nachtprijs\"] + prijs[\"schoonmaakprijs\"] + prijs[\"linnengoedprijs\"] + prijs[\"toeslag_exta\"]\n\n return prijs\n\ndef DateStringToObject(datum):\n # convert date string in a date object of the module datetime\n date = datetime.strptime(datum, '%Y-%m-%d').date()\n return date\n\ndef dateisavailable(bookings, arrival_date, departure_date):\n # Check whether dat the booked date has overlap with one of the bookings \n for booking in bookings:\n if (booking[\"start\"][\"date\"] < departure_date and arrival_date < booking[\"end\"][\"date\"]):\n return False\n return True\n\ndef send_email(subject, msg, email):\n try:\n # Use the SMTP module to send an email\n user_email = \"sintannaverhuur@gmail.com\"\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.ehlo()\n server.starttls()\n server.login(user_email, \"Vangennep1\")\n message = 'Subject: {}\\n\\n{}'.format(subject,msg)\n server.sendmail(user_email, email, message)\n server.quit()\n\n except:\n pass\n\ndef google_service():\n # Use credentials to log in to the google service API\n credentials = pickle.load(open(\"/Users/abelvangennep/Desktop/Programmeren/project-sintanna/app/googleapi-setup/token.pkl\", \"rb\"))\n service = build(\"calendar\", \"v3\", credentials=credentials)\n return service\n\n","sub_path":"app/sintannaverhuur/bookings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"605943596","text":"from odoo.tests.common import TransactionCase\n\nclass TestTargetUseRange(TransactionCase):\n def setUp(self, *args, **kwargs):\n super(TestTargetUseRange, self).setUp(*args, **kwargs)\n #self.demo_user = self.env.ref('base.user_demo')\n TargetUse = self.env['terralab.targetuse']#.sudo(self.demo_user)\n self.target_use_1 = TargetUse.create({\n 'spreadsheet': None,\n 'default_code': 'target_use_1',\n 'name': 'Target Use 1',\n })\n TestType = self.env['terralab.testtype']#.sudo(self.demo_user)\n self.test_type_1 = TestType.create({\n 'sample_types': [],\n 'spreadsheet': None,\n 'default_code': 'test_type_1',\n 'name': 'Test Type 1',\n 'test_products': [],\n 'test_result_uom_name': 'uom',\n })\n\n def test_create_target_use_range(self):\n \"\"\"Create a target use range\"\"\"\n TargetUseRange = self.env['terralab.targetuserange']#.sudo(self.demo_user)\n target_use_range_1 = TargetUseRange.create({\n 'spreadsheet': None,\n 'test_type': self.test_type_1.id,\n 'target_use': self.target_use_1.id,\n 'num_thresholds': 5,\n 'threshold_1': 1,\n 'threshold_2': 2,\n 'threshold_3': 3,\n 'threshold_4': 4,\n 'threshold_5': 5,\n })\n self.assertEqual(target_use_range_1.name, '%s (%s)' % (self.target_use_1.name, self.test_type_1.name))\n self.assertEqual(target_use_range_1.num_thresholds, 5)\n self.assertEqual(target_use_range_1.threshold_1, 1)\n self.assertEqual(target_use_range_1.threshold_2, 2)\n self.assertEqual(target_use_range_1.threshold_3, 3)\n self.assertEqual(target_use_range_1.threshold_4, 4)\n self.assertEqual(target_use_range_1.threshold_5, 5)\n","sub_path":"terralab/tests/test_target_use_range.py","file_name":"test_target_use_range.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"102083448","text":"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport cv2\nimport os\n\ndef get_images_recursively(parent, extension='.png'):\n file_container = []\n for root, dirs, files in os.walk(parent):\n for file in files:\n if file.endswith(extension):\n file_container.append(os.path.join(root, file))\n return file_container\n\ndef display_images(fname, n_images=12, n_rows=6, title=None):\n random_files = np.random.choice(fname, n_images)\n images = []\n for file in random_files:\n images.append(mpimg.imread(file))\n\n grid_space = gridspec.GridSpec(n_images // n_rows + 1, n_rows)\n grid_space.update(wspace=0.1, hspace=0.1)\n plt.figure(figsize=(n_rows, n_images // n_rows + 1))\n\n for i in range(0, n_images):\n ax1 = plt.subplot(grid_space[i])\n ax1.axis('off')\n ax1.imshow(images[i])\n\n if title is not None:\n plt.suptitle(title)\n plt.show()\n\ndef display_features(hog_features, images, color_map=None, suptitle=None):\n n_images = len(images)\n space = gridspec.GridSpec(n_images, 2)\n space.update(wspace=0.1, hspace=0.1)\n plt.figure(figsize=(4, 2 * (n_images // 2 + 1)))\n\n for i in range(0, n_images*2):\n if i % 2 == 0:\n ax1 = plt.subplot(space[i])\n ax1.axis('off')\n ax1.imshow(images[i // 2], cmap=color_map)\n else:\n ax2 = plt.subplot(space[i])\n ax2.axis('off')\n ax2.imshow(hog_features[i // 2], cmap=color_map)\n\n if suptitle is not None:\n plt.suptitle(suptitle)\n plt.show()","sub_path":"vehicle_lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"141834052","text":"from channels.generic.websocket import WebsocketConsumer\nfrom asgiref.sync import async_to_sync\n#from channels.generic.websocket import AsyncWebsocketConsumer\nimport json\nfrom .models import Message\nfrom django.contrib.auth import get_user_model\n\nUser=get_user_model()\n\nclass ChatConsumer(WebsocketConsumer):\n\n\tdef fetch_messages(self,data):\n\t\t#print('fetch')\n\t\tmessages=Message.last_10_messages()\n\t\tcontent={\n\t\t\t'messages':self.messages_to_json(messages)\n\t\t}\n\t\t\n\t\treturn self.send_message(content)\n\n\tdef new_message(self,data):\n\t\t#print('new msg')\n\t\tauthor=data['from']\n\t\tauthor_user=User.objects.filter(username=author)[0]\n\t\tmessage=Message.objects.create(\n\t\t\tauthor=author_user,\n\t\t\tcontent=data['message'])\n\t\tcontent={\n\t\t\t'command':'new_message',\n\t\t\t'message':self.message_to_json(message)\n\t\t}\n\t\treturn self.send_chat_message(content)\n\n\n\tdef messages_to_json(self,messages):\n\t\tresult=[]\n\t\tfor message in messages:\n\t\t\tresult.append(self.message_to_json(message))\n\t\treturn result\n\n\tdef message_to_json(self,message):\n\n\t\treturn{\n\t\t\t'author':message.author.username,\n\t\t\t'content':message.content,\n\t\t\t'timestamp':str(message.timestamp)\n\t\t}\n\n\tcommands={\n\t\t'fetch_messages':fetch_messages,\n\t\t'new_message':new_message\n\t}\n\n\tdef connect(self):\n\t\tself.room_name=self.scope['url_route']['kwargs']['room_name']\n\t\tself.room_group_name = 'chat_%s' % self.room_name\n\t\t\n\t\t# Join room group\n\t\tasync_to_sync(self.channel_layer.group_add)(\n\t\t\tself.room_group_name,\n\t\t\tself.channel_name\n\t\t)\n\t\t\t\n\t\t\n\t\tself.accept()\n\n\tdef disconnect(self,close_code):\n\t\t# Leave room group\n\t\tasync_to_sync(self.channel_layer.group_discard)(\n\t\t\tself.room_group_name,\n\t\t\tself.channel_name\n\t\t)\n\n\t# Receive message from Websocket\n\tdef receive(self,text_data):\n\t\tdata=json.loads(text_data)\n\t\tself.commands[data['command']](self,data)\n\n\tdef send_chat_message(self,message):\n\t\t#message=data['message']\n\n\t\t# Send message to room group\n\t\tasync_to_sync(self.channel_layer.group_send)(\n\t\t\tself.room_group_name,\n\t\t\t{\n\t\t\t\t'type':'chat_message',\n\t\t\t\t'message':message\n\t\t\t}\n\n\t\t)\n\tdef send_message(self,message):\n\t\tself.send(text_data=json.dumps(message))\n\n\t# Receive message from room group\n\tdef chat_message(self,event):\n\t\tmessage=event['message']\n\t\t#print(message)\n\t\t# Send message to WebSocket\n\t\tself.send(text_data=json.dumps(message))\n\n\n'''\n\nclass ChatConsumer(AsyncWebsocketConsumer):\n async def connect(self):\n self.room_name = self.scope['url_route']['kwargs']['room_name']\n self.room_group_name = 'chat_%s' % self.room_name\n\n # Join room group\n await self.channel_layer.group_add(\n self.room_group_name,\n self.channel_name\n )\n\n await self.accept()\n\n async def disconnect(self, close_code):\n # Leave room group\n await self.channel_layer.group_discard(\n self.room_group_name,\n self.channel_name\n )\n\n # Receive message from WebSocket\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n\n # Send message to room group\n await self.channel_layer.group_send(\n self.room_group_name,\n {\n 'type': 'chat_message',\n 'message': message\n }\n )\n\n # Receive message from room group\n async def chat_message(self, event):\n message = event['message']\n\n # Send message to WebSocket\n await self.send(text_data=json.dumps({\n 'message': message\n }))\n'''","sub_path":"justchat/chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"367196573","text":"from bs4 import BeautifulSoup\nfrom urllib.parse import urlencode\nimport sys\nfrom urllib.request import Request, urlopen\nfrom datetime import datetime, timedelta\nimport math\nimport json\nimport os\nimport xmltodict\nimport pandas as pd\nimport re\nimport pymysql\nfrom sqlalchemy import create_engine\n\n\nRESULT_DIRECTORY = '../__result__/crawling'\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlencode\nimport sys\nfrom urllib.request import Request, urlopen\nfrom datetime import datetime, timedelta\nimport math\nimport json\nimport os\nimport xmltodict\nimport pandas as pd\nimport re\nimport pymysql\nfrom sqlalchemy import create_engine\n\nRESULT_DIRECTORY = '../__result__/crawling'\n\n#동물관리보호소 공공데이터 API 서비스키\n\n# SURVICE_KEY = 'lPho2AedT94HdWcuLEqLx%2FxutLFprTW4diIv6lp%2FylcbEtT0TFuMSfWdSiWip2LcqZ3fRfZ4tTKNyZiU%2BKUfAw%3D%3D'\nSURVICE_KEY = 'kjzgwf40zX1dWlcX1PKEw2r%2BUfP1YbASnaMYa5dQ6aOr9mFJOi%2FcDQB%2FRlvaWdCVVQ5uSS%2BWwXU1WJYDAFmmBA%3D%3D' # 김민규\n# SURVICE_KEY = 'EdieVeGWBCgcq7f02Z4gpx%2FEssqE8l151SGr%2FHYps1SvWYKgXvpn35kSxTQUhMkxyf9yOrp2SU%2Fr9xZjf7aWQA%3D%3D' # 송수진\n# SURVICE_KEY = 'FXCllNPKHcV69y%2FBSMoNxmHKoCNvPRagdDMlScSRSsNJLbGqp12VchucwYzzGf1jWKNrbyi%2BBDF0zJSL%2Bi4K3Q%3D%3D' # 김신애\nbase_url='http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/abandonmentPublic'\n\n\ndef animal_url(base=base_url, **params):\n url = '%s?%s&ServiceKey=%s' % (base, urlencode(params), SURVICE_KEY)\n return url\n\ndef animal_crawling():\n year = datetime.now().strftime('%Y')\n year = int(year)\n date = datetime.now().date()\n date = date - timedelta(days=1)\n date = str(date).split('-')\n\n # for year in range(2018): # 년도가 바뀔 때마다, pageNo, isnext 초기화\n\n bgnde = '%s%s%s' % (date[0], date[1], date[2]) # 주소값 시작일\n endde = '%s%s%s' % (date[0], date[1], date[2]) # 끝일\n pageNo = 1\n isnext = True\n datalist = []\n columns = []\n encoding = 'utf-8'\n numOfRows = '1'\n\n while isnext:\n url = animal_url(bgnde=bgnde, endde=endde, pageNo=pageNo, numOfRows=numOfRows)\n res = urlopen(url=url)\n\n if res is None:\n break\n\n xml_result = res.read().decode(encoding)\n xml_data = xmltodict.parse(xml_result)\n xml_dict = json.dumps(xml_data)\n dict_result = json.loads(xml_dict)\n xml_body = dict_result.get('response').get('body')\n print(xml_body)\n xml_nor = None if dict_result is None else xml_body.get('numOfRows')\n xml_tc = None if dict_result is None else xml_body.get('totalCount')\n lostData = xml_body.get('items').get('item')\n\n datalist.append(lostData)\n\n\n cnt = math.ceil(int(xml_tc)/int(xml_nor)) # 크롤링 횟수 확인\n\n if pageNo == cnt:\n isnext = False\n else:\n pageNo += 1\n\n df_crawling = pd.DataFrame(datalist) # Dict -> DataFrame\n df_crawling.to_csv('{0}/{1}_realtime_data.csv'.format(RESULT_DIRECTORY, bgnde), encoding='euc-kr', mode='w', index=True)\n\ndef db_save():\n year = datetime.now().strftime('%Y')\n year = int(year)\n date = datetime.now().date()\n date = date - timedelta(days=1)\n date = str(date).split('-')\n bgnde = '%s%s%s' % (date[0], date[1], date[2]) # 주소값 시작일\n\n df = pd.read_csv('{0}/{1}_realtime_data.csv'.format(RESULT_DIRECTORY, bgnde), encoding=\"euc-kr\")\n df = df.drop(\"Unnamed: 0\", 1)\n df = df.fillna(\"NaN\")\n\n # df = pd.read_csv('{0}/{1}_realtime_data.csv'.format(RESULT_DIRECTORY, bgnde),encoding=\"euc-kr\")\n # df = df.drop(\"Unnamed: 0\", 1)\n # print(df)\n\n # ------------------------------------------- 컬럼을 리스트로 변환\n a = [df.loc[i, j] for i in df.index for j in df[['weight']]]\n b = [df.loc[i, j] for i in df.index for j in df[['age']]]\n\n temp_weight = []\n temp_age = []\n\n # ------------------------------------ weight 에러단어만 검출\n for i in a:\n pattern = re.compile(r'\\d[.]\\d\\(Kg\\)+|\\d\\(Kg\\)+|\\d\\d\\(Kg\\)+|\\d?\\d[.]\\d?\\d?\\(Kg\\)') # 형식에 맞는 패턴 인식\n no_error_weight_word = pattern.findall(i) # 패턴값과 맞는 값을 반환\n temp_weight += no_error_weight_word # 임시리스트에 추가\n error_word_weight = list(set(a) - set(temp_weight)) # 차집합\n print(\"에러다 시버펄\\n\")\n print(temp_weight)\n print(no_error_weight_word, '\\n')\n\n print(\"임시 weight 리스트 반환\\n\")\n print(temp_weight, '\\n')\n\n print(\"임시 에러weight 초기화\\n\")\n del temp_weight[:]\n print(temp_weight)\n\n print(error_word_weight)\n\n # ------------------------------------ age 에러단어만 검출\n for j in b:\n pattern2 = re.compile(r'20+[0-1]+[0-9]\\(년생\\)') # 형식에 맞는 패턴 인식\n no_error_age_word = pattern2.findall(j) # 패턴값과 맞는 값을 반환\n temp_age += no_error_age_word # 임시리스트에 추가\n error_word_age = list(set(b) - set(temp_age)) # 차집합\n print(no_error_age_word, \"패턴값 반환\")\n print(temp_age, \"임시 age 리스트 반환\")\n del temp_age[:]\n print(temp_age, \"임시 에러age 초기화\")\n print(error_word_age)\n conn = pymysql.connect(host='localhost', user='root', password='qwer1234!', db='animaldb', charset='utf8mb4', )\n curs = conn.cursor()\n # -----------------------테이블이 없을시에 테이블 생성\n\n SQL_QUERY = '''\n CREATE TABLE IF NOT EXISTS animaldb.weight_error(\n id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n weight VARCHAR(30) NOT NULL,\n PRIMARY KEY(id)\n )DEFAULT CHARSET=utf8mb4 '''\n SQL_QUERY2 = \"\"\"\n CREATE TABLE IF NOT EXISTS animaldb.age_error(\n id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n age VARCHAR(30) NOT NULL,\n PRIMARY KEY(id)\n )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 \n \"\"\"\n\n curs.execute(SQL_QUERY)\n conn.commit()\n\n curs.execute(SQL_QUERY2)\n conn.commit()\n\n # === 에러단어만 각 테이블에 insert ===\n\n sql1 = \"\"\"insert into age_error(age) values (%s)\"\"\"\n sql2 = \"\"\"insert into weight_error(weight) values (%s)\"\"\"\n\n # === 에러단어만 들어있는 리스트를 통채로 db에 적재 ===\n curs.executemany(sql1, error_word_age)\n conn.commit()\n\n curs.executemany(sql2, error_word_weight)\n conn.commit()\n\n # === 적제된 에러문자의 데이터를 select문으로 불러옴\n sql_a = \"\"\" select * from weight_error \"\"\"\n sql_b = \"\"\" select * from age_error\"\"\"\n\n curs.execute(sql_a)\n result_weight_error = curs.fetchall()\n print(result_weight_error, \"db_weight 에러단어\\n\")\n\n curs.execute(sql_b)\n result_age_error = curs.fetchall()\n print(result_age_error, \"db_age 에러단어\\n\")\n\n list_temp = [] # weight에러가 있는 로우가 들어갈 리스트\n list_temp2 = [] # weight,age오류가 없는 로우가 들어갈 리스트\n\n # ------��러온 에러단어리스트 속 튜플에서 속성값 i값의 1번째를 가져옴\n if len(result_weight_error) != 0:\n for i in result_weight_error:\n error = i[1]\n for j in df.itertuples():\n\n if j.__contains__(error):\n list_temp.append(j)\n else:\n list_temp2.append(j)\n\n list_temp2 = list(set(list_temp2))\n else:\n for j in df.itertuples():\n list_temp2.append(j)\n\n list_temp2 = list(set(list_temp2))\n print(\"weight 에러단어가 없습니다.\")\n # print(list_temp2,'에러없는 데이터')\n # print(list_temp,'에러있는 데이터')\n\n if len(result_age_error) != 0:\n for i in result_age_error:\n error = i[1]\n for j in list_temp2:\n\n if j.__contains__(error):\n list_temp.append(j)\n else:\n print(\"age에러단어가 없습니다.\")\n\n engine = create_engine(\"mysql+pymysql://root:\" + \"qwer1234!\" + \"@localhost:3306/animaldb?charset=utf8mb4\",\n encoding='utf8')\n conn = engine.connect()\n\n if len(set(list_temp)) != 0:\n realdata = list(set(list_temp2) - set(list_temp))\n else:\n realdata = list(set(list_temp2))\n print(realdata)\n\n if len(set(list_temp)) != 0:\n error_df = pd.DataFrame(list_temp).drop('Index', 1).drop_duplicates() # index 컬럼제거 row중복값 제거\n print(\"error_df\", error_df)\n error_df.to_sql(name='animal_realtime_2018_error', con=engine, if_exists='append', index=False)\n del error_df\n else:\n print(\"에러데이터가 없기때문에 저장하지 않습니다.\")\n\n if len(realdata) != 0:\n\n\n no_error_df = pd.DataFrame(realdata).drop('Index', 1).drop_duplicates() # index 컬럼제거 row중복값 제거\n print(\"에러가 없는 데이터를 저장했습니다.\", no_error_df)\n\n\n # ---------------전처리 시작하는 부분----------------#\n #----------age 전처리-------------------------------\n no_error_df['age(before)'] = no_error_df[\"age\"].copy(deep=True)\n no_error_df['age(after)'] = no_error_df['age'].copy(deep=True)\n\n list_age = []\n ages = no_error_df[\"age(after)\"]\n for i in ages:\n parse = re.sub('\\(년생\\)', '', i)\n age = abs(int(parse) - int(2018))\n list_age.append(age)\n\n no_error_df['age(after)'] = list_age\n\n\n #### (processState, sexCd, neuterYn) 전처리(레이블링, column화, one-hot 코딩)\n\n no_error_df.loc[no_error_df['processState'] == '보호중', 'processState'] = 'C' # 보호중\n no_error_df.loc[no_error_df['processState'] == '종료(입양)', 'processState'] = 'A'\n no_error_df.loc[no_error_df['processState'] == '종료(기증)', 'processState'] = 'A'\n no_error_df.loc[no_error_df['processState'] == '종료(자연사)', 'processState'] = 'D'\n no_error_df.loc[no_error_df['processState'] == '종료(안락사)', 'processState'] = 'D'\n no_error_df.loc[no_error_df['processState'] == '종료(반환)', 'processState'] = 'R'\n no_error_df.loc[no_error_df['processState'] == '종료(방사)', 'processState'] = 'E'\n no_error_df.loc[no_error_df['processState'] == '종료(미포획)', 'processState'] = 'E'\n no_error_df['processState_Pre'] = no_error_df['processState']\n\n no_error_df['processState_C'] = no_error_df['processState'] == 'C' # 보호중\n no_error_df['processState_A'] = no_error_df['processState'] == 'A' # 입양+기증\n no_error_df['processState_D'] = no_error_df['processState'] == 'D' # 자연사+안락사\n no_error_df['processState_R'] = no_error_df['processState'] == 'R' # 반환\n no_error_df['processState_E'] = no_error_df['processState'] == 'E' # 미포획+방사\n\n\n ### -process state_pre: 문자->숫자 mapping\n\n proc_mapping = {\"C\": 0, \"A\": 1, \"D\": 2, \"R\": 3, \"E\": 4}\n no_error_df['processState_Pre'] = no_error_df['processState_Pre'].map(proc_mapping)\n\n ### 성별( M=남, F=여자, Q=미상)\n no_error_df['sexCd_M'] = no_error_df['sexCd'] == 'M'\n no_error_df['sexCd_F'] = no_error_df['sexCd'] == 'F'\n no_error_df['sexCd_Q'] = no_error_df['sexCd'] == 'Q'\n no_error_df[['sexCd', 'sexCd_M', 'sexCd_F', 'sexCd_Q']].head(30)\n\n ### -neuterYn 문자-> 숫자\n sex_mapping = {\"M\": 0, \"F\": 1, \"Q\": 2}\n no_error_df['sexCd'] = no_error_df['sexCd'].map(sex_mapping)\n no_error_df.sexCd\n\n ### 중성화여부 (Y=중성화, N=중성화X, U=미확인)\n no_error_df['neuterYn_Y'] = no_error_df['neuterYn'] == 'Y'\n no_error_df['neuterYn_N'] = no_error_df['neuterYn'] == 'N'\n no_error_df['neuterYn_U'] = no_error_df['neuterYn'] == 'U'\n no_error_df[['neuterYn', 'neuterYn_Y', 'neuterYn_N', 'neuterYn_U']].head(20)\n\n ### neuterYn: 문자-> 숫자\n\n neuter_mapping = {\"Y\": 0, \"N\": 1, \"U\": 2}\n no_error_df['neuterYn'] = no_error_df['neuterYn'].map(neuter_mapping)\n no_error_df.neuterYn[1:3]\n\n ### 보호장소\n dfh1 = no_error_df['careNm'].str.contains('병원|의료센터|메디컬|클리닉|의료원') # 메디컬(715)+의료(91)+의료(23408)\n dfh2 = no_error_df['careNm'].str.contains('보호소|보호센터|리본센터') # 보호소(18387)+센터(18413)\n dfh3 = no_error_df['careNm'].str.contains('군청|시청') # 군청(54)+시청(24)\n dfh4 = no_error_df['careNm'].str.contains('수의사회') # 수의사회(2443)\n dfh5 = no_error_df['careNm'].str.contains('한동보|협회|보호협') # 한동보(1115)+동물협회(10806)\n dfh6 = no_error_df['careNm'].str.contains('병원|의료|메디컬|클리닉|보호소|보호센터|리본센터|군청|시청|수의사회|한동보|협회|보호협|의료원') == False\n\n no_error_df['careNm_ETC'] = dfh6 # 밑에 컬럼속성들을 제외한 속성\n no_error_df['careNm_H'] = dfh1 # 병원,의료센터,메디컬,클리닉,의료원\n no_error_df['careNm_C'] = dfh2 # 보호소,보호센터,리본센터\n no_error_df['careNm_O'] = dfh3 # 군청, 시청\n no_error_df['careNm_AD'] = dfh4 # 수의사회\n no_error_df['careNm_CM'] = dfh5 # 한동보,동물협회\n\n ### Kind Cd\n\n no_error_df['kind'] = no_error_df['kindCd'].str.extract('([가-힣]+)\\]', expand=False) # 한글 정규식\n no_error_df['kind'].head()\n\n kind_mapping = {'개': 0, '고양이': 1, '기타축종': 2}\n no_error_df['kind'] = no_error_df['kind'].map(kind_mapping)\n\n no_error_df['breed'] = no_error_df['kindCd'].str.split('] ').str[1]\n\n # 8자리를 날짜형식으로 바꿈\n no_error_df['happenDt'] = pd.to_datetime(no_error_df['happenDt'], format='%Y%m%d')\n\n # df['happenWd'] = df['happenDt'].dt.dayofweekday # 요일을 숫자로 표현함 \"0 = Sunday\"\n no_error_df['happenWd'] = no_error_df['happenDt'].dt.day_name()\n\n # 날짜에서 '월'값을 받음\n no_error_df['happenMth'] = pd.DatetimeIndex(no_error_df['happenDt']).month\n\n ### - happenWd(발견요일) : 문자 -> 숫자 mapping\n week_mapping = {\"Monday\": 0, \"Tuesday\": 2, \"Wednesday\": 3,\n \"Thursday\": 4, \"Friday\": 5, \"Saturday\": 6, \"Sunday\": 7}\n no_error_df['happenWd'] = no_error_df['happenWd'].map(week_mapping)\n\n ### orgNm(담당지역주소): 두분류로 나눈뒤, 숫자 mapping\n no_error_df['sido'] = no_error_df['orgNm'].str.split(\" \").str[0]\n sido_mapping = {\"경기도\": 0, \"서울특별시\": 1, \"부산광역시\": 2, \"경상남도\": 3,\n \"인천광역시\": 4, \"충청남도\": 5, \"강원도\": 6, \"대구광역시\": 7,\n \"전라북도\": 8, \"경상북도\": 9, \"대전광역시\": 10, \"울산광역시\": 11,\n \"충청북도\": 12, \"전라남도\": 13, \"제주특별자치도\": 14, \"광주광역시\": 15,\n \"세종특별자치시\": 16\n }\n no_error_df['sido'] = no_error_df['sido'].map(sido_mapping)\n no_error_df['sido'].head(3)\n ### weight\n\n no_error_df['weight(after)'] = no_error_df['weight'].copy(deep=True)\n list_weight = []\n weights = no_error_df[\"weight(after)\"]\n for i in weights:\n parse = re.sub('\\(Kg\\)', '', i)\n list_weight.append(float(parse))\n\n no_error_df['weight(after)'] = list_weight\n\n no_error_df.loc[no_error_df['weight(after)'] <= 3, 'size'] = '초소형'\n no_error_df.loc[(no_error_df['weight(after)'] > 3) & (no_error_df['weight(after)'] <= 9), 'size'] = '소형'\n no_error_df.loc[(no_error_df['weight(after)'] > 9) & (no_error_df['weight(after)'] <= 25), 'size'] = '중형'\n no_error_df.loc[no_error_df['weight(after)'] > 25, 'size'] = '대형'\n\n ### - size : 문자 -> 숫자 mapping\n no_error_df['size'].fillna('중형', inplace=True)\n size_mapping = {\"대형\": 0, \"소형\": 1, \"중형\": 2, \"초소형\": 3}\n no_error_df['size'] = no_error_df['size'].map(size_mapping)\n\n ### age\n no_error_df.loc[no_error_df['age(after)'] <= 1, 'age_u'] = '유견기'\n no_error_df.loc[(no_error_df['age(after)'] > 1) & (no_error_df['age(after)'] <= 9), 'age_u'] = '성견기'\n no_error_df.loc[no_error_df['age(after)'] > 9, 'age_u'] = '노견기'\n\n ### -age mapping\n age_mapping = {\"노견기\": 0, \"성견기\": 1, \"유견기\": 2}\n no_error_df['age_u'] = no_error_df['age_u'].map(age_mapping)\n columns = ['age(after)', 'colorCd', 'neuterYn', 'noticeEdt', 'orgNm', 'sexCd', 'weight(after)', 'kind',\n 'happenWd','happenMth', 'size', 'age_u', 'processState_Pre', 'processState_C', 'processState_A',\n 'processState_D', 'processState_R', 'processState_E', 'sexCd_M', 'sexCd_F', 'sexCd_Q', 'neuterYn_Y',\n 'neuterYn_N', 'neuterYn_U', 'careNm_ETC', 'careNm_H', 'careNm_C', 'careNm_O', 'careNm_AD',\n 'careNm_CM', 'sido']\n no_error_df=pd.DataFrame(no_error_df,columns=columns)\n\n no_error_df.to_sql(name='animal_realtime_2018', con=engine, if_exists='append', index=False )\n\n conn.close()\n\n del list_temp[:]\n del list_temp2[:]\n print(list_temp2)\n\n\nif not os.path.exists(RESULT_DIRECTORY):\n os.makedirs(RESULT_DIRECTORY)\n\nif __name__ == '__main__':\n animal_crawling()\n db_save()","sub_path":"collection/real_crawling.py","file_name":"real_crawling.py","file_ext":"py","file_size_in_byte":17758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"467710598","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as scio\nimport lrCostFunction as lCF\nimport oneVsAll as ova\nfrom displayData import *\nimport predictOneVsAll as pova\n\nplt.ion()\n\ninput_layer_size = 400 # 20x20 input images of Digits\nnum_labels = 10 # 10 labels, from 0 to 9\n\ndata = scio.loadmat('./data/ex3data1.mat')\n\nX = data['X']\ny = data['y'].flatten()\nm = y.size\n\n# Randomly select 100 data points to display\nrand_indices = np.random.permutation(range(m))\nselected = X[rand_indices[0:100], :]\n\ndisplay_data(selected)\n\n\n# input('Program paused. Press ENTER to continue')\n\ntheta_t = np.array([-2, -1, 1, 2])\nX_t = np.c_[np.ones(5), np.arange(1, 16).reshape((3, 5)).T/10]\ny_t = np.array([1, 0, 1, 0, 1])\nlmda_t = 3\ncost, grad = lCF.lr_cost_function(theta_t, X_t, y_t, lmda_t)\n\nnp.set_printoptions(formatter={'float': '{: 0.6f}'.format})\nprint('Cost: {:0.7f}'.format(cost))\nprint('Expected cost: 2.534819')\nprint('Gradients:\\n{}'.format(grad))\nprint('Expected gradients:\\n[ 0.146561 -0.548558 0.724722 1.398003]')\n\n\nprint('Training One-vs-All Logistic Regression ...')\n\nlmd = 0.1\nall_theta = ova.one_vs_all(X, y, num_labels, lmd)\n\ninput('Program paused. Press ENTER to continue')\n\npred = pova.predict_one_vs_all(all_theta, X)\n\nprint('Training set accuracy: {}'.format(np.mean(pred == y)*100))\n\ninput('ex3 Finished. Press ENTER to exit')\n","sub_path":"Ng-ML-PY/ex3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"469941316","text":"# -*- coding: utf-8 -*-\nfrom admintool.nc import models\nfrom admintool.lib import *\nfrom django.conf import settings\n \ndef index(request):\n json = []\n \n #default values\n start = 0\n limit = 17\n \n sort = 'name'\n dir = ''\n \n if 'start' in request.GET:\n try:\n start = int(request.GET['start'])\n except ValueError:\n pass\n else:\n if start < 0: \n start = 0\n \n if 'limit' in request.GET:\n try:\n limit = int(request.GET['limit'])\n except ValueError:\n pass\n else:\n if limit < 0 or limit == 0: \n limit = 17\n\n if 'sort' in request.GET:\n sort = request.GET['sort'].lower()\n \n if 'dir' in request.GET:\n if request.GET['dir'].lower() == 'asc':\n dir = ''\n if request.GET['dir'].lower() == 'desc':\n dir = '-' \n \n order = \"%s%s\" % (dir, sort,)\n \n #фильтрация[c 0 по 4 включительно]\n filter = False\n args = {}\n \n for i in range(5):\n \n search_value = \"filter[%s][data][value]\" % i\n search_field = \"filter[%s][field]\" % i\n \n if search_field in request.GET and search_value in request.GET:\n filter = True\n \n field = str(request.GET[search_field])\n\n if field == 'text': field = 'name'\n if field == 'nc_id': field = 'id'\n\n value = str(request.GET[search_value])\n \n #очищаем VALUE от %\n strip_value = value.replace('%', '')\n if '%' in value:\n \n if value.find('%') == value.rfind('%'):\n #в value имеется единственное вхождение '%'\n \n if value.find('%') == 0:\n #% в начале строки\n args[\"%s__iendswith\" % field] = strip_value\n else:\n #% в конце строки\n args[\"%s__istartswith\" % field] = strip_value\n else:\n #value содержит более чем 1 вхождение символа %\n args[\"%s__icontains\" % field] = strip_value\n else:\n #для всех кроме первого фильтра\n args[\"%s__iexact\" % field] = strip_value\n \n #выполняем фильтрацию\n if i == 0:\n attr_groups = models.AG.objects.filter(**args)\n \n #подсчитываем кол-во отфильтрованных групп\n totalCount = len(attr_groups) \n \n #накладываем start/limit/order\n attr_groups_slice = attr_groups.order_by(order)[start:start+limit]\n else: \n attr_groups = attr_groups.filter(**args)\n \n #подсчитываем кол-во отфильтрованных групп\n totalCount = len(attr_groups)\n\n #накладываем start/limit/order\n attr_groups_slice = attr_groups.order_by(order)[start:start+limit] \n else:\n #если фильтров больше нет - прерываем фильтрование\n break\n \n \n if not filter:\n attr_groups = models.AG.objects.all()\n \n #подсчитываем кол-во отфильтрованных групп\n totalCount = len(attr_groups)\n\n #накладываем start/limit\n attr_groups_slice = attr_groups.order_by(order)[start:start+limit]\n \n for attr_group in attr_groups_slice:\n json.append(attr_group.data())\n \n json = {'totalCount': totalCount, 'data': json}\n \n return HttpResponseJSON.HttpResponseJSON(json)","sub_path":"nc/attr_group/grid/index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285254897","text":"import wikipedia\nimport urllib3\n\ndado = ''\nlinhas = 0\nperguntas = []\nrespostas = []\nkeywords = []\nhttp = urllib3.PoolManager()\n\n\ndef wp(tema):\n tema_link = wikipedia.page(tema)\n print(tema_link.url)\n return (tema_link)\n\n\nlista = http.request('GET',\n 'https://gist.githubusercontent.com/oihugu/ef8766f7ab3780e6e324505b927b0992/raw/e74fa15eec128a7cadce575c391576a1f913816b/perguntas.txt')\nlista = str(lista.data)\n\n\nfor count in range(5, (len(lista) - 2)):\n if (lista[count] + lista[count + 1]) == '\\\\n':\n linhas += 1\n dado = ''\n\n elif (lista[count - 1] + lista[count]) == '\\\\n':\n dado = ''\n\n elif (lista[count] + lista[count + 1] + lista[count + 2]) == 'end':\n break\n\n else:\n dado = dado + lista[count]\n if (lista[count + 1] + lista[count + 2]) == '\\\\n':\n if linhas % 3 == 1:\n perguntas.append(dado)\n if linhas % 3 == 2:\n respostas.append(dado)\n if linhas % 3 == 0:\n keywords.append(dado)\n\nprint(perguntas)\nprint(respostas)\nprint(keywords)\n","sub_path":"jogo.py","file_name":"jogo.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"553101920","text":"from objects.food import Food\nfrom objects.snake import Snake\nimport pygame\n\n# global game variables for access by all modules\n\n# gameboard controls\nGAME_WIDTH = 400\nGAME_HEIGHT = 400\nCLOCK_SPEED = 100\n\n# snake controls\nSNAKE_BODY_SIZE = 10\nSNAKE_COLOR = (255, 64, 89)\n\n# food controls\nFOOD_SIZE = 10\nFOOD_COLOR = (34, 231, 2)\n\nclass Game:\n def __init__(self):\n self.screen = pygame.display.set_mode((GAME_HEIGHT, GAME_WIDTH))\n self.clock = pygame.time.Clock()\n self.food = Food(FOOD_COLOR)\n self.snake = Snake(SNAKE_COLOR)\n self.game_over = False\n\n def run(self):\n # update core game components\n self.clock.tick(100 * (1 + len(self.snake.body) / 50))\n self.screen.fill(pygame.Color(0,0,0))\n\t \n # render the snake and food for the game\n self.food.render(self.screen)\n self.snake.render(self.screen)\n\n # update the snake and check for lose conditions\n self.snake.snake_controls(self.food)\n self.game_over = self.snake.check_lose()\n\n return self.game_over\n","sub_path":"snake/objects/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"415324374","text":"import tensorflow as tf\n\ndef Unit3D(filters, kernel_size=(1, 1, 1), strides=(1, 1, 1), activation='relu', use_batch_norm=True, use_bias=False, name='unit_3d'):\n net = tf.keras.Sequential(name=name)\n net.add( tf.keras.layers.Conv3D(filters=filters, kernel_size=kernel_size, strides=strides, padding='SAME', use_bias=use_bias) )\n if use_batch_norm: net.add( tf.keras.layers.BatchNormalization() )\n if activation is not None: net.add( tf.keras.layers.Activation(activation) )\n return net\n\nclass Inc(tf.keras.Model):\n def __init__(self, filters = [64, [96,128], [16,32], 32], name='Inc'):\n super(Inc, self).__init__()\n self._name = name\n self.branch_0 = Unit3D(filters=filters[0], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n self.branch_1_a = Unit3D(filters=filters[1][0], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n self.branch_1_b = Unit3D(filters=filters[1][1], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n self.branch_2_a = Unit3D(filters=filters[2][0], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n self.branch_2_b = Unit3D(filters=filters[2][1], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n self.branch_3_a = tf.keras.layers.MaxPool3D(pool_size=[3,3,3], strides=[1,1,1], padding='SAME', name='MaxPool3d_0a_3x3')\n self.branch_3_b = Unit3D(filters=filters[3], kernel_size=[1, 1, 1], name='Conv3d_0a_1x1')\n\n def call(self, inputs):\n # with tf.name_scope(self._name):\n with tf.name_scope('Branch_0'):\n branch_0 = self.branch_0(inputs)\n with tf.name_scope('Branch_1'):\n branch_1 = self.branch_1_a(inputs)\n branch_1 = self.branch_1_b(branch_1)\n with tf.name_scope('Branch_2'):\n branch_2 = self.branch_2_a(inputs)\n branch_2 = self.branch_2_b(branch_2)\n with tf.name_scope('Branch_3'):\n branch_3 = self.branch_3_a(inputs)\n branch_3 = self.branch_3_b(branch_3)\n net = tf.concat([branch_0, branch_1, branch_2, branch_3], 4)\n return net\n\n\ndef InceptionI3d(input_shape, num_classes=400, spatial_squeeze=True, final_endpoint='Logits', dropout_keep_prob=0.9, name='inception_i3d'):\n \"\"\"Connects the model to inputs.\n\n Args:\n inputs: Inputs to the model, which should have dimensions\n `batch_size` x `num_frames` x 224 x 224 x `num_channels`.\n is_training: whether to use training mode for snt.BatchNorm (boolean).\n dropout_keep_prob: Probability for the tf.nn.dropout layer (float in\n [0, 1)).\n\n Returns:\n A tuple consisting of:\n 1. Network output at location `final_endpoint`.\n 2. Dictionary containing all endpoints up to `final_endpoint`,\n indexed by endpoint name.\n\n Raises:\n ValueError: if `final_endpoint` is not recognized.\n \"\"\"\n VALID_ENDPOINTS = (\n 'Conv3d_1a_7x7',\n 'MaxPool3d_2a_3x3',\n 'Conv3d_2b_1x1',\n 'Conv3d_2c_3x3',\n 'MaxPool3d_3a_3x3',\n 'Mixed_3b',\n 'Mixed_3c',\n 'MaxPool3d_4a_3x3',\n 'Mixed_4b',\n 'Mixed_4c',\n 'Mixed_4d',\n 'Mixed_4e',\n 'Mixed_4f',\n 'MaxPool3d_5a_2x2',\n 'Mixed_5b',\n 'Mixed_5c',\n 'Logits',\n 'Predictions',\n )\n if final_endpoint not in VALID_ENDPOINTS:\n raise ValueError('Unknown final endpoint %s' % final_endpoint)\n\n input_layer = tf.keras.layers.Input(shape=input_shape)\n end_points = {}\n end_point = 'Conv3d_1a_7x7'\n net = Unit3D(filters=64, kernel_size=[7, 7, 7], strides=[2, 2, 2], name=end_point)(input_layer)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n end_point = 'MaxPool3d_2a_3x3'\n net = tf.keras.layers.MaxPool3D(pool_size=[1,3,3], strides=[1,2,2], padding='SAME', name=end_point)(net)\n '''\n ksize: An int or list of ints that has length 1, 3 or 5. The size of the window for each dimension of the input tensor.\n strides: An int or list of ints that has length 1, 3 or 5. The stride of the sliding window for each dimension of the input tensor.\n \n pool_size: Tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). (2, 2, 2) will halve the size of the 3D input in each dimension.\n strides: tuple of 3 integers, or None. Strides values.\n '''\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n end_point = 'Conv3d_2b_1x1'\n net = Unit3D(filters=64, kernel_size=[1, 1, 1], name=end_point)(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n end_point = 'Conv3d_2c_3x3'\n net = Unit3D(filters=192, kernel_size=[3, 3, 3], name=end_point)(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n end_point = 'MaxPool3d_3a_3x3'\n net = tf.keras.layers.MaxPool3D(pool_size=[1,3,3], strides=[1,2,2], padding='SAME', name=end_point)(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_3b'\n net = Inc([64, [96,128], [16,32], 32], 'Mixed_3b')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_3c'\n net = Inc([128, [128,192], [32,96], 64], 'Mixed_3c')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'MaxPool3d_4a_3x3'\n net = tf.keras.layers.MaxPool3D(pool_size=[3,3,3], strides=[2,2,2], padding='SAME', name=end_point)(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_4b'\n net = Inc([192, [96,208], [16,48], 64], 'Mixed_4b')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_4c'\n net = Inc([160, [112,224], [24,64], 64], 'Mixed_4c')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_4d'\n net = Inc([128, [128,256], [24,64], 64], 'Mixed_4d')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_4e'\n net = Inc([112, [144,288], [32,64], 64], 'Mixed_4e')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_4f'\n net = Inc([256, [160,320], [32,128], 128], 'Mixed_4f')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'MaxPool3d_5a_2x2'\n net = tf.keras.layers.MaxPool3D(pool_size=[2,2,2], strides=[2,2,2], padding='SAME', name=end_point)(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_5b'\n net = Inc([256, [160,320], [32,128], 128], 'Mixed_5b')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Mixed_5c'\n net = Inc([384, [192,384], [48,128], 128], 'Mixed_5c')(net)\n end_points[end_point] = net\n if final_endpoint == end_point: return net, end_points\n\n end_point = 'Logits'\n with tf.name_scope('Logits'):\n net = tf.keras.layers.MaxPool3D(pool_size=[2,7,7], strides=[1,1,1], padding='VALID')(net)\n net = tf.keras.layers.Dropout(dropout_keep_prob)(net)\n logits = Unit3D(filters=num_classes, kernel_size=[1, 1, 1], activation=None, use_batch_norm=False, use_bias=True, name='Conv3d_0c_1x1')(net)\n if spatial_squeeze:\n logits = tf.squeeze(logits, [2, 3], name='SpatialSqueeze')\n averaged_logits = tf.reduce_mean(logits, axis=1)\n end_points[end_point] = averaged_logits\n if final_endpoint == end_point: return averaged_logits, input_layer, end_points\n\n end_point = 'Predictions'\n predictions = tf.keras.activations.softmax(averaged_logits)\n end_points[end_point] = predictions\n return predictions, end_points\n\nif __name__ == '__main__':\n # model = tf.keras.Sequential(name = \"discriminator\")\n # model.add( tf.keras.layers.InputLayer((64,224,224,3)) )\n # model.add( Unit3D(64) )\n # model.add( Inc([64, [96,128], [16,32], 32], name = 'Inc') )\n # model.add( Inc([64, [96,128], [16,32], 32], name = 'Inc2') )\n # model.summary()\n\n averaged_logits, input_layer, end_points = InceptionI3d((64, 224, 224, 3), 400)\n model = tf.keras.models.Model(input_layer, end_points['Logits'])\n model.summary()\n\n # for layer in model.layers:\n # print(layer.name)\n # if 'Mixed' in layer.name:\n # for layer_ in layer.layers:\n # print('\\t', layer_.name)\n\n # for weight in model.weights:\n # print(weight.name)\n # rand = tf.random.normal([10,64,224,224,3])\n # print(model(rand))","sub_path":"test/I3D_github.py","file_name":"I3D_github.py","file_ext":"py","file_size_in_byte":8800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"87171830","text":"### first\n\nx = [i*2 for i in range(50)]\n\ng = (i*2 for i in range(50)) #generator\n\nfor i in g:\n print(i)\n \n### second\n\ndef fib(times):\n n = 0\n a, b = 0, 1\n while n < times:\n print(b)\n a, b = b, a+b\n n += 1\n return 'Done'\n\nprint(fib(10))\n\n\n### third, generator\n\ndef lib(times):\n n = 0\n a, b = 0, 1\n while n < times:\n yield b\n a, b = b, a+b\n n += 1\n\nprint(lib(10))\n\nfor i in lib(10):\n print(i)\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42255408","text":"import cv2 as cv\ncap = cv.VideoCapture(0)\n\n# get width and height of the view port, the video's size must be same as them\nwidth = int(cap.get(3))\nheight = int(cap.get(4))\n\n# set format as mp4 on Mac.\nfourcc = cv.VideoWriter_fourcc(*'mp4v')\nout = cv.VideoWriter('helloworld.mp4',fourcc, 10.0, (width, height))\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n if ret==True:\n # write the frame\n out.write(frame)\n # custiomize the window title\n cv.imshow('demo',frame)\n # program will quit if press 'q' on keyboard\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n# Release everything if job is finished\ncap.release()\nout.release()\ncv.destroyAllWindows()","sub_path":"helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"621076213","text":"import numpy as np \n\ndef f(arr,s,haveone) :\n if haveone and s==0 :\n return True\n if len(arr) == 0 :\n return False\n if f(arr[1:],s,haveone) :\n return True\n if f(arr[1:],s-arr[0],True) :\n return True\n return False\n\nmaxSum = 0\nn = int(input())\narr = list()\nfor i in range(n) :\n a,b,c = input().split()\n a = 1 if a == 'acid' else -1\n b = int(b)\n c = int(c)\n arr.append(a*b*c)\n maxSum += b*c\n\nif f(arr,0,False) :\n print('yes')\nelse :\n print('no')","sub_path":"4/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"646122657","text":"# %%\n\nimport argparse\nimport os\nimport librosa\nimport numpy as np\nimport time as time\nimport librosa.output as lo\nimport tensorflow as tf\nprint(tf.VERSION)\n\nparser = argparse.ArgumentParser()\n\n# Example usage\n# python infer.py -c train-techno\\model.ckpt-72825 -ig train-techno\\infer\\infer.meta -n 100 --human_friendly True\n# 'train-techno\\model.ckpt-72825'\nparser.add_argument('--checkpoint_name', '-c', type=str, required=True)\n\n# 'train-techno\\infer\\infer.meta'\nparser.add_argument('--infer_graph', '-ig', type=str, required=True)\nparser.add_argument('--samples', '-n', type=int, default=100)\nparser.add_argument('--human_friendly', type=bool, default=False)\n\nargs = parser.parse_args()\n\ntf.reset_default_graph()\nsaver = tf.train.import_meta_graph(args.infer_graph)\ngraph = tf.get_default_graph()\nsess = tf.InteractiveSession()\n\ntry:\n saver.restore(sess, args.checkpoint_name)\n\n # Sample latent vectors\n _z = (np.random.rand(args.samples, 100) * 2.) - 1.\n\n # Generate\n z = graph.get_tensor_by_name('z:0')\n G_z = graph.get_tensor_by_name('G_z:0')[:, :, 0]\n\n start = time.time()\n _G_z = sess.run([G_z], {z: _z})\n print('Finished! (Took {} seconds)'.format(time.time() - start))\n\n os.makedirs(f'infer/{args.checkpoint_name}/', exist_ok=True)\n \n\n for i in range(args.samples):\n if args.human_friendly:\n raw_sample = np.stack([_G_z[0][i], _G_z[0][i], _G_z[0][i], _G_z[0][i]]).flatten()\n audio = librosa.effects.time_stretch(raw_sample, 130 / 120)\n else:\n audio = _G_z[0][i]\n lo.write_wav(f'infer/{args.checkpoint_name}/{i}.wav', audio, 16000, norm=False)\nfinally:\n sess.close()\n\n\n# %%\n","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"630551096","text":"# Binary Tree Level Order Traversal II\n# Given a binary tree, return the bottom-up level order traversal of its nodes' values.\n# (ie, from left to right, level by level from leaf to root).\n\n# For example:\n# Given binary tree [3,9,20,null,null,15,7],\n# 3\n# / \\\n# 9 20\n# / \\\n# 15 7\n# return its bottom-up level order traversal as:\n# [\n# [15,7],\n# [9,20],\n# [3]\n# ]\n# ======================================================================================\n# Algorithm:\n# iterative using queue\n# TC:\n# SC:\n# Description: https://www.youtube.com/watch?v=H2K0CGAjQDc\n# ========================================================================================\nimport collections\n\n\nclass TreeNode:\n\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def __repr__(self):\n \"\"\"Returns a printable representation of object we call it on.\"\"\"\n return \"{}\".format(self.val)\n\n\n# breadth-first-traversal\n# Method-1: iterative using queue\n# Tc: O(n)\n# Sc: O(n)\ndef levelorder_bottom_iter(root):\n\n if not root:\n return []\n\n # res = collections.deque()\n res = []\n q = collections.deque()\n q.append(root)\n\n while q:\n\n size = len(q)\n level = []\n\n while size > 0:\n curr_node = q.popleft()\n\n if curr_node.left:\n q.append(curr_node.left)\n\n if curr_node.right:\n q.append(curr_node.right)\n\n level.append(curr_node.val)\n size -= 1\n\n res.insert(0, level)\n\n return res\n\n\n# breadth-first-traversal\n# Method-1: recursive\n# Tc: O(n)\n# Sc: O(n)\ndef levelorder_bottom_recur(root):\n\n result = []\n\n def dfs(node, level, result):\n if node:\n if level >= len(result):\n result.insert(0, [])\n result[-(level+1)].append(node.val)\n dfs(node.left, level+1, result)\n dfs(node.right, level+1, result)\n\n dfs(root, 0, result)\n return result\n\n\nif __name__ == \"__main__\":\n\n # Tree\n root = [3,9,20,None,None,15,7]\n # 3\n # / \\\n # 9 20\n # / \\\n # 15 7\n # L-1: root\n root = TreeNode(3)\n\n # # L-2\n root.left = TreeNode(9)\n root.right = TreeNode(20)\n\n # # L-3\n root.left.left = None\n root.left.right = None\n root.right.left = TreeNode(15)\n root.right.right = TreeNode(7)\n\n # print(root)\n print(levelorder_bottom_iter(root))\n print(levelorder_bottom_recur(root))\n\n\n\n\n","sub_path":"code/set_20_tree/107_binary_tree_level_order_traversal_II.py","file_name":"107_binary_tree_level_order_traversal_II.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27867719","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 ('MyANSRSource', '0095_auto_20150830_0907'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='task',\n name='taskType',\n field=models.CharField(default=None, max_length=2, verbose_name=b'Task type', choices=[(b'B', b'Revenue'), (b'I', b'Idle'), (b'N', b'Non-Revenue')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"MyANSRSource/migrations/0096_auto_20150910_1956.py","file_name":"0096_auto_20150910_1956.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"606848756","text":"import os\n\ndef CreateDirs(dirs):\n\t'''\n\tInput:\n\tdirs = a list of directories\n\t\t = ['PATH1', 'PATH2', ... 'PATHn']\n\t\n\tOutput:\n\tReturns a '0' for successfully creating and a '-1' for failing\n\n\tDescription:\n\tCreates directories, which could not be found\n\t'''\n\n\ttry:\n\t\t# Go through all directories in the list of directories\n\t\tfor dir_ in dirs:\n\n\t\t\t# if the path does not exist \n\t\t\tif not os.path.exists(dir_):\n\n\t\t\t\t# Make the path\n\t\t\t\tos.makedirs(dir_)\n\n\t\t# Return 0 for successfull creating\n\t\treturn 0\n\n\t# If there is an error\n\texcept Exception as err:\n\n\t\t# Print the error\n\t\tprint(\"Creating directories error: {0}\".format(err))\n\n\t\t# And stop the code!\n\t\texit(-1)\n","sub_path":"utils/dirs.py","file_name":"dirs.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"68382997","text":"#! /usr/bin/env python\n# encoding: utf-8\n# Thomas Nagy, 2008 (ita)\n\nVERSION='0.0.1'\nAPPNAME='simple_tool'\ntop = '.'\nout = 'build'\n\nimport os\nimport TaskGen\nTaskGen.declare_chain(\n\tname = 'dang',\n\taction = '${COPY} ${SRC} ${TGT}',\n\text_in = '.coin',\n\text_out = '.cpp',\n\treentrant = 0\n)\n\ndef configure(conf):\n\tcmd = os.getcwd() + os.sep + \"cp.py\"\n\tconf.env.COPY = cmd\n\n\tenv2 = conf.env.copy()\n\tconf.set_env_name('debug', env2)\n\tconf.setenv('debug')\n\n\tconf.env.COPY = \"echo 'the command to execute is ' %s && %s\" % (cmd, cmd)\n\ndef build(bld):\n\tfoo = TaskGen.task_gen()\n\tfoo.source = \"uh.coin\"\n\t#foo.env = bld.env_of_name(\"default\")\n\tfoo.env = bld.env_of_name(\"debug\")\n\n","sub_path":"demos/simple_scenarios/environments/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"441959495","text":"import requests\nimport json\nimport time \nimport datetime\nfrom insert_poll_to_db import db_inserter\n\nURL = 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql'\nHEADERS = {'Content-Type': 'application/graphql'}\n\nwith open(\"bus_data.json\") as file:\n bus_data = json.load(file)\n \ndef get_realtime_bus_data(route_gtfsId, tries = 5):\n if tries <= 0:\n raise ValueError(\"Tries must be at least 1\")\n data = '''\n {{\n route(id: \"{route_gtfsId}\") {{\n gtfsId\n shortName\n stops {{\n name\n gtfsId\n stoptimesWithoutPatterns {{\n scheduledArrival\n arrivalDelay\n \n \n realtime\n \n serviceDay\n \n \n \n trip {{\n gtfsId\n \n \n directionId\n \n }}\n }}\n }}\n }}\n }}\n '''.format(route_gtfsId=route_gtfsId)\n\n \n i = 0\n while i < tries:\n response = requests.post(url=URL, data=data, headers=HEADERS)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError:\n i += 1\n else:\n break\n content_json = response.json()[\"data\"]\n return content_json\n \n \ndef filter_next_stop_for_busses(content_json):\n ## SHOULD WORK\n final = {}\n route_name = content_json[\"route\"][\"shortName\"]\n route_gtfsId = content_json[\"route\"][\"gtfsId\"]\n for stop in content_json[\"route\"][\"stops\"]:\n stopGtfsId = stop[\"gtfsId\"]\n \n for stoptime in stop[\"stoptimesWithoutPatterns\"]:\n \n # Take only busses that have realtime\n if stoptime[\"realtime\"] and \\\n route_gtfsId in stoptime[\"trip\"][\"gtfsId\"]:\n this_data = {\n \"stopGtfsId\": stopGtfsId,\n \n \"scheduledArrival\": stoptime[\"scheduledArrival\"],\n \"arrivalDelay\": stoptime[\"arrivalDelay\"],\n \"realtime\": stoptime[\"realtime\"],\n \"serviceDay\": stoptime[\"serviceDay\"],\n \"directionId\": stoptime[\"trip\"][\"directionId\"]\n }\n\n \n tripGtfsId = stoptime[\"trip\"][\"gtfsId\"]\n # take only the stops data that has the minimum scheduled arrival\n \n # if no previous, currently nearest is this\n if (tripGtfsId not in final):\n final[tripGtfsId] = this_data\n \n # else if this arrival time is sooner than previous, currently nearest is this\n elif (this_data[\"scheduledArrival\"]\n < final[tripGtfsId][\"scheduledArrival\"]):\n final[tripGtfsId] = this_data\n \n \n return final\n \ndef yield_changed(old, new):\n ## NOT TESTED\n for id, old_data in old.items():\n if id in new and old_data[\"stopGtfsId\"] == new[id][\"stopGtfsId\"]:\n continue\n yield {id: old_data}\n\n \ndef get_realtime_for_all(data: {\"name\": \"id\"}):\n ## SHOULD WORK\n all = {}\n for name, data in data.items():\n route_gtfsId = data.get(\"gtfsId\")\n content_json = get_realtime_bus_data(route_gtfsId)\n next_stops = filter_next_stop_for_busses(content_json)\n all.update(next_stops)\n return all\n\n \ndef seconds_from_midnight():\n return time.time() - time.mktime(datetime.date.today().timetuple())\n \n\ndef update_current(old, new, discard_min = 5):\n \"\"\" Returns tuple(updated, visited_stops)\"\"\"\n \n # discard time is now + n minutes\n discard_time = seconds_from_midnight() + discard_min *60\n print(discard_time)\n updated = old.copy()\n visited_stops = {}\n for id, old_data in old.items():\n # If the next stop is changed and it is later than current next stop\n if id in new and (old_data[\"stopGtfsId\"] != new[id][\"stopGtfsId\"] \n and new[id][\"scheduledArrival\"] > old_data[\"scheduledArrival\"]):\n visited_stops[id] = old_data\n updated[id] = new[id]\n \n # if some bus has been out of radat for discard_min minutes \n elif id not in new and (old_data[\"scheduledArrival\"] + old_data[\"arrivalDelay\"]\n > discard_time):\n visited_stops[id] = old_data\n del updated[id]\n \n for id in new:\n if id not in updated:\n updated[id] = new[id]\n \n return updated, visited_stops\n \n \ndef main():\n inserter = db_inserter()\n print(bus_data.keys())\n # return\n data = bus_data\n previous = get_realtime_for_all(data)\n while True:\n try:\n current = get_realtime_for_all(data)\n previous, visited_stops = update_current(previous, current)\n for id, item in visited_stops.items():\n print(\"# CHANGED: \", id, json.dumps(item, indent=4))\n print(\"next: \", json.dumps(previous.get(id), indent=4))\n inserter.insert_trip(id, item)\n inserter.insert_poll(id, item)\n except Exception as e:\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"loaders/hslviritys.py","file_name":"hslviritys.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"143247784","text":"import pickle\nimport numpy as np\n\nimport classes.data as data\nfrom classes.cost import SoftmaxCrossEntropy\nfrom classes.layer import BatchNorm, LinearLayer, ReLU, Softmax\nfrom classes.network import FeedForward\nfrom classes.schedule import ExponentialSchedule\n\nPICKLE_FILE = \"datasets/MNIST/MNIST.pickle\"\n\n# load dataset\nwith open(PICKLE_FILE, \"rb\") as file:\n dataset = pickle.load(file)\n\n# parameters\nlearning_rate = 1\nbatch_size = 32\nnum_steps = 10000\nenable_schedule = True\nreport_test_accuracy = True\n\n# prep. images for a dense network\ndataset[\"train_data\"] = np.reshape(dataset[\"train_data\"], (-1, 28 * 28)) / 255\ndataset[\"valid_data\"] = np.reshape(dataset[\"valid_data\"], (-1, 28 * 28)) / 255\ndataset[\"test_data\"] = np.reshape(dataset[\"test_data\"], (-1, 28 * 28)) / 255\n\nfeed = data.BatchFeed(dataset[\"train_data\"], dataset[\"train_labels\"], batch_size=batch_size)\n\nlayers = [\n LinearLayer(784, 512, learning_rate),\n BatchNorm(512),\n ReLU(),\n LinearLayer(512, 256, learning_rate),\n BatchNorm(256),\n ReLU(),\n LinearLayer(256, 128, learning_rate),\n BatchNorm(128),\n ReLU(),\n LinearLayer(128, 64, learning_rate),\n BatchNorm(64),\n ReLU(),\n LinearLayer(64, 10, learning_rate),\n Softmax()\n]\n\ncost = SoftmaxCrossEntropy()\n\nnetwork = FeedForward(layers, cost)\n\nprint(\"training a network with {:d} parameters\".format(network.count_parameters()))\n\nschedule = ExponentialSchedule(learning_rate, 100, 0.9)\n\ncosts = []\n\nfor i in range(num_steps):\n\n input_data, labels = feed.get_batch()\n\n forward = network.feed_forward(input_data)\n costs.append(network.compute_cost(forward, labels))\n network.backprop(forward, labels)\n\n if enable_schedule and i != 0 and i % 10 == 0:\n network.update_learning_rate(schedule.get_learning_rate(i))\n\n if i != 0 and i % 1000 == 0:\n print(\"step {:d}\".format(i))\n print(\"cost 100 steps average: {:.6f}\".format(np.mean(costs[len(costs) - 100:])))\n\n forward = network.feed_forward(dataset[\"valid_data\"])\n valid_accuracy = data.one_hot_accuracy(forward, dataset[\"valid_labels\"])\n\n print(\"validation accuracy: {:.2f}%\".format(valid_accuracy * 100))\n print()\n\nif report_test_accuracy:\n forward = network.feed_forward(dataset[\"test_data\"])\n test_accuracy = data.one_hot_accuracy(forward, dataset[\"test_labels\"])\n\n print(\"test accuracy: {:.2f}%\".format(test_accuracy * 100))\n print()","sub_path":"run_MNIST_fully_connected.py","file_name":"run_MNIST_fully_connected.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"510571659","text":"from sklearn import metrics\r\nfrom sklearn.metrics import confusion_matrix\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report\r\nimport seaborn as sn\r\n\r\nstyle.use('seaborn-whitegrid')\r\nplt.rcParams['figure.figsize'] = (16, 7)\r\n\r\ndf = pd.read_csv(\"Rock_data_1.csv\")\r\n\r\nX_var = df[['X', 'Y']].values\r\ny_var = df['id'].values\r\n\r\nX_var = StandardScaler().fit(X_var).transform(X_var.astype(float))\r\n\r\nX_train, X_test, y_train, y_test = \\\r\n train_test_split(X_var, y_var,\r\n test_size=0.3,\r\n random_state=0)\r\n\r\nclf = RandomForestClassifier(n_estimators=100)\r\nclf.fit(X_train, y_train)\r\ny_pred = clf.predict(X_test)\r\n\r\ncm = confusion_matrix(y_var, clf.predict(X_var))\r\nsn.heatmap(cm, annot=True, fmt='g')\r\n\r\nprint('F1 Score:', metrics.f1_score(y_test, y_pred, average='macro'))\r\n\r\nprint('Accuracy: ', metrics.accuracy_score(y_test, y_pred))\r\nprint()\r\n\r\nprint(\"Diagonal: \" + str(cm.diagonal()))\r\nprint(\"Matrix Sum: \" + str(cm.sum(axis=0)))\r\nprint()\r\naccuracy = cm.diagonal() / cm.sum(axis=0)\r\nprint(\"Accuracy: \" + str(accuracy) + '\\n')\r\nprint(classification_report(y_test, y_pred))\r\nprint(\"Precision Score: \", metrics.precision_score(y_test, y_pred, average='macro'))\r\nprint(\"Recall Score: \", metrics.recall_score(y_test, y_pred, average='macro'))\r\nplt.show()\r\n","sub_path":"neighbortest/rawRF.py","file_name":"rawRF.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"630009338","text":"#!/usr/bin/python3\n\"\"\"Usage: randline FILE [COUNT] [FILE2 [COUNT2] ...]\n\nPrints a random line from FILE.\n\nIf a numeric COUNT is given, print COUNT random lines from FILE.\nIf multiple FILEs are given, print random random line(s) from each.\nAll lines in the output are whitespace-trimmed and space-separated.\n\"\"\"\nfrom sys import argv, exit\nfrom random import choice\n\ntry:\n arr = []\n i = 1\n while i < len(argv):\n filename = argv[i]\n if i+1 < len(argv) and argv[i+1].isnumeric():\n count = int(argv[i+1])\n i += 2\n else:\n count = 1\n i += 1\n with open(filename) as f:\n lines = f.readlines()\n for _ in range(count):\n arr.append(choice(lines).strip())\n\n print(\" \".join(arr))\nexcept:\n print(__doc__)\n print()\n\n","sub_path":"scripts/randline.py","file_name":"randline.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"161663549","text":"# Copyright 2021 The SODA Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom delfin import test\nfrom delfin.task_manager.scheduler import scheduler\n\n\nclass TestScheduler(test.TestCase):\n\n def test_scheduler_singleton(self):\n first_instance = scheduler.Scheduler.get_instance()\n self.assertIsInstance(first_instance, BackgroundScheduler)\n\n second_instance = scheduler.Scheduler.get_instance()\n self.assertIsInstance(second_instance, BackgroundScheduler)\n\n self.assertEqual(first_instance, second_instance)\n","sub_path":"delfin/tests/unit/task_manager/scheduler/test_scheduler.py","file_name":"test_scheduler.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"108083493","text":"import argparse\nimport os\nimport zlib\n\nimport tqdm\n\nfrom protgraph.cli import check_if_file_exists\n\n# Optional Dependencies, currently installable via [sqlite]\ntry:\n import apsw\nexcept ImportError:\n print(\"Error: 'apsw' is needed for this script to run properly. Exiting...\")\n exit()\n\n\ndef parse_args():\n \"\"\" Parse Arguments \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Small script to generate fasta files from a generated sqlite database by ProtGraph. \"\n \"Protgraph should be called prior with the flag '-epepfasta'\"\n )\n\n # Base Folder of generated Pickle Files\n parser.add_argument(\n \"sqlite_file\", type=check_if_file_exists, nargs=1,\n help=\"Sqlite database file of exported peptides.\"\n )\n\n # Output fasta file\n parser.add_argument(\n \"--output_file\", \"-o\", type=str, default=\"sqlite_peptides.fasta\",\n help=\"Output fasta file. DEFAULT 'sqlite_peptides.fasta' (NOTE: This file WILL be overwritten)\"\n )\n\n return parser.parse_args()\n\n\ndef export_with_text(conn, output, num_of_entries):\n \"\"\" Export Case for Text columns \"\"\"\n cur = conn.cursor()\n cur.execute(\"SELECT peptide, meta from peptide_meta;\")\n\n pep_id = 0\n for pep, meta in tqdm.tqdm(cur, total=num_of_entries, unit=\"entries\"):\n\n # Write Output-Entry\n output.write(\n \">pg|ID_\" + str(pep_id) + \"|\" + meta + \"\\n\" + '\\n'.join(pep[i:i+60] for i in range(0, len(pep), 60)) + \"\\n\"\n )\n # Increase id\n pep_id += 1\n\n cur.close()\n\n\ndef export_with_blob(conn, output, num_of_entries):\n \"\"\" Export case for BLOB columns (here we read blobs directly) \"\"\"\n\n cur = conn.cursor()\n cur.execute(\"SELECT peptide from peptide_meta;\")\n\n pep_id = 0\n for rowid in tqdm.tqdm(range(1, num_of_entries + 1), total=num_of_entries):\n bl = conn.blobopen(\"main\", \"peptide_meta\", \"meta\", rowid, False)\n binar_meta = bl.read()\n bl.close()\n meta = \"\"\n stream = binar_meta\n while stream:\n dco = zlib.decompressobj()\n meta += \",\" + dco.decompress(stream).decode(\"ascii\")\n stream = dco.unused_data\n meta = meta[1:]\n\n bl = conn.blobopen(\"main\", \"peptide_meta\", \"peptide\", rowid, False)\n binar_pep = bl.read()\n bl.close()\n pep = zlib.decompress(binar_pep).decode(\"ascii\")\n\n # Write Output-Entry\n output.write(\n \">pg|ID_\" + str(pep_id) + \"|\" + meta + \"\\n\" + '\\n'.join(pep[i:i+60] for i in range(0, len(pep), 60)) + \"\\n\"\n )\n # Increase id\n pep_id += 1\n\n\ndef main():\n # Parse args\n args = parse_args()\n abs_file = os.path.abspath(args.sqlite_file[0])\n\n # Get Connection, column and size info\n conn = apsw.Connection(abs_file)\n cur = conn.cursor()\n\n cur.execute(\"PRAGMA table_info(peptide_meta);\")\n results = cur.fetchall()\n\n if results[0][2] == \"TEXT\":\n export_method = export_with_text\n else: # == BLOB\n export_method = export_with_blob\n\n cur.execute(\"SELECT MAX(rowid) from peptide_meta;\")\n num_of_entries = cur.fetchone()[0]\n cur.close()\n\n # Start Export for text\n with open(args.output_file, \"w\") as output_fasta:\n export_method(conn, output_fasta, num_of_entries)\n\n conn.close()\n","sub_path":"protgraph/scripts/pepsqlite_to_fasta.py","file_name":"pepsqlite_to_fasta.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"197281000","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='article',\n options={'ordering': ('-created', 'title'), 'verbose_name': 'Article', 'verbose_name_plural': 'Articles'},\n ),\n migrations.AddField(\n model_name='article',\n name='online',\n field=models.BooleanField(default=False),\n ),\n ]\n","sub_path":"dangamble/apps/blog/migrations/0002_auto_20150914_2125.py","file_name":"0002_auto_20150914_2125.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"116946091","text":"\"\"\"\n this is the script for the kaggle competition: https://www.kaggle.com/c/titanic\n this script has 3 optional parameter which will be the train data filename, test data filename, output filename\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import train_test_split\nimport sys\nimport csv as csv\n\n\n\"\"\"\n this will take in the data in the form of a dataframe object (from pandas)\n and will clean the data by getting rid of un wanted columns and fill empty values\n data is mutable so it will change the original data as well as returning it\n\"\"\"\ndef cleanData(data):\n ## remove unnecessary columns\n ## remove name, ticket fare, PassengerId\n data.drop(\"PassengerId\", axis=1, inplace=True)\n data.drop(\"Name\", axis=1, inplace=True)\n data.drop(\"Ticket\", axis=1, inplace=True)\n data.drop(\"Cabin\", axis=1, inplace=True)\n\n ## convert to numbers\n ## S -> C -> Q\n data[\"Sex\"] = data[\"Sex\"].map({\"female\":0, \"male\":1})\n data[\"Embarked\"] = data[\"Embarked\"].map({\"S\":0, \"C\":1, \"Q\":2})\n\n ## rename column sex\n data.rename(columns = {\"Sex\":\"IsMale\"})\n\n\n ## data imputation for age (~30)\n ageMean = data[\"Age\"].mean()\n data[\"Age\"] = data[\"Age\"].fillna(value = round(ageMean))\n data[\"Embarked\"] = data[\"Embarked\"].fillna(value=0)\n data[\"Fare\"] = data[\"Fare\"].fillna(value = round(data[\"Fare\"].mean()))\n\n return data;\n\n\n\"\"\"\n this function will build the model\n\"\"\"\ndef buildModel():\n ## create the random forest classifier model\n ## random forest works from\n # forest = RandomForestClassifier(max_depth = 20, min_samples_split=2, n_estimators = 100, random_state = 9)\n\n # model = sklearn.linear_model.LogisticRegression(\n # C=1,\n # max_iter=1000,\n # verbose=0,\n # random_state=None,\n # solver='liblinear',\n # tol=0.0001,\n # warm_start=False,\n # intercept_scaling=1,\n # multi_class='ovr'\n # )\n\n model = GaussianNB()\n\n ## return the result of the trained model\n return model\n\n\n\"\"\"\n this function will take in a model and will train the given data on that model, by giving the function a\n target it will print the accuracy of that target\n\"\"\"\ndef trainModel(model, data, target):\n ## run it on the train data\n my_forest = model.fit(data, target)\n return my_forest\n\n\n\"\"\"\n this function will take in a name for the test data file and return the results after predicting\n their survival status\n function will also take in the trained model that is used for predicting\n\"\"\"\ndef runModel(testDataFileName, model):\n ## run on test data\n testData = pd.read_csv(testDataFileName)\n cleanedTestData = cleanData(testData)\n testArray = testData[testData.columns.values].values\n result = model.predict(testArray)\n return result;\n\n\n\"\"\"\n this function will take in a 2d array for the result that has the data of passenger id and a\n boolean value representing if they survived and a string for saveFileName\n\"\"\"\ndef saveResults(result, ids, saveFileName):\n predictions_file = open(saveFileName, \"w\")\n open_file_object = csv.writer(predictions_file)\n\n open_file_object.writerow([\"PassengerId\",\"Survived\"])\n open_file_object.writerows(zip(ids, result))\n\n predictions_file.close()\n\n\n\"\"\"\n this function will take in the trainedModel and the data as a dataframe object and will return a value that shows how accurate this trained data is\n\"\"\"\ndef findAccuracy(trainedModel, data):\n target = data[\"Survived\"].values;\n data = cleanData(data) # clean the data\n\n ## store the target and drop it from the data\n data.drop(\"Survived\", axis=1, inplace=True)\n dataArray = data[data.columns.values].values ## stores the data as a 2d array\n\n ## run the tester\n accuracy = trainedModel.score(dataArray, target)\n return accuracy;\n\n\n\ndef main():\n ## grab the data\n dataFilename = sys.argv[1] if len(sys.argv) > 1 else \"./data/train.csv\"\n data = pd.read_csv(dataFilename)\n\n ## split the data\n data, testData = train_test_split(data, test_size = 0.30)\n\n ## clean the data\n data = cleanData(data);\n\n ## remove the target somewhere else\n target = data[\"Survived\"].values;\n data.drop(\"Survived\", axis=1, inplace=True)\n\n ## build the model\n model = buildModel()\n\n ## normalize the data\n # data = normalizeData(data);\n\n ## train the model\n feature_forest = data[data.columns.values].values\n trainedModel = trainModel(model, feature_forest, target);\n\n\n # run it on the target to check accuracy\n accuracy = findAccuracy(trainedModel, testData);\n print(\"accuracy: \", accuracy)\n\n ## run the model on the test data\n testFileName = sys.argv[2] if len(sys.argv) > 2 else \"./data/test.csv\"\n result = runModel(testFileName, model);\n\n ## save the result in a file\n outputFileName = sys.argv[3] if len(sys.argv) > 3 else \"./data/prediction2.csv\"\n testData = pd.read_csv(testFileName)\n ids = testData[\"PassengerId\"].values;\n saveResults(result, ids, outputFileName)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"546971376","text":"import os\nfrom datetime import datetime\nfrom croniter import croniter\n\nimport query_builder.application.default_settings as default_settings\nfrom query_builder.domain_model.dtos import SimpleQuery\nfrom query_builder.domain_model.adapters import (\n from_model_to_query_dto,\n from_dto_to_step_model\n)\nfrom query_builder.domain_model.services.pubsub_service import publish_uuid_to_clean\nfrom .configuration_service import is_production_environment, get_organization_id\nfrom .scc_service import (\n process_scc_query,\n build_mark_from_id,\n mark_to_query_filed,\n build_temp_mark_from_id\n)\nfrom .pubsub_service import publish_queries_uuid\nfrom .validation_service import (\n validate_runnable_query,\n assert_existing_query,\n validate_save_query\n)\n\nfrom ..models import Query, Step\nfrom ..db import database\n\nLOGGER = default_settings.configure_logger('query_service')\n\nSCC_URL_LINK_TEMPLATE = \"https://console.cloud.google.com/security/{}s?organizationId={}\"\nSCC_URL_LINK_GENERIC_TEMPLATE = \"https://console.cloud.google.com/security/?organizationId={}\"\n\n\ndef run_query_by_uuid(uuid):\n query_model = get_query(uuid)\n assert_existing_query(uuid, query_model)\n dto = from_model_to_query_dto(query_model)\n LOGGER.info(\"run_query_by_uuid - uuid: %s\", uuid)\n return run_query(dto)\n\n\ndef update_last_execution(query, last_execution_query_result, steps_result, execution_date):\n LOGGER.info(\"update_last_execution - uuid: %s, last_execution_query_result: %s\",\n query.uuid, last_execution_query_result\n )\n with database.atomic():\n query_ = (\n Query.update(\n {\n Query.last_execution_result: last_execution_query_result,\n Query.last_execution_date: execution_date,\n Query.last_execution_status: steps_result[len(steps_result)][\"status\"]\n }\n )\n .where(Query.uuid == query.uuid)\n )\n query_.execute()\n update_last_execution_steps(query, steps_result)\n\ndef update_last_execution_steps(query, steps_result):\n for step in query.steps:\n step_ = (\n Step.update({\n Step.last_execution_result: steps_result[step.order][\"responseSize\"],\n Step.last_execution_status: steps_result[step.order][\"status\"]\n }).where(Step.query == step.uuid and Step.order == step.order)\n )\n step_.execute()\n\ndef update_query_notify(uuid, flag):\n query = get_query(uuid)\n assert_existing_query(uuid, query)\n\n query = (Query\n .update({\n Query.send_notification: bool(flag),\n Query.timestamp: __now()\n })\n .where(Query.uuid == query.uuid))\n query.execute()\n\n LOGGER.info('Query with id %s updated notification flag to %s', uuid, flag)\n\n\ndef run_query(query_dto, mode=\"execution\"):\n LOGGER.info(\"run_query - working_marks: %s\", query_dto)\n validate_runnable_query(query_dto)\n\n if mode == \"draft\" or not is_production_environment():\n working_marks = build_temp_mark_from_id(query_dto.uuid)\n else:\n working_marks = build_mark_from_id(query_dto.uuid)\n\n LOGGER.info(working_marks)\n result_size, result_kind, step_results, execution_date = process_scc_query(\n query_dto,\n working_marks,\n mode\n )\n if mode == \"execution\":\n update_last_execution(query_dto, result_size, step_results, execution_date)\n\n LOGGER.info(\"run_query - working_marks: %s\", working_marks)\n return (\n query_dto.uuid,\n result_size,\n build_url(result_kind),\n mark_to_query_filed(working_marks),\n step_results\n )\n\n\ndef clean_up_marks(uuid_to_clean):\n publish_uuid_to_clean(uuid_to_clean)\n\n\ndef save_query(query):\n LOGGER.info(\"save_query - uuid: %s\", query.uuid)\n validate_save_query(query)\n with database.atomic():\n saved_query = Query.create(\n uuid=query.uuid,\n name=query.name,\n description=query.description,\n owner=query.owner,\n topic=query.topic,\n timestamp=__now(),\n schedule=query.schedule,\n next_run=__get_next_query_run(\n schedule=query.schedule, base_datetime=__now()) if query.schedule else None,\n send_notification=query.send_notification,\n last_execution_date=query.last_execution_date,\n last_execution_result=query.last_execution_result,\n last_execution_status=query.last_execution_status,\n )\n saved_query.save()\n steps = []\n for step_dto in query.steps:\n steps.append(from_dto_to_step_model(step_dto, saved_query))\n for step in steps:\n step.save()\n\n return saved_query\n\n\ndef get_query(uuid):\n LOGGER.info(\"get_query - uuid: %s\", uuid)\n return Query.get_or_none(Query.uuid == uuid)\n\n\ndef delete_query(uuid):\n LOGGER.info(\"delete_query - uuid: %s\", uuid)\n with database.atomic():\n Step.delete().where(Step.query_id == uuid).execute()\n Query.delete().where(Query.uuid == uuid).execute()\n\n\ndef update_query(_query):\n LOGGER.info(\"update_query - uuid: %s\", _query.uuid)\n with database.atomic():\n delete_query(_query.uuid)\n save_query(_query)\n\n\ndef list_queries(page=None, page_size=None, text=''):\n LOGGER.info(\"list_queries - page: %s, page_size: %s, text: %s\",\n page, page_size, text)\n queries = get_queries(page, page_size, text)\n simple_queries = []\n total = get_total_queries(text)\n for query in queries:\n mark = build_mark_from_id(query.uuid)\n simple_queries.append(\n SimpleQuery(\n uuid=query.uuid,\n name=query.name,\n timestamp=query.timestamp,\n description=query.description,\n owner=query.owner,\n mark=mark_to_query_filed(mark),\n next_run=query.next_run,\n last_execution_date=query.last_execution_date,\n last_execution_result=query.last_execution_result,\n last_execution_status=query.last_execution_status,\n send_notification=query.send_notification))\n return simple_queries, total\n\n\ndef get_queries(page, page_size, text):\n LOGGER.info(\"get_queries - page: %s, page_size: %s, text: %s\",\n page, page_size, text)\n if(page is not None and page_size is not None):\n return Query.select().paginate(page, page_size).where(\n Query.name.contains(text) | Query.description.contains(text) | Query.owner.contains(text)\n ).order_by(Query.name)\n return __get_queries(text)\n\n\ndef get_total_queries(text):\n LOGGER.info(\"get_total_queries - text: %s\", text)\n return __get_queries(text).count()\n\n\ndef run_scheduled_queries():\n \"\"\"Get the scheduled queries to run and publish their uuid on topic to be executed\"\"\"\n with database.atomic():\n queries_to_run = __get_scheduled_queries()\n if queries_to_run:\n publish_queries_uuid(queries_to_run)\n\n\ndef __get_scheduled_queries():\n exec_datetime = __now()\n LOGGER.info('run_scheduled_queries called at: %s', exec_datetime)\n\n # Get queries scheduled to run now\n queries_to_run = []\n for uuid_schedule in Query.select(\n Query.uuid, Query.schedule).where(Query.next_run <= exec_datetime):\n queries_to_run.append(uuid_schedule.uuid)\n LOGGER.info('Query to run: %s, schedule: %s',\n uuid_schedule.uuid,\n uuid_schedule.schedule)\n # Update the next_run based on schedule cron expression\n query = (Query\n .update({\n Query.next_run: __get_next_query_run(uuid_schedule.schedule,\n exec_datetime)\n })\n .where(Query.uuid == uuid_schedule.uuid))\n query.execute()\n\n return queries_to_run\n\n\ndef __get_queries(text):\n return Query.select().where(\n Query.name.contains(text) | Query.description.contains(text) | Query.owner.contains(text)\n ).order_by(Query.name)\n\n\ndef build_url(kind):\n if kind:\n return SCC_URL_LINK_TEMPLATE.format(\n kind.lower(),\n get_organization_id())\n return SCC_URL_LINK_GENERIC_TEMPLATE.format(get_organization_id())\n\n\ndef __get_next_query_run(schedule, base_datetime):\n return croniter(schedule, base_datetime).get_next(datetime)\n\n\ndef __now():\n return datetime.utcnow()\n","sub_path":"securitycenter/query-builder/back/query_builder/domain_model/services/query_service.py","file_name":"query_service.py","file_ext":"py","file_size_in_byte":8587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"574160864","text":"\"\"\"\nmatplotlib learning\n面向对象的方法绘制多图\n2017.12.12\nauthor:Ezra\nemail:zgahwuqiankun@qq.com\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"\nseed( ) 用于指定随机数生成时所用算法开始的整数值,如果使用相同的seed( )值,\n则每次生成的随即数都相同,如果不设置这个值,则系统根据时间来自己选择这个值,\n此时每次生成的随机数因时间差异而不同。\n\nnumpy中rand和randn区别\nrandn(n)是用于产生均值为0,方差和标准差为1,且正态分布的n*n随机矩阵。\nrand(n)是在[0.0,1.0]区间,产生均匀分布的n*n随机矩阵。\n\"\"\"\nnp.random.seed(1)\ndata = np.random.randn(2,100)\n\nfig,axs = plt.subplots(2,2,figsize=(5,5))#绘制两行两列 figsize是画布的大小\naxs[0,0].hist(data[0]) #直方图 在第一个 也就是第一行第一列\naxs[1,0].scatter(data[0],data[1])#散点图\naxs[0,1].plot(data[0],data[1]) #线\naxs[1,1].hist2d(data[0],data[1]) #双变量直方图\n\nfig.subplots_adjust(hspace = 0.8) #子图的垂直间距\nplt.show()","sub_path":"test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636877430","text":" \r\ndef avgQueuelength(): \r\n f = open(\"length_of_queue.txt\", \"r\")\r\n sum=0\r\n count=0\r\n for x in f:\r\n sum=sum+int(x[:1])\r\n count+=1\r\n avg=sum/count\r\n return avg\r\n\r\ndef avgTime(): \r\n f = open(\"time_spend_by_user.txt\", \"r\")\r\n sum=0\r\n count=0\r\n minTime=99999999999\r\n maxTime=0\r\n for x in f:\r\n sum=sum+int(x)\r\n if(int(x)>maxTime):\r\n \tmaxTime=int(x)\r\n if(int(x)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport logging\nfrom threading import Lock\nfrom tornado.gen import coroutine, Return\nfrom katcp import KATCPClientResource\n\nlog = logging.getLogger('mpikat.worker_pool')\nlock = Lock()\n\n\nclass WorkerAllocationError(Exception):\n pass\n\n\nclass WorkerDeallocationError(Exception):\n pass\n\n\nclass WorkerRequestError(Exception):\n pass\n\nclass WorkerPool(object):\n \"\"\"Wrapper class for managing server\n allocation and deallocation to subarray/products\n \"\"\"\n\n def __init__(self):\n \"\"\"\n @brief Construct a new instance\n \"\"\"\n self._servers = set()\n self._allocated = set()\n\n def make_wrapper(self, hostname, port):\n raise NotImplemented\n\n def add(self, hostname, port):\n \"\"\"\n @brief Add a new FbfWorkerServer to the server pool\n\n @params hostname The hostname for the worker server\n @params port The port number that the worker server serves on\n \"\"\"\n log.debug(\"Adding {}:{} to worker pool\".format(hostname, port))\n wrapper = self.make_wrapper(hostname, port)\n if not wrapper in self._servers:\n wrapper.start()\n log.debug(\"Adding {} to server set\".format(wrapper))\n self._servers.add(wrapper)\n else:\n log.debug(\"Worker instance {} already exists\".format(wrapper))\n log.debug(\"Added {}:{} to worker pool\".format(hostname, port))\n\n def remove(self, hostname, port):\n \"\"\"\n @brief Add a new FbfWorkerServer to the server pool\n\n @params hostname The hostname for the worker server\n @params port The port number that the worker server serves on\n \"\"\"\n log.debug(\"Removing {}:{} from worker pool\".format(hostname, port))\n wrapper = self.make_wrapper(hostname, port)\n if wrapper in self._allocated:\n raise WorkerDeallocationError(\n \"Cannot remove allocated server from pool\")\n try:\n self._servers.remove(wrapper)\n except KeyError:\n log.warning(\n \"Could not find {}:{} in server pool\".format(hostname, port))\n else:\n log.debug(\"Removed {}:{} from worker pool\".format(hostname, port))\n\n def allocate(self, count):\n \"\"\"\n @brief Allocate a number of servers from the pool.\n\n @note Free servers will be allocated by priority order\n with 0 being highest priority\n\n @return A list of FbfWorkerWrapper objects\n \"\"\"\n with lock:\n log.debug(\"Request to allocate {} servers\".format(count))\n available_servers = list(self._servers.difference(self._allocated))\n log.debug(\"{} servers available\".format(len(available_servers)))\n available_servers.sort(\n key=lambda server: server.priority, reverse=True)\n if len(available_servers) < count:\n raise WorkerAllocationError(\"Cannot allocate {0} servers, only {1} available\".format(\n count, len(available_servers)))\n allocated_servers = []\n for _ in range(count):\n server = available_servers.pop()\n log.debug(\"Allocating server: {}\".format(server))\n allocated_servers.append(server)\n self._allocated.add(server)\n return allocated_servers\n\n def deallocate(self, servers):\n \"\"\"\n @brief Deallocate servers and return the to the pool.\n\n @param A list of Node objects\n \"\"\"\n for server in servers:\n log.debug(\"Deallocating server: {}\".format(server))\n self._allocated.remove(server)\n\n def reset(self):\n \"\"\"\n @brief Deallocate all servers\n \"\"\"\n log.debug(\"Reseting server pool allocations\")\n self._allocated = set()\n\n def available(self):\n \"\"\"\n @brief Return list of available servers\n \"\"\"\n return list(self._servers.difference(self._allocated))\n\n def navailable(self):\n return len(self.available())\n\n def used(self):\n \"\"\"\n @brief Return list of allocated servers\n \"\"\"\n return list(self._allocated)\n\n def nused(self):\n return len(self.used())\n\n\nclass WorkerWrapper(object):\n \"\"\"Wrapper around a client to an FbfWorkerServer\n instance.\n \"\"\"\n\n def __init__(self, hostname, port):\n \"\"\"\n @brief Create a new wrapper around a client to a worker server\n\n @params hostname The hostname for the worker server\n @params port The port number that the worker server serves on\n \"\"\"\n log.debug(\n \"Creating worker client to worker at {}:{}\".format(hostname, port))\n self._client = KATCPClientResource(dict(\n name=\"worker-server-client\",\n address=(hostname, port),\n controlled=True))\n self.hostname = hostname\n self.port = port\n self.priority = 0 # Currently no priority mechanism is implemented\n self._started = False\n\n @coroutine\n def get_sensor_value(self, sensor_name):\n \"\"\"\n @brief Retrieve a sensor value from the worker\n \"\"\"\n yield self._client.until_synced()\n response = yield self._client.req.sensor_value(sensor_name)\n if not response.reply.reply_ok():\n raise WorkerRequestError(response.reply.arguments[1])\n raise Return(response.informs[0].arguments[-1])\n\n def start(self):\n \"\"\"\n @brief Start the client to the worker server\n \"\"\"\n log.debug(\"Starting client to worker at {}:{}\".format(\n self.hostname, self.port))\n self._client.start()\n self._started = True\n\n def __repr__(self):\n return \"<{} @ {}:{}>\".format(self.__class__.__name__, self.hostname, self.port)\n\n def __hash__(self):\n # This has override is required to allow these wrappers\n # to be used with set() objects. The implication is that\n # the combination of hostname and port is unique for a\n # worker server\n return hash((self.hostname, self.port))\n\n def __eq__(self, other):\n # Also implemented to help with hashing\n # for sets\n return self.__hash__() == hash(other)\n\n def __del__(self):\n if self._started:\n try:\n self._client.stop()\n except Exception as error:\n log.exception(str(error))\n","sub_path":"mpikat/core/worker_pool.py","file_name":"worker_pool.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"411722020","text":"class LectureDecorator:\n @staticmethod\n def convertLecture(lecture):\n result = {\n 'id': lecture.id,\n 'theme': lecture.theme,\n 'lecture_id': lecture.lecture_id,\n }\n\n if lecture.__dict__.has_key('section_name'):\n result['section_name'] = lecture.section_name\n\n return result","sub_path":"Confercio/frame/decorator/LectureDecorator.py","file_name":"LectureDecorator.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"611903521","text":"# Copy your practical work 2 to 3.student.mark.oop.math.py\n# 1. Use math module to round-down student scores to 1-digit decimal upon input, floor()\n# 2. Use numpy module and its array to\n# 2.1. Add function to calculate average GPA for a given student\n# • Weighted sum of credits and marks\n# 2.2 Sort student list by GPA descending\n# 3. Decorate your UI with curses module\n\n\nimport math\n# import numpy\n\n\nclass domain:\n\n students = []\n studentsDict = []\n gpas = []\n\n\n def findGPA(studentObj):\n GPA = 0\n all_grade_points = 0\n all_credits = 0\n\n for course in studentObj.courses:\n grade_point = course.mark * course.credit\n all_grade_points += grade_point\n all_credits += course.credit\n\n GPA = all_grade_points/all_credits\n studentObj.gpa = GPA\n\n return GPA\n\n\n class Student():\n def __init__(self, Id, name, dob):\n self.name = name\n self.id = Id\n self.dob = dob\n self.courses = []\n self.gpa = None\n\n\n class Course():\n def __init__(self, Id, name, credit, mark):\n self.name = name\n self.id = Id\n self.mark = math.floor(float(mark))\n self.credit = credit\n\n\n\nclass main:\n\n # input user selection\n def selection(self):\n while True:\n firstSl = print(\"1.Student Info\")\n secondSl = print(\"2.Course Info\")\n # thirdSl = print(\"3.Mark Info\")\n fourthSl = print(\"4.Exit\")\n\n mySl = input(\"My Choice: \")\n\n if mySl == \"1\":\n return self.studentInput()\n elif mySl == \"2\":\n return self.courseInput()\n # elif mySl == \"3\":\n # return self.markInput()\n elif mySl == \"4\":\n break\n\n # input student info\n def studentInput(self):\n studentNum = input(\"Enter numbers of student: \")\n for i in range(int(studentNum)):\n studentName = input(\"Enter Student Name:\")\n studentID = input(\"Enter Student ID: \")\n studentDOB = input(\"Student's DOB:\")\n students.append(\n {'student Name': studentName, 'studentID': studentID, 'student DOB': studentDOB})\n print(students)\n\n # input course info\n\n def courseInput(self):\n courseNum = input(\"Enter number of courses: \")\n for j in range(int(courseNum)):\n courseName = input(\"Enter course name:\")\n courseInfo = input(\"ID: \")\n courses.append({'course name': courseName, 'ID': courseInfo})\n print(courses)\n\n # input grade\n\n # def markInput(self):\n # inputID = input(\"enter Student ID: \")\n # inputCourse = input(\"Course: \")\n\n # inputMark = input(\"Mark: \")\n # x = math.floor(float(inputMark))\n\n # marks.append({'ID': inputID, 'Course': inputCourse, 'Mark': x})\n # print(marks)\n\nclass output:\n my_input = Input()\n my_input.selection()\n\n\n stu1 = Student(1, \"kien\", 1)\n crs1 = Course(\"c1\", \"Python\", 3, 11)\n crs2 = Course(\"c2\", \"Signal\", 3, 12)\n crs3 = Course(\"c3\", \"DSA\", 5, 15)\n\n stu1.courses.append(crs1)\n stu1.courses.append(crs2)\n stu1.courses.append(crs3)\n\n\n stu2 = Student(2, \"long\", 1)\n crs4 = Course(\"c1\", \"Python\", 3, 10)\n crs5 = Course(\"c2\", \"Signal\", 3, 10)\n crs6 = Course(\"c3\", \"DSA\", 5, 13)\n\n stu2.courses.append(crs4)\n stu2.courses.append(crs5)\n stu2.courses.append(crs6)\n\n\n students.append(stu1)\n students.append(stu2)\n print(len(students))\n\n\n # find GPA of all students\n for student in students:\n findGPA(student)\n\n # print(students[0].gpa)\n\n # Convert object to dictionary\n for student in students:\n studentsDict.append(vars(student))\n\n print(studentsDict)\n\n # Sort students descendingly\n newStudents = sorted(studentsDict, key=lambda k: k['gpa'], reverse=False)\n\n\n print(newStudents)","sub_path":"3.student.mark.py","file_name":"3.student.mark.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"648391194","text":"from django.shortcuts import render\nfrom .forms import instructForm\n# Create your views here.\ndef instr(request):\n\ttemplate=\"instruct.html\"\n\n\tif request.method == \"POST\":\n\t\tform = instructForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\n\telse:\n\t\tform = instructForm()\n\n\tcontext = {\n\t\t'form' : form ,\n\t}\t\t\t\n\n\treturn render(request, template, context)","sub_path":"instructor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"48164829","text":"from sushi_train_packing_list import STPackingList\nfrom database import Database\nimport os, xlrd, datetime, glob\n\n\ndef convert_excel_date(excel_book, excel_date):\n ms_bbd_date_number = excel_date\n year, month, day, hour, minute, second = xlrd.xldate_as_tuple(ms_bbd_date_number, excel_book.datemode)\n py_date = datetime.datetime(year, month, day, hour, minute, second)\n return py_date\n\n\ndef read_excel_and_insert_to_db():\n #os.chdir(r\"\\\\192.168.20.50\\AlexServer\\SD共有\\ボタニーパレット\\Siwan\\StockFiles\\working_place\")\n os.chdir('/home/siwanpark/ExcelData/')\n excel_files = glob.glob('*.xls*') \n file_number = 1 \n for excel_file in excel_files: \n print('{} - {}'.format(excel_file, file_number))\n generate_data_frame_and_insert_to_db(excel_file) #generate data frame \n file_number += 1\n\n\ndef generate_data_frame_and_insert_to_db(file_path): \n loc = (file_path) \n wb = xlrd.open_workbook(loc) \n sheet = wb.sheet_by_index(0) \n \n #dispatch_date = sheet.cell_value(6, 9) \n #dispatch_date = update_date.strip()\n # Convert excel date to python date \n if sheet.cell(0, 0).ctype == 3 or sheet.cell(0, 0).ctype == 2:\n dispatch_date = convert_excel_date(wb, sheet.cell(0, 0).value).date()\n elif sheet.cell(0, 0).ctype == 1:\n dispatch_date = datetime.datetime.strptime(sheet.cell(0, 0).value, \"%d/%m/%Y\")\n else:\n dispatch_date = sheet.cell(0, 0).value\n \n shipment_info = file_path\n #print(dispatch_date)\n if 'NSW' in shipment_info:\n customer = 'STNSW'\n elif 'SQ' in shipment_info:\n customer = 'STQLD'\n elif 'SA' in shipment_info:\n customer = 'STADL'\n else:\n customer = 'UNKNOWN'\n\n if 'DRY' in shipment_info:\n product_type = 'DRY'\n elif 'FRZ' in shipment_info:\n product_type = 'FRZ'\n else:\n product_type = 'UNKNOWN'\n\n #for i in range(3, sheet.nrows): \n \n i = 3\n while sheet.cell(i, 4).value != 'TOTAL': \n if sheet.cell(i, 1).value != '' and sheet.cell(i, 1).value != '-' and sheet.cell(i, 5).value != '': # when actual data is found\n \n \n st_packing_list = STPackingList(dispatch_date, product_type, customer, sheet.cell(i, 1).value, sheet.cell(i, 0).value, \n sheet.cell(i, 5).value, sheet.cell(i, 6).value, None)\n st_packing_list.save_to_db()\n \n i += 1\n \n\ndef insert_excel_to_db():\n Database.initialise(database=\"sfstock\", user=\"siwan\", password=\"psw1101714\", host=\"localhost\")\n\n read_excel_and_insert_to_db() \n #user_from_db = User.load_from_db_by_email('jose@schoolofcode.me')\n #print(user_from_db)\n\n\nif __name__ == \"__main__\":\n insert_excel_to_db()","sub_path":"WranglingExcelFile/sushi_train/insert_sushi_train_packinglist_old_format.py","file_name":"insert_sushi_train_packinglist_old_format.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"262480454","text":"import random\nimport sys\nimport os\nimport datetime\nfrom timeit import default_timer as timer\n\nfrom query_runner_new import *\n\ncomma = ','\ndef to_str(str):\n return \"'\"+str+\"'\"\n \ndef to_str_list(str):\n strs = str.strip().split(';')\n for i in range(len(strs)):\n strs[i] = to_str(strs[i])\n return \"[\" + comma.join(strs) +\"]\"\n \ndef change_date_format(str):\n str = str.replace('-', '')\n str = str.replace(' ', '')\n str = str.replace(':', '')\n return str + '000'\n \ndef change_birthday_format(str):\n str = str.replace('-', '')\n str = str.replace(' ', '')\n str = str.replace(':', '')\n return str\n \ndef run_bi(name_data, param_path,i):\n #create result folder\n if not os.path.exists(os.path.dirname(\"./result/\")):\n try:\n os.makedirs(os.path.dirname(\"./result/\"))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n runner = Neo4jQueryRunner();\n\n ofile = open(\"result/business_i\" + \"_\" + str(i)+\"_\" + name_data, 'a')\n report = \"\\n---------- \" + str(datetime.datetime.now()) + \" \" + \" ----------\\n\"\n f_name = \"BI_{}.txt\".format(i)\n params_file = open(os.path.join(param_path, f_name), \"r\")\n header = next(params_file)\n params =[]\n for number, line in enumerate(params_file):\n params = line.strip().split('|')\n if i == 1 or i == 12:\n params[0] = change_date_format(params[0]) #date\n elif i == 2:\n params[0] = change_date_format(params[0]) #startDate\n params[1] = change_date_format(params[1]) #endDate\n params[2] = to_str(params[2]) #country1\n params[3] = to_str(params[3]) #country2\n elif i == 4 or i == 9 or i == 22:\n params[0] = to_str(params[0]) #tagClass\n params[1] = to_str(params[1]) #country\n elif i == 5 or i == 6 or i == 7 or i == 8 or i == 13 or i == 15 or i == 17 or i == 23 or i == 24:\n params[0] = to_str(params[0]) #country or tag\n elif i == 10 or i == 21:\n params[0] = to_str(params[0]) #tag\n params[1] = change_date_format(params[1]) #date\n elif i == 11:\n params[0] = to_str(params[0]) #country\n params[1] = to_str_list(params[1]) #blocklist\n elif i == 14:\n params[0] = change_date_format(params[0]) #startDate\n params[1] = change_date_format(params[1]) #endDate\n elif i == 16:\n params[1] = to_str(params[1]) #country\n params[2] = to_str(params[2]) #tagClass\n elif i == 18:\n params[0] = change_date_format(params[0]) #date\n params[2] = to_str_list(params[2]) #languages\n elif i == 19:\n params[0] = change_birthday_format(params[0]) #date\n params[1] = to_str(params[1]) #tagClass1\n params[2] = to_str(params[2]) #tagClass2\n elif i == 20:\n params[0] = to_str_list(params[0]) #tagClassName\n elif i == 25:\n params[2] = change_date_format(params[2]) #startDate\n params[3] = change_date_format(params[3]) #endDate\n \n total_time = 0.0\n for j in range(0,3): # run 3 times for 1 pararmeter\n if i == 1:\n start = timer()\n runner.bi_1(params)\n end = timer()\n elif i == 2:\n start = timer()\n runner.bi_2(params)\n end = timer()\n elif i == 3:\n start = timer()\n runner.bi_3(params)\n end = timer()\n elif i == 4:\n start = timer()\n runner.bi_4(params)\n end = timer()\n elif i == 5:\n start = timer()\n runner.bi_5(params)\n end = timer()\n elif i == 6:\n start = timer()\n runner.bi_6(params)\n end = timer()\n elif i == 7:\n start = timer()\n runner.bi_7(params)\n end = timer()\n elif i == 8:\n start = timer()\n runner.bi_8(params)\n end = timer()\n elif i == 9:\n start = timer()\n runner.bi_9(params)\n end = timer()\n elif i == 10:\n start = timer()\n runner.bi_10(params)\n end = timer()\n elif i == 11:\n start = timer()\n runner.bi_11(params)\n end = timer()\n elif i == 12:\n start = timer()\n runner.bi_12(params)\n end = timer()\n elif i == 13:\n start = timer()\n runner.bi_13(params)\n end = timer()\n elif i == 14:\n start = timer()\n runner.bi_14(params)\n end = timer()\n elif i == 15:\n start = timer()\n runner.bi_15(params)\n end = timer()\n elif i == 16:\n start = timer()\n runner.bi_16(params)\n end = timer()\n elif i == 17:\n start = timer()\n runner.bi_17(params)\n end = timer()\n elif i == 18:\n start = timer()\n runner.bi_18(params)\n end = timer()\n elif i == 19:\n start = timer()\n runner.bi_19(params)\n end = timer()\n elif i == 20:\n start = timer()\n runner.bi_20(params)\n end = timer()\n elif i == 21:\n start = timer()\n runner.bi_21(params)\n end = timer()\n elif i == 22:\n start = timer()\n runner.bi_22(params)\n end = timer()\n elif i == 23:\n start = timer()\n runner.bi_23(params)\n end = timer()\n elif i == 24:\n start = timer()\n runner.bi_24(params)\n end = timer()\n elif i == 25:\n start = timer()\n runner.bi_25(params)\n end = timer()\n exe_time = end - start\n if j != 0: # the first result usually large, exclude it \n total_time += exe_time\n param = '|'.join(params)\n line = str(j)+\": \" +name_data + \", \" + \"bi_\"+str(i)+\", \" + param + \", \" + str(exe_time) + \" seconds\"\n print(line)\n report += line + \"\\n\"\n if j != 0:\n report += \"summary, \" + \"bi_\"+str(i)+\", \" + str(total_time/j) + \" seconds\\n\"\n ofile.write(report)\n ofile.write(\"\\n\")\n print (report)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 4:\n print(\"Usage: python run_bi.py data_name param_path query_index\")\n sys.exit()\n run_bi(os.path.basename(sys.argv[1]), sys.argv[2], int(sys.argv[3]) if len(sys.argv) == 4 else \"\")\n","sub_path":"neo4j/run_bi.py","file_name":"run_bi.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"326350858","text":"import re\nwith open('people.txt', 'r', encoding='utf8') as file:\n data = file.read()\n\n pattern = re.compile(r'\\d{3}-\\d{3}-\\d{4}')\n matches = pattern.finditer(data)\n print(type(matches))\n match_list = []\n for match in matches:\n print(match)\n match_list.append((match.group()))\n\nprint(match_list)\n","sub_path":"022_regular_expressions.py","file_name":"022_regular_expressions.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"416915709","text":"from data.GP_data_sampler import GPCurvesReader\nfrom module.NP import NeuralProcess as NP\nfrom module.utils import compute_loss, comput_kl_loss, to_numpy, load_plot_data\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport numpy as np\nfrom tqdm import tqdm\nimport time\nimport matplotlib.pyplot as plt\nimport os\n\ndef validation(data_test, model, test_batch = 64):\n total_ll = 0\n model.eval()\n for i in range(test_batch):\n data = data_test.generate_curves(include_context=False)\n (x_context, y_context), x_target = data.query\n (mean, var), _, _ = model(x_context.to(device), y_context.to(device), x_target.to(device))\n loss = compute_loss(mean, var, data.y_target.to(device))\n total_ll += -loss.item()\n return total_ll / (i+1)\n\ndef save_plot(epoch, data, model):\n ax, fig = plt.subplots()\n (x_context, y_context), x_target = data.query\n x_grid = torch.arange(-2, 2, 0.01)[None, :, None].repeat([x_context.shape[0], 1, 1]).to(device)\n (mean, var), _, _ = model(x_context.to(device), y_context.to(device), x_grid.to(device))\n # plot scatter:\n plt.scatter(to_numpy(x_context[0]), to_numpy(y_context[0]), label = 'context points', c = 'red', s = 15)\n # plot sampled function:\n plt.scatter(to_numpy(x_target[0]), to_numpy(data.y_target[0]), label = 'target points', marker='x', color = 'k')\n # plot predicted function:\n plt.plot(to_numpy(x_grid[0]), to_numpy(mean[0]), label = '%s predicted mean'%MODELNAME, c = 'blue')\n # mu +/- 1.97* sigma: 97.5% confidence\n plt.fill_between(to_numpy(x_grid[0,:,0]), to_numpy(mean[0,:,0] - 1.97*var[0,:,0]), to_numpy(mean[0, :, 0] + 1.97*var[0, :, 0]), color ='blue', alpha = 0.15)\n plt.legend(loc = 'upper right')\n plt.title(\"epoch:%d\"%epoch)\n plt.ylim(-0.5, 1.7)\n model_path = \"saved_fig/\" + MODELNAME\n kernel_path = os.path.join(model_path, kernel)\n if not os.path.exists(model_path):\n os.mkdir(model_path)\n if not os.path.exists(kernel_path):\n os.mkdir(kernel_path)\n plt.savefig(\"saved_fig/\"+MODELNAME+\"/\"+kernel+\"/\"+\"%04d\"%(epoch//100)+\".png\")\n plt.close()\n return fig\n\nif __name__ == '__main__':\n # define hyper parameters\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n TRAINING_ITERATIONS = int(2e5)\n MAX_CONTEXT_POINT = 50\n VAL_AFTER = 1e3\n BEST_LOSS = -np.inf\n MODELNAME = 'ANP' # 'NP' or 'ANP'\n kernel = 'period' # EQ or period\n # set up tensorboard\n time_stamp = time.strftime(\"%m-%d-%Y_%H:%M:%S\", time.localtime())\n writer = SummaryWriter('runs/'+kernel+'_' + MODELNAME +'_'+ time_stamp)\n # load data set\n dataset = GPCurvesReader(kernel=kernel, batch_size=64, max_num_context= MAX_CONTEXT_POINT, device=device)\n # data for recording training progress\n plot_data = load_plot_data(kernel)\n\n np = NP(input_dim=1, latent_dim = 128, output_dim=1, use_attention=MODELNAME=='ANP').to(device)\n optim = torch.optim.Adam(np.parameters(), lr=3e-4, weight_decay=1e-5)\n\n for epoch in tqdm(range(TRAINING_ITERATIONS)):\n data = dataset.generate_curves()\n (x_context, y_context), x_target = data.query\n (mean, var), prior, poster = np(x_context.to(device), y_context.to(device), x_target.to(device), data.y_target.to(device))\n nll_loss = compute_loss(mean, var, data.y_target.to(device))\n kl_loss = comput_kl_loss(prior, poster)\n loss = nll_loss + kl_loss\n optim.zero_grad()\n loss.backward()\n optim.step()\n writer.add_scalars(\"Log-likelihood\", {\"train/overall\": -loss.item(),\n \"train/ll\": -nll_loss.item(),\n \"train/kl\": kl_loss.item()}, epoch)\n if (epoch % 100 == 0 and epoch BEST_LOSS:\n BEST_LOSS = val_loss\n print(\"save module at epoch: %d, val log-likelihood: %.4f\" %(epoch, val_loss))\n torch.save(np.state_dict(), 'saved_model/'+kernel+'_' + MODELNAME+'.pt')\n writer.close()\n print(\"finished training: \" + MODELNAME)\n\n\n\n","sub_path":"third_party/np_family/NP_or_ANP_train.py","file_name":"NP_or_ANP_train.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95153878","text":"'''\r\n Istream\r\n Oneclickwatch\r\n Copyright (C) 2013 Coolwave\r\n\r\n version 0.1\r\n\r\n'''\r\n\r\n\r\nfrom entertainment.plugnplay import Plugin\r\nfrom entertainment import common\r\n\r\nfrom entertainment.plugnplay.interfaces import TVShowSource\r\nfrom entertainment.plugnplay.interfaces import MovieSource\r\n\r\nclass oneclickwatch(MovieSource, TVShowSource):\r\n implements = [MovieSource, TVShowSource]\r\n\t\r\n #unique name of the source\r\n name = \"oneclickwatch\"\r\n source_enabled_by_default = 'false'\r\n #display name of the source\r\n display_name = \"Oneclickwatch\"\r\n \r\n #base url of the source website\r\n base_url = 'http://oneclickwatch.org/'\r\n \r\n def GetFileHosts(self, url, list, lock, message_queue):\r\n import re\r\n\r\n from entertainment.net import Net\r\n net = Net()\r\n\r\n content = net.http_GET(url).content\r\n r = '.+?
' \r\n match = re.compile(r).findall(content)\r\n\r\n r2 = 'Release Title\\: (.+?)
'\r\n quality = re.compile(r2).findall(content)\r\n \r\n \r\n urlselect = []\r\n\r\n for url in match: \r\n if url not in urlselect:\r\n urlselect.append(url)\r\n res = 'SD'\r\n if re.findall('720', str(quality), re.I):\r\n res = 'HD'\r\n elif re.findall('1080', str(quality), re.I):\r\n res = 'HD'\r\n elif re.findall('CAM', str(quality), re.I):\r\n res = 'CAM'\r\n elif re.findall('BRRIP', str(quality), re.I):\r\n res = 'DVD'\r\n \r\n #if '720p' in quality or '1080p' in quality or 'BRRip' in quality:\r\n #res = 'HD'\r\n #elif 'CAM' in quality:\r\n #res = 'CAM'\r\n #elif 'Cam' in quality:\r\n #res = 'CAM'\r\n \r\n \r\n self.AddFileHost(list, res, url)\r\n\r\n\r\n\r\n def GetFileHostsForContent(self, title, name, year, season, episode, type, list, lock, message_queue):\r\n\r\n import urllib2\r\n import re\r\n from entertainment.net import Net\r\n net = Net()\r\n\r\n search_term = name\r\n category = ''\r\n if type == 'tv_episodes':\r\n category = 'category=4'\r\n elif type == 'movies':\r\n category = 'category=5'\r\n \r\n title = self.CleanTextForSearch(title) \r\n name = self.CleanTextForSearch(name)\r\n\r\n #Movies = http://oneclickwatch.org/?s=Escape+Plan+2013\r\n #TV Shows = http://oneclickwatch.org/?s=warped+roadies+s02E07\r\n\r\n season_pull = \"0%s\"%season if len(season)<2 else season\r\n episode_pull = \"0%s\"%episode if len(episode)<2 else episode\r\n\r\n tv_url='http://oneclickwatch.org/?s=%s+S%s+E%s' %(name.replace(' ','+'),season_pull,episode_pull)\r\n movie_url='http://oneclickwatch.org/?s=%s+%s' %(name.replace(' ','+'),year)\r\n if type == 'movies':#

.+?

\r\n headers = ({'User-Agent': 'Magic Browser'})\r\n link = re.split('Start: Post', net.http_GET(movie_url).content)[0]\r\n url = re.findall(r'

.+?

', str(link), re.DOTALL)\r\n for url in url:\r\n self.GetFileHosts(url, list, lock, message_queue)\r\n \r\n elif type == 'tv_episodes':\r\n headers = ({'User-Agent': 'Magic Browser'})\r\n link = re.split('Start: Post', net.http_GET(tv_url).content)[0]\r\n r = re.findall('s\\d+e', link, re.I)\r\n if r:\r\n url = re.findall(r'

.+?

', str(link), re.I)\r\n for url in url:\r\n self.GetFileHosts(url, list, lock, message_queue)\r\n","sub_path":"USA/script.icechannel.extn.xunitytalk/plugins/tvandmovies/oneclickwatch_mvs_tvs.py","file_name":"oneclickwatch_mvs_tvs.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"251834201","text":"from datetime import datetime\n\nfrom levels.models import Level\nfrom core.endpoint import Endpoint\nfrom core.response import HTTPResponse\n\n\nclass LevelEndpoint(Endpoint):\n\n def create(self, request, *args, **kwargs):\n data = dict(request.data)\n user = request.user\n if not (user.is_admin or user.is_superuser):\n return HTTPResponse({\"Error\": \"Cannot create a Level !! Only admin can create a new level!!\"})\n level = Level()\n level.title = data.get('title', '')\n level.level_no = data.get('level_no', 0)\n level.created_at = datetime.utcnow()\n level.created_by = user.to_dbref() if user.id else None\n level.save()\n response = {\"id\": str(level.id), \"title\": level.title, \"level_no\": level.level_no}\n return HTTPResponse(response)\n\n def update(self, request, level_id=None):\n data = request.data\n user = request.user\n level = Level.safe_get(level_id)\n if not level:\n return HTTPResponse({\"No such level found !\"})\n level.title = data.get('title', level.title)\n level.level_no = data.get('level_no', level.level_no)\n level.updated_at = datetime.utcnow()\n level.updated_by = user.to_dbref() if user.id else None\n level.save()\n return self.retrieve(request, level_id=level_id)\n\n def list(self, request, *args, **kwargs):\n levels = Level.objects.all()\n response = []\n for level in levels:\n response.append({\"id\": str(level.id), \"title\": level.title, \"level_no\": level.level_no})\n return HTTPResponse(response)\n\n def retrieve(self, request, level_id=None):\n level = Level.safe_get(level_id)\n if not level:\n return HTTPResponse({\"No such level found !\"})\n response = {\"id\": str(level.id), \"title\": level.title, \"level_no\": level.level_no}\n return HTTPResponse(response)\n\n def delete(self, request, level_id=None):\n level = Level.safe_get(level_id)\n if not level:\n return HTTPResponse({\"No such level found !\"})\n level.delete()\n return HTTPResponse({})\n","sub_path":"api/endpoints/levels.py","file_name":"levels.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264158742","text":"from datetime import datetime\n\nfrom src.character import Character\nfrom src.item import Weapon\n\n\nclass Profile:\n \"\"\"\n Class representing a Profile. Allows for performing account-level API operations for a player\n \"\"\"\n\n def __init__(self, api):\n self.api = api\n self._active_character = None\n self.last_equip_time = 0\n\n @property\n def active_character(self):\n \"\"\"\n Gets the currently-active character on the account. If all characters are offline, this will\n be the character that was played most recently. This is lazily initialized, so it is only\n evaluated once. If the player changes characters, then the bot will need to be restarted\n \"\"\"\n if self._active_character is None:\n self._active_character = self.get_most_recent_character()\n return self._active_character\n\n @property\n def characters(self):\n \"\"\"\n Get all characters in the account\n \"\"\"\n characters = self.api.make_get_call(\n '/Destiny2/{}/Profile/{}'.format(self.api.membership_type, self.api.membership_id),\n {'components': '200'}\n )['Response']['characters']['data']\n return [Character(self.api, x, self) for x in characters.values()]\n\n def get_most_recent_character(self):\n \"\"\"\n Returns the character that was played most recently. If currently playing, then that means\n the active character will be returned\n \"\"\"\n most_recent_character = None\n most_recent_playtime = None\n current_datetime = datetime.utcnow()\n\n # Figure out which character has the most recent playtime\n for character in self.characters:\n\n if most_recent_character is None:\n most_recent_character = character\n most_recent_playtime = character.last_played\n else:\n # If the character in question has more recent playtime than the other characters\n # already inspected, then set as the new most recent character\n if (current_datetime - character.last_played).total_seconds() < \\\n (current_datetime - most_recent_playtime).total_seconds():\n most_recent_character = character\n most_recent_playtime = character.last_played\n\n return most_recent_character\n\n def get_vault_weapons(self):\n \"\"\"\n Get all weapons in the vault\n \"\"\"\n items = self.api.make_get_call(\n '/Destiny2/{}/Profile/{}'.format(self.api.membership_type, self.api.membership_id),\n {'components': '102'}\n )['Response']['profileInventory']['data']['items']\n return [\n Weapon(x, self.api.manifest) for x in items\n if self.api.manifest.item_data[x['itemHash']]['itemType'] == 3\n ]\n\n def get_all_weapons(self):\n \"\"\"\n Get all weapons, across all characters and the vault. Does not include postmaster weapons\n or currently equipped weapons\n \"\"\"\n all_weapons = self.get_vault_weapons()\n\n for character in self.characters:\n unequipped = character.unequipped_weapons\n all_weapons += unequipped\n\n return all_weapons\n\n def get_weapon_owner(self, weapon):\n \"\"\"\n Return the character currently in possession of a specified weapon. If no character has it,\n then return None\n \"\"\"\n if weapon in self.get_vault_weapons():\n return None\n\n for character in self.characters:\n for char_weapon in character.equipped_weapons:\n if char_weapon == weapon:\n return character\n for char_weapon in character.unequipped_weapons:\n if char_weapon == weapon:\n return character\n\n return None # No character has this weapon\n","sub_path":"src/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188264045","text":"from django.db import models\n\n# Create your models here.\nclass Team(models.Model):\n name = models.CharField(\n max_length=30,\n verbose_name=\"队名\"\n )\n def __str__(self):\n return self.name\n\nclass Player(models.Model):\n name = models.CharField(\n max_length=30,\n verbose_name=\"名字\"\n )\n age = models.IntegerField(\n verbose_name=\"年纪\"\n )\n is_live = models.BooleanField(\n verbose_name=\"是否现役\"\n )\n team = models.ForeignKey(\n Team,\n null=True,\n verbose_name=\"归属球队\"\n )\n def __str__(self):\n return self.name","sub_path":"Django/day03/t03/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"607312120","text":"import pandas as pd\nimport numpy as np\nfrom osmread import parse_file, Node\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport csv\nimport os\n\n\nhousing_df = pd.read_csv('./data/out/datall.csv')\n\ndef decode_node_to_csv():\n # Dictionary with geo-locations of each address to use as strings\n for entry in parse_file('./data/denmark-latest.osm'):\n if (isinstance(entry, Node) and \n 'addr:street' in entry.tags and \n 'addr:postcode' in entry.tags and \n 'addr:housenumber' in entry.tags):\n\n yield entry\n\ndef add_geolocations(decoded_node):\n \n progress_bar = tqdm()\n for file in os.listdir('./data/'):\n for idx, decoded_node in enumerate(decode_node_to_csv()):\n try: \n full_address = decoded_node.tags['addr:street'] + \" \" + decoded_node.tags['addr:housenumber'] + \" \" + decoded_node.tags['addr:postcode'] + \" \" + decoded_node.tags['addr:city']\n addr_with_geo = (full_address,decoded_node.lon,decoded_node.lat)\n \n with open('decoded_nodes.csv', 'a', encoding='utf-8') as f:\n output_writer = csv.writer(f)\n output_writer.writerow(addr_with_geo)\n \n progress_bar.update()\n\n except (KeyError, ValueError):\n pass\n\n\n# Convert all sales dates in the dataset into proper datetime objects\ndef sales_dates_to_datetime():\n # Pandas.to_datetime(arg)\n df = pd.DataFrame['sale_date_str'] = pd.to_datetime(pd.DataFrame['sale_date_str'])\n df.to_csv('datetime.csv')\n\n\ndef scatter_plot_from_dataframe(dataframe):\n plot = dataframe.plot(kind='scatter', x='lon', y='lat')\n plot.get_figure().savefig('scatterplot1.png')\n\n\ndef generate_scatter_plot(datetime_dataframe):\n scatter_plot_from_dataframe(datetime_dataframe) \n\n\ndef run():\n # add_geolocations(decode_node_to_csv())\n # Write DataFrame to csv\n # to_csv(path)\n\n datetime_dataframe = pd.read_csv('decoded_nodes.csv')\n generate_scatter_plot(datetime_dataframe)\n\n\nrun()","sub_path":"BI - Plotting/Example 3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"199334188","text":"# -*- coding: utf-8 -*-\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nimport random\nimport cv2\nIMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']\n\n\ndef pil_loader(path, rgb=True):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n img = Image.open(f)\n if rgb:\n return img.convert('RGB')\n else:\n return img.convert('I')\ndef fdm_loader(path):\n img = Image.open(path)\n img = np.array(img).astype(np.float32)\n h = img.shape[0]\n w = img.shape[1]\n mask = np.zeros((h,w),dtype=np.float32)\n if \"tmap\" in path:\n ratio = 255.0\n img = 255.0 - img\n elif \"flow\" in path:\n ratio = 255.0\n mask = np.where(img>0.0,1.0,0.0)\n else:\n ratio = 200.0\n img = img * 1.0 / ratio\n return img,mask\n\ndef readPathFiles(file_path, root_dir):\n im_gt_paths = []\n\n with open(file_path, 'r') as f:\n lines = f.readlines()\n\n for line in lines:\n if '&' in line:\n im_path = os.path.join(root_dir, line.split('&')[0])\n if '\\n' in os.path.join(root_dir, line.split('&')[1]):\n gt_path = os.path.join(root_dir, line.split('&')[1])[:-1]\n else:\n gt_path = os.path.join(root_dir, line.split('&')[1])\n else:\n if '\\n' in os.path.join(root_dir, line):\n im_path = os.path.join(root_dir, line)[:-1]\n else:\n im_path = os.path.join(root_dir, line)\n gt_path = '&'\n im_gt_paths.append((im_path, gt_path))\n return im_gt_paths\n\n# array to tensor\nfrom dataloaders import transforms as my_transforms\nto_tensor = my_transforms.ToTensor()\n\nclass KittiFolder(Dataset):\n\n def __init__(self, root_dir='',\n mode='train', loader=pil_loader, gtloader = fdm_loader,\n size=(256, 512)):\n super(KittiFolder, self).__init__()\n self.root_dir = root_dir\n\n self.mode = mode\n self.im_gt_paths = None\n self.loader = loader\n self.gtloader = gtloader\n self.size = size\n\n if self.mode == 'train':\n self.im_gt_paths = readPathFiles('/share2/public/fail_safe/kitti/DeepBlur/tool/filenames/output_train.txt', root_dir)\n\n elif self.mode == 'test':\n self.im_gt_paths = readPathFiles('/share2/public/fail_safe/kitti/DeepBlur/tool/filenames/output_test.txt', root_dir)\n\n else:\n print('no mode named as ', mode)\n exit(-1)\n\n def __len__(self):\n return len(self.im_gt_paths)\n\n def train_transform(self, im, gt, mask):\n im = np.array(im).astype(np.float32)\n im = cv2.resize(im,(512,256),interpolation=cv2.INTER_AREA)\n gt = cv2.resize(gt,(512,256),interpolation=cv2.INTER_AREA)\n mask = cv2.resize(mask,(512,256),interpolation=cv2.INTER_AREA)\n # h,w,c = im.shape\n # th, tw = 256,512\n # x1 = random.randint(0, w - tw)\n # y1 = random.randint(0, h - th)\n # img = im[y1:y1 + th, x1:x1 + tw, :]\n # gt = gt[y1:y1 + th, x1:x1 + tw]\n # mask = mask[y1:y1 + th, x1:x1 + tw]\n s = np.random.uniform(1.0, 1.5) # random scaling\n angle = np.random.uniform(-5.0, 5.0) # random rotation degrees\n do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip\n color_jitter = my_transforms.ColorJitter(0.4, 0.4, 0.4)\n\n transform = my_transforms.Compose([\n my_transforms.Rotate(angle),\n my_transforms.Resize(s),\n my_transforms.CenterCrop(self.size),\n my_transforms.HorizontalFlip(do_flip)\n ])\n\n im_ = transform(im)\n im_ = color_jitter(im_)\n\n gt_ = transform(gt)\n mask_ = transform(mask)\n im_ = np.array(im_).astype(np.float32)\n gt_ = np.array(gt_).astype(np.float32)\n mask_ = np.array(mask_).astype(np.float32) \n\n im_ /= 255.0\n gt_ /= s\n im_ = to_tensor(im_)\n gt_ = to_tensor(gt_)\n mask_ = to_tensor(mask_)\n \n gt_ = gt_.unsqueeze(0)\n mask_ = mask_.unsqueeze(0)\n \n return im_, gt_, mask_\n\n def val_transform(self, im, gt,mask):\n im = np.array(im).astype(np.float32)\n h,w,c = im.shape\n im = cv2.resize(im,(512,256),interpolation=cv2.INTER_AREA)\n gt = cv2.resize(gt,(512,256),interpolation=cv2.INTER_AREA)\n mask = cv2.resize(mask,(512,256),interpolation=cv2.INTER_AREA)\n \n transform = my_transforms.Compose([\n # my_transforms.Crop(130, 10, 240, 1200),\n # my_transforms.Resize(460 / 240, interpolation='bilinear'),\n # my_transforms.CenterCrop(self.size)\n ])\n\n im_ = transform(im)\n gt_ = transform(gt)\n mask_ = transform(mask)\n im_ = np.array(im_).astype(np.float32)\n gt_ = np.array(gt_).astype(np.float32)\n mask_ = np.array(mask_).astype(np.float32)\n im_ /= 255.0\n im_ = to_tensor(im_).numpy()\n gt_ = to_tensor(gt_)\n mask_ = to_tensor(mask_)\n gt_ = gt_.unsqueeze(0).numpy()\n mask_ = mask_.unsqueeze(0).numpy()\n # im_ = np.reshape(im_,[1,3,im.shape[0],im.shape[1]])\n # gt_ = np.reshape(gt_,[1,1,im.shape[0],im.shape[1]])\n # mask_=np.reshape(mask_,[1,1,im.shape[0],im.shape[1]])\n im_ = np.reshape(im_,[1,3,256,512])\n gt_ = np.reshape(gt_,[1,1,256,512])\n mask_=np.reshape(mask_,[1,1,256,512])\n # if w>1100:\n # top_pad = 384-im.shape[0]\n # left_pad = 1248-im.shape[1]\n # else:\n # top_pad = 384-im.shape[0]\n # left_pad = 624-im.shape[1]\n\n # im_ = np.lib.pad(im_,((0,0),(0,0),(top_pad,0),(0,left_pad)),mode='constant',constant_values=0)\n # gt_ = np.lib.pad(gt_,((0,0),(0,0),(top_pad,0),(0,left_pad)),mode='constant',constant_values=0)\n # mask_ = np.lib.pad(mask_,((0,0),(0,0),(top_pad,0),(0,left_pad)),mode='constant',constant_values=0)\n return im_, gt_, mask_\n\n def __getitem__(self, idx):\n im_path, gt_path = self.im_gt_paths[idx]\n im = self.loader(im_path)\n h,w,c = np.array(im).shape\n gt = np.zeros((h,w),dtype = np.float32)\n label = -1\n if '&' in gt_path:\n mask = np.zeros((h,w),dtype=np.float32)\n else:\n gt,mask = self.gtloader(gt_path)\n if \"tmap\" in gt_path:\n label = 0\n elif \"flow\" in gt_path:\n label = 1\n else:\n label = 2\n\n if self.mode == 'train':\n im, gt, mask = self.train_transform(im, gt,mask)\n\n else:\n im, gt, mask = self.val_transform(im, gt,mask)\n\n return im, gt, label, mask\n\nif __name__ == '__main__':\n paths = readPathFiles('/share2/public/fail_safe/kitti/DeepBlur/tool/filenames/output_test.txt','')\n for i in range(len(paths)):\n im_path, gt_path = paths[i]\n temp1 = pil_loader(im_path, rgb=True)\n if '&' in gt_path:\n pass\n else:\n temp2 = fdm_loader(gt_path)\n","sub_path":"Network/dataloaders/kitti_dataloader.py","file_name":"kitti_dataloader.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"103352234","text":"\"\"\"visualization.py\n\nThe BBoxVisualization class implements drawing of nice looking\nbounding boxes based on object detection results.\n\"\"\"\n\n\nfrom pickle import TRUE\nimport numpy as np\nimport cv2\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\n\n\n# Constants\nALPHA = 0.5\nFONT = cv2.FONT_HERSHEY_PLAIN\nTEXT_SCALE = 1.0\nTEXT_THICKNESS = 1\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n\ndef gen_colors(num_colors):\n \"\"\"Generate different colors.\n\n # Arguments\n num_colors: total number of colors/classes.\n\n # Output\n bgrs: a list of (B, G, R) tuples which correspond to each of\n the colors/classes.\n \"\"\"\n import random\n import colorsys\n\n hsvs = [[float(x) / num_colors, 1., 0.7] for x in range(num_colors)]\n random.seed(1234)\n random.shuffle(hsvs)\n rgbs = list(map(lambda x: list(colorsys.hsv_to_rgb(*x)), hsvs))\n bgrs = [(int(rgb[2] * 255), int(rgb[1] * 255), int(rgb[0] * 255))\n for rgb in rgbs]\n return bgrs\n\n\ndef draw_boxed_text(img, text, topleft, color):\n \"\"\"Draw a transluent boxed text in white, overlayed on top of a\n colored patch surrounded by a black border. FONT, TEXT_SCALE,\n TEXT_THICKNESS and ALPHA values are constants (fixed) as defined\n on top.\n\n # Arguments\n img: the input image as a numpy array.\n text: the text to be drawn.\n topleft: XY coordinate of the topleft corner of the boxed text.\n color: color of the patch, i.e. background of the text.\n\n # Output\n img: note the original image is modified inplace.\n \"\"\"\n assert img.dtype == np.uint8 \n img_h, img_w, _ = img.shape\n if topleft[0] >= img_w or topleft[1] >= img_h:\n return img\n margin = 3\n size = cv2.getTextSize(text, FONT, TEXT_SCALE, TEXT_THICKNESS)\n w = size[0][0] + margin * 2\n h = size[0][1] + margin * 2\n # the patch is used to draw boxed text\n patch = np.zeros((h, w, 3), dtype=np.uint8)\n patch[...] = color\n cv2.putText(patch, text, (margin+1, h-margin-2), FONT, TEXT_SCALE,\n WHITE, thickness=TEXT_THICKNESS, lineType=cv2.LINE_8)\n cv2.rectangle(patch, (0, 0), (w-1, h-1), BLACK, thickness=1)\n w = min(w, img_w - topleft[0]) # clip overlay at image boundary\n h = min(h, img_h - topleft[1])\n # Overlay the boxed text onto region of interest (roi) in img\n roi = img[topleft[1]:topleft[1]+h, topleft[0]:topleft[0]+w, :]\n cv2.addWeighted(patch[0:h, 0:w, :], ALPHA, roi, 1 - ALPHA, 0, roi)\n return img\n\ndef draw_polygon(img, points, zone_color):\n poly_mask = img.copy()\n alpha_mask = 0.3\n cv2.fillPoly(poly_mask, [points], color=zone_color)\n img = cv2.addWeighted(poly_mask, alpha_mask, img, 1 - alpha_mask, 0)\n cv2.polylines(img, [points], isClosed=True, color=zone_color, thickness=2)\n return img\n\ndef validate_detection(polygon, centroid):\n point = Point(centroid)\n return polygon.contains(point)\n\n\nclass BBoxVisualization():\n \"\"\"BBoxVisualization class implements nice drawing of boudning boxes.\n\n # Arguments\n cls_dict: a dictionary used to translate class id to its name.\n \"\"\"\n\n def __init__(self, cls_dict, d_zone):\n self.cls_dict = cls_dict\n self.colors = gen_colors(len(cls_dict))\n self.d_zone = np.array(d_zone, np.int32)\n self.polygon = Polygon(self.d_zone)\n\n def draw_bboxes(self, img, boxes, confs, clss, draw_zone, detect):\n \"\"\"Draw detected bounding boxes on the original image.\"\"\"\n validation, is_valid = False, False\n valid_list = []\n zone_color = (226, 43, 138)\n \n for bb, cf, cl in zip(boxes, confs, clss):\n cl = int(cl)\n x_min, y_min, x_max, y_max = bb[0], bb[1], bb[2], bb[3]\n color = self.colors[cl]\n cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, 2)\n txt_loc = (max(x_min+2, 0), max(y_min+2, 0))\n cls_name = self.cls_dict.get(cl, 'CLS{}'.format(cl))\n txt = '{} {:.2f}'.format(cls_name, cf)\n img = draw_boxed_text(img, txt, txt_loc, color)\n # car class\n if detect and cl == 1:\n centroid = (int(x_min+x_max)//2, int(y_min+y_max)//2)\n cv2.circle(img, centroid, radius=5, color=color, thickness=-1)\n validation = validate_detection(self.polygon, centroid)\n valid_list.append(validation)\n # license plate class\n elif detect and cl == 0:\n valid_list.append(False)\n \n if detect:\n is_valid = any(valid_list) == True\n if is_valid: zone_color = (0, 255, 0)\n\n if draw_zone:\n img = draw_polygon(img, self.d_zone, zone_color)\n\n return img, is_valid, valid_list\n","sub_path":"utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245804929","text":"#\r\n# @lc app=leetcode.cn id=609 lang=python3\r\n#\r\n# [609] 在系统中查找重复文件\r\n#\r\n# https://leetcode-cn.com/problems/find-duplicate-file-in-system/description/\r\n#\r\n# algorithms\r\n# Medium (54.11%)\r\n# Likes: 19\r\n# Dislikes: 0\r\n# Total Accepted: 1.3K\r\n# Total Submissions: 2.5K\r\n# Testcase Example: '[\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]'\r\n#\r\n#\r\n# 给定一个目录信息列表,包括目录路径,以及该目录中的所有包含内容的文件,您需要找到文件系统中的所有重复文件组的路径。一组重复的文件至少包括二个具有完全相同内容的文件。\r\n#\r\n# 输入列表中的单个目录信息字符串的格式如下:\r\n#\r\n# \"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ...\r\n# fn.txt(fn_content)\"\r\n#\r\n# 这意味着有 n 个文件(f1.txt, f2.txt ... fn.txt 的内容分别是 f1_content, f2_content ...\r\n# fn_content)在目录 root/d1/d2/.../dm 下。注意:n>=1 且 m>=0。如果 m=0,则表示该目录是根目录。\r\n#\r\n# 该输出是重复文件路径组的列表。对于每个组,它包含具有相同内容的文件的所有文件路径。文件路径是具有下列格式的字符串:\r\n#\r\n# \"directory_path/file_name.txt\"\r\n#\r\n# 示例 1:\r\n#\r\n# 输入:\r\n# [\"root/a 1.txt(abcd) 2.txt(efgh)\", \"root/c 3.txt(abcd)\", \"root/c/d\r\n# 4.txt(efgh)\", \"root 4.txt(efgh)\"]\r\n# 输出:\r\n#\r\n# [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\r\n#\r\n#\r\n#\r\n#\r\n# 注:\r\n#\r\n#\r\n# 最终输出不需要顺序。\r\n# 您可以假设目录名、文件名和文件内容只有字母和数字,并且文件内容的长度在 [1,50] 的范围内。\r\n# 给定的文件数量在 [1,20000] 个范围内。\r\n# 您可以假设在同一目录中没有任何文件或目录共享相同的名称。\r\n# 您可以假设每个给定的目录信息代表一个唯一的目录。目录路径和文件信息用一个空格分隔。\r\n#\r\n#\r\n#\r\n#\r\n# 超越竞赛的后续行动:\r\n#\r\n#\r\n# 假设您有一个真正的文件系统,您将如何搜索文件?广度搜索还是宽度搜索?\r\n# 如果文件内容非常大(GB级别),您将如何修改您的解决方案?\r\n# 如果每次只能读取 1 kb 的文件,您将如何修改解决方案?\r\n# 修改后的解决方案的时间复杂度是多少?其中最耗时的部分和消耗内存的部分是什么?如何优化?\r\n# 如何确保您发现的重复文件不是误报?\r\n#\r\n#\r\n#\r\n\r\n# @lc code=start\r\ntry:\r\n from collections import defaultdict\r\n from typing import *\r\n MOD = 10**9 + 7\r\n import os\r\n import sys\r\n curFileParentPath = os.path.dirname(\r\n os.path.dirname(os.path.realpath(__file__)))\r\n sys.path.append(curFileParentPath)\r\n from Utils.Tree import *\r\nexcept Exception as err:\r\n print('Import failed: ' + str(err))\r\n\r\n\r\nclass Solution:\r\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\r\n # 使用一个dict存储content到path的映射\r\n # Follow up:\r\n # 1. 假设您有一个真正的文件系统,您将如何搜索文件?广度搜索还是宽度搜索?\r\n # 广度搜索. 虽然会用更多的内存, 但是广度搜索会受益于文件的局部性, 所以可能会快一些\r\n # 2. 如果文件内容非常大(GB级别),您将如何修改您的解决方案?\r\n # 用md5值+文件大小等标识来唯一标记文件, 作为key. 可以先用文件大小作为key初筛一遍, 然后相同大小的用md5再筛一遍, 如果hash值也相同的话再完全比较实际文件(按字节)\r\n # 3. 如果每次只能读取 1 kb 的文件,您将如何修改解决方案?\r\n # 并不需要改变, 还是先比较size, 然后hash这1KB的文件, 将相同hash值的再每次读取1KB进行完全比较\r\n # 4. 修改后的解决方案的时间复杂度是多少?其中最耗时的部分和消耗内存的部分是什么?如何优化?\r\n # O((n^2)*k), n是文件数目, k是文件大小, 因为最差情况会对每两个文件的全部内容进行比较\r\n # 最耗时的部分是完全比较文件内容\r\n # 最消耗内存的部分是将文件hash成md5\r\n # 优化的话是采用多次筛选的方法, 以及选用更优的hash算法, 以节省时间和空间\r\n # 5. 如何确保您发现的重复文件不是误报?\r\n # 使用多种筛选方法来判断, 最终的完全比较保证了一定不会误报\r\n d = defaultdict(list)\r\n\r\n def combinePath(folder, file):\r\n return folder + '/' + file\r\n\r\n for p in paths:\r\n ls = p.split(' ')\r\n folder = ls[0]\r\n for path in ls[1:]:\r\n file = path[0:path.find('(')]\r\n content = path[path.find('(') + 1:path.find(')')]\r\n d[content].append(combinePath(folder, file))\r\n res = []\r\n for k in d:\r\n if len(d[k]) > 1:\r\n res.append(d[k])\r\n return res\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Solution().findDuplicate([\r\n \"root/a 1.txt(abcd) 2.txt(efgh)\", \"root/c 3.txt(abcd)\",\r\n \"root/c/d 4.txt(efgh)\", \"root 4.txt(efgh)\"\r\n ]))\r\n\r\n# @lc code=end\r\n","sub_path":"Medium/609.在系统中查找重复文件.py","file_name":"609.在系统中查找重复文件.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389479699","text":"import pickle\nclass Src_vob(object):\n def __init__(self):\n self.word2idx={}\n self.idx2word={}\n self.idx=0\n def add_word(self,word):\n if word not in self.word2idx:\n self.word2idx[word]=self.idx\n self.idx2word[self.idx]=word\n self.idx+=1\n def __call__(self,word):\n if word not in self.word2idx:\n return self.word2idx['']\n return self.word2idx[word]\n \n def __len__(self):\n return len(self.word2idx)\n\nclass Tag_vob(object):\n def __init__(self):\n self.word2idx={}\n self.idx2word={}\n self.idx=0\n def add_word(self,word):\n if word not in self.word2idx:\n self.word2idx[word]=self.idx\n self.idx2word[self.idx]=word\n self.idx+=1\n def __call__(self,word):\n if word not in self.word2idx:\n return self.word2idx['']\n return self.word2idx[word]\n \n def __len__(self):\n return len(self.word2idx)\n\n\nsrc_vob=Src_vob()\nsrc_vob.add_word('')\nsrc_vob.add_word('')\nsrc_vob.add_word('')\nsrc_vob.add_word('')\n\n\ntag_vob=Tag_vob()\ntag_vob.add_word('')\ntag_vob.add_word('')\ntag_vob.add_word('')\ntag_vob.add_word('')\n\ndef read_tagfile(filename):\n with open(filename,\"r\") as f:\n for line in f:\n words=line.strip().split()\n for word in words:\n tag_vob.add_word(word)\n\ndef read_srcfile(filename):\n with open(filename,\"r\") as f:\n for line in f:\n words=line.strip().split()\n for word in words:\n src_vob.add_word(word)\n\nread_srcfile(\"./data/train.ja\")\nread_tagfile(\"./data/train.en\")\nprint(len(src_vob))\nprint(len(tag_vob))\nprint(tag_vob.idx2word[1])\n#for k,v in tag_vob.word2idx.items():\n# print(k,v)\nwith open('src_vob.pkl','wb') as f:\n pickle.dump(src_vob,f,pickle.HIGHEST_PROTOCOL)\nwith open('tag_vob.pkl','wb') as f:\n pickle.dump(tag_vob,f,pickle.HIGHEST_PROTOCOL)\n","sub_path":"machine translation attention/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"417557943","text":"\nfrom math import sqrt\n\ndef Length(ls1, ls2):\n \"\"\"Function to calculate the lenght\"\"\"\n length = float(sqrt(float(pow((ls2[1]-ls1[1]),2)) +float(pow((ls2[0]-ls1[0]),2))))\n print(\"The length is:\",length)\n \nif __name__ == \"__main__\":\n point_1 = input(\"Enter the Co-ordinates of 1st point:\")\n\n point_1 = [float(i) for i in point_1.split(',')]\n\n point_2 = input(\"Enter the Co-ordinates of 2nd point:\")\n\n point_2 = [float(i) for i in point_2.split(',')]\n\n print(\"\\n\",point_1 )\n print(\"\\n\",point_2 )\n\n Length(point_1,point_2)","sub_path":"Functional_programming/Distance_between_2pts.py","file_name":"Distance_between_2pts.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"521441641","text":"# -*- coding: utf-8 -*-\n\nclass StatusCodes:\n def __init__(self):\n\n self.Sifirlandi = \"TYYP 0: Paralar Sifirlandi\" # 0\n self.ParayiVer = \"TYYP 24: Parayi Ver\" # 24 şubat 2014 için kod 24\n self.BunlarMontajDublaj = \"TYYP 203: Bunlar Montaj, Bunlar Dublaj\" # 203\n self.KonuCarpitildi = \"TYYP 301: Konu Carpitildi\" # 301\n self.ProxyTespitEdildi = \"TYYP 305: VPN ya da Proxy Tespit Edildi. O da yasak\" # 305\n self.FethullahTehlikesi = \"TYYP 400: Fethullah Gulen Girisimi Tespit Edildi\" # 400\n self.KabulEdilemez = \"TYYP 406: Bu kabul edilemez alcakca bir komplo\" # 406\n self.AdaletKaybedidi = \"TYYP 408: Mahkeme zaman asimindan davayi dusurdu\" # 408\n self.OtekiMedya = \"TYYP 415: Desteklenmeyen medya turu\" # 415\n self.MAQ = \"TYYP 417: Milletin a.. koyuldu\" # 417\n self.PartiIciDeprem = \"TYYP 500: Parti Icinde Deprem Var\" # 500\n self.HizmetHareketiYasaklandi = \"TYYP 503: Hizmet hareketi tamamen yasaklandi\" # 503\n self.HukumetDustu = \"TYYP 504: Hukumet Dustu\" # 504\n self.SeriHukukYasaklari = \"TYYP 1299: Yapmaya Calistiniz Eylem Ser-i Hukuka Gore Yasak\" # 1299\n self.TamamBabacigim = \"TYYP 1453: Tamam Babacigim\" # 1453\n self.Bulamadik = \"TYYP 1461: Bahane Bulunamadi\" # 1461\n self.IstifaDepremi = \"TYYP 2013: Bakanlar Istifa Etti\" # 2013 (bakanların istifası)\n self.BilalAnlamadi = \"TYYP Cagrisi Anlasilamadi. Bilal Tarayiciyi Kapatti\"\n\n def status(self, status_code):\n if status_code == 0:\n print(self.Sifirlandi)\n elif status_code == 24:\n print(self.ParayiVer)\n elif status_code == 203:\n print(self.BunlarMontajDublaj)\n elif status_code == 301:\n print(self.KonuCarpitildi)\n elif status_code == 305:\n print(self.ProxyTespitEdildi)\n elif status_code == 400:\n print(self.FethullahTehlikesi)\n elif status_code == 406:\n print(self.KabulEdilemez)\n elif status_code == 408:\n print(self.AdaletKaybedidi)\n elif status_code == 415:\n print(self.OtekiMedya)\n elif status_code == 417:\n print(self.MAQ)\n elif status_code == 500:\n print(self.PartiIciDeprem)\n elif status_code == 503:\n print(self.HizmetHareketiYasaklandi)\n elif status_code == 504:\n print(self.HukumetDustu)\n elif status_code == 1299:\n print(self.SeriHukukYasaklari)\n elif status_code == 1453:\n print(self.TamamBabacigim)\n elif status_code == 1461:\n print(self.Bulamadik)\n elif status_code == 2013:\n print(self.IstifaDepremi)\n else:\n print(self.BilalAnlamadi)","sub_path":"StatusCodes.py","file_name":"StatusCodes.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"517571961","text":"__author__ = 'jjw'\n\nfrom distutils.core import setup\n\nsetup(\n name='MaxHeap',\n version='0.1.0',\n author='Joel Wright',\n author_email='joel.wright@gmail.com',\n packages=['max_heap', 'max_heap.test'],\n scripts=[],\n #url='http://pypi.python.org/pypi/MaxHeap/',\n license='LICENSE.txt',\n description='MaxHeap is a class based implementation of Leftist Max Heaps.',\n long_description=open('README.txt').read(),\n #install_requires=[],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"349939689","text":"class Environment(object):\n\n chargebee_domain = None\n\n def __init__(self, options):\n self.api_key = options['api_key']\n self.site = options['site']\n\n if self.chargebee_domain is None:\n self.api_endpoint = 'https://%s.chargebee.com/api/v1' % self.site\n else:\n self.api_endpoint = 'http://%s.%s/api/v1' % (self.site, self.chargebee_domain)\n\n def api_url(self, url):\n return self.api_endpoint + url\n","sub_path":"chargebee/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432564022","text":"import os\nimport sys\n\nfrom avalon import api, io\nfrom avalon.vendor import Qt\nfrom pype import lib\nimport pyblish.api\n\n\ndef check_inventory():\n if not lib.any_outdated():\n return\n\n host = api.registered_host()\n outdated_containers = []\n for container in host.ls():\n representation = container['representation']\n representation_doc = io.find_one(\n {\n \"_id\": io.ObjectId(representation),\n \"type\": \"representation\"\n },\n projection={\"parent\": True}\n )\n if representation_doc and not lib.is_latest(representation_doc):\n outdated_containers.append(container)\n\n # Warn about outdated containers.\n print(\"Starting new QApplication..\")\n app = Qt.QtWidgets.QApplication(sys.argv)\n\n message_box = Qt.QtWidgets.QMessageBox()\n message_box.setIcon(Qt.QtWidgets.QMessageBox.Warning)\n msg = \"There are outdated containers in the scene.\"\n message_box.setText(msg)\n message_box.exec_()\n\n # Garbage collect QApplication.\n del app\n\n\ndef application_launch():\n check_inventory()\n\n\ndef install():\n print(\"Installing Pype config...\")\n\n plugins_directory = os.path.join(\n os.path.dirname(os.path.dirname(os.path.dirname(__file__))),\n \"plugins\",\n \"photoshop\"\n )\n\n pyblish.api.register_plugin_path(\n os.path.join(plugins_directory, \"publish\")\n )\n api.register_plugin_path(\n api.Loader, os.path.join(plugins_directory, \"load\")\n )\n api.register_plugin_path(\n api.Creator, os.path.join(plugins_directory, \"create\")\n )\n\n pyblish.api.register_callback(\n \"instanceToggled\", on_pyblish_instance_toggled\n )\n\n api.on(\"application.launched\", application_launch)\n\n\ndef on_pyblish_instance_toggled(instance, old_value, new_value):\n \"\"\"Toggle layer visibility on instance toggles.\"\"\"\n instance[0].Visible = new_value\n","sub_path":"pype/hosts/photoshop/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"1171912","text":"# program that calculates compound interest\n\nprincipal = float(input(\"What is the principal amount? \"))\ninterest_rate = float(input(\"What is the interest rate? \"))\ntime_invested = float(input(\"How many years will this be invested? \"))\ncompound_time = float(input(\"How many times will the interest be compounded per year? \"))\n\naccrued_moola = principal*(1 + (interest_rate/compound_time)**(time_invested*compound_time))\naccrued_moola = round(accrued_moola, 2)\n\nprint(\"$\" + (\"%.2f\" % principal), \"invested at\", str(interest_rate) + \"%\", \"for\", \t\ttime_invested,\"years compounded\", int(compound_time), \"times per year will be worth...\" + \"$\" + str(accrued_moola))\n","sub_path":"13/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"351644957","text":"total = 0\r\ncount = 0\r\nwhile True:\r\n try:\r\n num = int(input('enter number: '))\r\n again = input('another number (Y/N)?\\n ')\r\n total = total + num\r\n count += 1\r\n if again == 'y' or again == 'Y':\r\n continue\r\n elif again == 'n' or again == 'N':\r\n break\r\n else:\r\n print('That means No!')\r\n break\r\n except ValueError:\r\n print('Invalid command!')\r\nprint('you entered number', count, 'times')\r\nprint('and have total value', total)\r\n\r\n\r\n","sub_path":"5.9.1.py","file_name":"5.9.1.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487215527","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\n# with open('HISTORY.rst') as history_file:\n# history = history_file.read()\n\nrequirements = [\n 'jsonschema==2.5.1',\n 'requests==2.9.1',\n 'isodate==0.5.4',\n 'pymongo==3.2'\n]\n\ntest_requirements = [\n 'bumpversion==0.5.3',\n 'wheel==0.24.0',\n 'flake8==2.4.1',\n 'tox==2.1.1',\n 'coverage==4.0',\n 'cryptography==1.0.1',\n 'PyYAML==3.11',\n]\n\nsetup(\n name='sd-python-wrapper',\n version='0.1.13',\n description=\"A python wrapper for the Server Density Api\",\n long_description=readme + '\\n\\n', # + history,\n author=\"Jonathan Sundqvist\",\n author_email='hello@serverdensity.com',\n url='https://github.com/serverdensity/sd-python-wrapper',\n packages=[\n 'serverdensity',\n 'serverdensity.wrapper',\n 'response',\n 'schema'\n ],\n package_dir={\n 'response': 'serverdensity',\n 'schema': 'serverdensity'\n },\n package_data={\n 'schema': ['wrapper/schema/*.json'],\n 'response': ['response.py']\n },\n include_package_data=True,\n install_requires=requirements,\n license=\"MIT\",\n zip_safe=False,\n keywords='monitoring,serverdensity',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n test_suite='tests',\n tests_require=test_requirements\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"567427404","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def countNodes(self, root):\n \"\"\"\n Only beats 1%\n \"\"\"\n if root is None:\n return 0\n longest = 0\n node = root\n while node:\n longest += 1\n node = node.left\n\n global count\n count = 0\n\n def helper(root, length):\n global count\n if root is None:\n return False\n if length == longest:\n count += 1\n return True\n if root.left is None and root.right is None:\n return False\n return helper(root.left, length + 1) and helper(root.right, length + 1)\n helper(root, 1)\n return pow(2, longest - 1) + count - 1\n\n def countNodes_2(self, root):\n \"\"\"\n Beats 73%.\n No 'global'\n \"\"\"\n def height(node):\n c = 0\n while node:\n c += 1\n node = node.left\n return c\n\n def count(node, lh):\n if node is None:\n return 0\n rh = height(node.right)\n if lh == rh:\n return (1 << lh) + count(node.right, rh - 1)\n else:\n val = (1 << rh) + count(node.left, lh - 1)\n return val\n\n return count(root, height(root) - 1)\n","sub_path":"count_complete_tree_nodes.py","file_name":"count_complete_tree_nodes.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530128611","text":"import sys\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport numpy as np\nfrom sklearn import metrics\n\n\nfrom model.pytorch import cnn\nfrom util import conf_utils\nfrom util import data_utils\nfrom util import batch_utils\nfrom util import output_utils\n\n\ndef train(config_path):\n config = conf_utils.init_train_config(config_path)\n\n batch_size = config[\"batch_size\"]\n epoch_size = config[\"epoch_size\"]\n model_class = config[\"model_class\"]\n print(f\"\\n>> model class is {model_class}\")\n\n train_input, train_target, validate_input, validate_target = data_utils.gen_train_data(config)\n\n model = cnn.Model(config)\n\n # 判断是否有GPU加速\n use_gpu = torch.cuda.is_available()\n\n if use_gpu:\n model = model.cuda()\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=config[\"learning_rate\"])\n\n for epoch in range(epoch_size):\n epoch = epoch + 1\n train_batch_gen = batch_utils.make_batch(train_input, train_target, batch_size)\n\n train_acc = 0\n for batch_num in range(len(train_input) // batch_size):\n train_input_batch, train_target_batch = train_batch_gen.__next__()\n\n if model_class == \"conv2d\":\n train_input_batch_v = Variable(torch.LongTensor(np.expand_dims(train_input_batch, 1)))\n elif model_class == \"conv1d\":\n train_input_batch_v = Variable(torch.LongTensor(train_input_batch))\n else:\n raise ValueError(\"model class is wrong!\")\n train_target_batch_v = Variable(torch.LongTensor(np.argmax(train_target_batch, 1)))\n\n if use_gpu:\n train_input_batch_v = train_input_batch_v.cuda()\n train_target_batch_v = train_target_batch_v.cuda()\n\n # 向前传播\n out = model(train_input_batch_v, model_class)\n loss = criterion(out, train_target_batch_v)\n _, pred = torch.max(out, 1)\n train_acc = (pred == train_target_batch_v).float().mean()\n\n # 向后传播\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if not batch_num % 5:\n print(f\">> e:{epoch:3} s:{batch_num:2} loss:{loss:5.4} acc: {train_acc:3f}\")\n\n if epoch > 10 and train_acc >= 0.9:\n torch.save({\n \"epoch\": epoch,\n \"optimizer\": optimizer.state_dict(),\n \"model\": model.state_dict(),\n \"train_acc\": train_acc\n }, config[\"model_path\"]+\"cnn.pt\")\n\n\ndef test(config_path):\n config = conf_utils.init_test_config(config_path)\n\n batch_size = config[\"batch_size\"]\n test_data, test_target = data_utils.gen_test_data(config)\n\n model = cnn.Model(config)\n\n use_gpu = torch.cuda.is_available()\n if use_gpu:\n model = model.cuda()\n\n model.load_state_dict(torch.load(config[\"model_path\"]+\"cnn.pt\", map_location=torch.device('cpu'))[\"model\"])\n\n test_batch_gen = batch_utils.make_batch(test_data, test_target, batch_size)\n\n pred_list = []\n target_list = []\n for batch_num in range(len(test_data) // batch_size):\n test_input_batch, test_target_batch = test_batch_gen.__next__()\n\n test_input_batch_v = Variable(torch.LongTensor(np.expand_dims(test_input_batch, 1)))\n\n if use_gpu:\n test_input_batch_v = test_input_batch_v.cuda()\n\n # 向前传播\n out = model(test_input_batch_v)\n _, pred = torch.max(out, 1)\n pred_list.extend(pred)\n target_list.extend(test_target_batch)\n\n report = metrics.classification_report(target_list, pred_list)\n print(f\"\\n>> REPORT:\\n{report}\")\n output_utils.save_metrics(config, \"report.txt\", report)\n\n cm = metrics.confusion_matrix(target_list, pred_list)\n print(f\"\\n>> Confusion Matrix:\\n{cm}\")\n output_utils.save_metrics(config, \"confusion_matrix.txt\", str(cm))\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) == 1:\n config_data_path = \"./config/pytorch-cnn.yaml\"\n train(config_data_path)\n elif len(args) == 3:\n if args[1] == \"train\":\n train(args[2])\n elif args[1] == \"test\":\n test(args[2])\n else:\n raise ValueError(\"The first parameter is wrong, only support train or test!\")\n else:\n raise ValueError(\"Incorrent parameter length!\")\n","sub_path":"run/pytorch_cnn.py","file_name":"pytorch_cnn.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"474532395","text":"import os, shutil;\nfrom math import floor;\nfrom tqdm import tqdm;\nfrom PIL import Image;\n\n#Meta Start\n\n#Paths start\ndataset_img_dir = \"/home/pyct/DATA/Datasets/kaggle_retinopathy/train\";\ntraining_set_dir = \"/home/pyct/DATA/Datasets/kaggle_retinopathy/training\";\nvalidation_set_dir = \"/home/pyct/DATA/Datasets/kaggle_retinopathy/validation\";\ndataset_labels_path = \"/home/pyct/DATA/Datasets/kaggle_retinopathy/labels.csv\";\n#Paths end\n\n\n#Model/Data parameters start\nnumber_of_classes = 5;\nclasses = {\n 0: \"0_No_DR\",\n 1: \"1_Mild_DR\",\n 2: \"2_Moderate_DR\",\n 3: \"3_Severe_DR\",\n 4: \"4_Proliferative_DR\"\n};\n\n\ninput_shape = (299, 299, 3);\n#input_shape = (600, 600, 3);\npretrained_input_shape = (299, 299, 3);\nconvolution_core = (2, 2);\n#Model/Data parameters end\n\n#--------------------------------------------------------------------------------------------------------------------------------------\n\ndef prepare_dir_structure(training_set_dir = training_set_dir,\\\n validation_set_dir = validation_set_dir):\n \n if (not os.path.exists(validation_set_dir)):\n os.mkdir(validation_set_dir);\n \n if (not os.path.exists(training_set_dir)):\n os.mkdir(training_set_dir);\n \n for key in classes:\n \n if (not os.path.exists(training_set_dir + \"/\" + classes[key])):\n os.mkdir(training_set_dir + \"/\" + classes[key])\n \n if (not os.path.exists(validation_set_dir + \"/\" + classes[key])):\n os.mkdir(validation_set_dir + \"/\" + classes[key])\n \n return True;\n\ndef prepare_sets(sets_split = 0.8, labels_path = dataset_labels_path, source_img_dir = dataset_img_dir,\\\n training_set_dir = training_set_dir, validation_set_dir = validation_set_dir):\n \n labels_file = open(labels_path, \"r\");\n labels = labels_file.readlines();\n labels_file.close();\n\n training_set_size = floor(len(labels) * sets_split);\n\n i = 1;\n\n target_dir = training_set_dir;\n\n for label in tqdm(labels):\n\n item = label.strip().split(\",\");\n\n if (i > training_set_size) and (target_dir == training_set_dir):\n target_dir = validation_set_dir;\n\n source_img_path = \"{}/{}.jpeg\".format(source_img_dir, item[0]);\n destination_img_path = \"{}/{}/{}.jpeg\".format(target_dir, classes[int(item[1])], item[0]);\n\n the_image = Image.open(source_img_path);\n resized_image = the_image.resize((input_shape[0], input_shape[1]), Image.LANCZOS);\n resized_image.save(destination_img_path);\n #shutil.copy(source_img, destination_img);\n\n i += 1;\n\n return True;\n\ndef main():\n\n prepare_dir_structure();\n prepare_sets();\n\nif __name__ == \"__main__\":\n main();","sub_path":"retina_kaggle/src/prepare_datasets.py","file_name":"prepare_datasets.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"370770612","text":"import unittest\n\nfrom scipy import constants\nfrom cavag.misc import *\n\nclass Test_Position(unittest.TestCase):\n\n def test_constructor(self):\n p = Position(position=1)\n self.assertEqual(p.position, 1)\n p.change_params(position=10)\n self.assertEqual(p.position, 10)\n p.change_params(a=1)\n self.assertEqual(p.property_set, {'position': 10})\n \n def test_inheritance_1(self):\n class A(Position):\n modifiable_properties = ('a', 'position')\n def __init__(self, a, position):\n super().__init__(position=position)\n self.property_set.add_required('a')\n self.property_set['a'] = a\n \n @property\n def a(self):\n return self.property_set.get_strictly('a')\n \n a = A(1, 2)\n self.assertEqual(a.a, 1)\n self.assertEqual(a.position, 2)\n\n a.change_params(a=4, position=10)\n self.assertEqual(a.a, 4)\n self.assertEqual(a.property_set, {'a':4, 'position':10})\n\n def test_inheritance_2(self):\n class A(Position):\n modifiable_properties = ('a', )\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self.property_set.add_required('a')\n self.property_set['a'] = kwargs.get('a', None)\n \n @property\n def a(self):\n return self.property_set.get_strictly('a')\n \n a = A(a=1, position=2)\n self.assertEqual(a.a, 1)\n self.assertEqual(a.position, 2)\n\n a.change_params(a=4, position=10)\n self.assertEqual(a.a, 4)\n self.assertEqual(a.property_set, {'a':4, 'position':2})\n\n\nclass Test_Wavelength(unittest.TestCase):\n\n def test_constructor(self):\n w = Wavelength(wavelength=1550)\n self.assertEqual(w.wavelength, 1550)\n w.change_params(wavelength=980)\n self.assertEqual(w.wavelength, 980)\n self.assertEqual(w.k, 2*constants.pi/980)\n \n def test_inheritance(self):\n class A(Wavelength):\n modifiable_properties = ('a', 'wavelength')\n def __init__(self, a, wavelength):\n super().__init__(wavelength=wavelength)\n self.property_set.add_required('a')\n self.property_set['a'] = a\n \n @property\n def a(self):\n return self.property_set.get_strictly('a')\n \n a = A(1, 2)\n self.assertEqual(a.a, 1)\n self.assertEqual(a.wavelength, 2)\n\n a.change_params(a=4, wavelength=10)\n self.assertEqual(a.a, 4)\n self.assertEqual(a.property_set, {'a':4, 'wavelength':10})\n self.assertEqual(a.k, 2*constants.pi/10)\n self.assertEqual(a.property_set, {'a':4, 'wavelength':10, 'k':2*constants.pi/10})\n a.change_params(a=1)\n self.assertEqual(a.property_set, {'a':1, 'wavelength':10})\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"126185289","text":"# Copyright 2019 IBM Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport lale.datasets.data_schemas\nimport lale.operators\nimport numpy as np\nimport pandas as pd\n\nclass KeepNonNumbersImpl:\n def __init__(self):\n pass\n\n def fit(self, X, y=None):\n s_all = lale.datasets.data_schemas.to_schema(X)\n s_row = s_all['items']\n n_columns = s_row['minItems']\n assert n_columns == s_row['maxItems']\n s_cols = s_row['items']\n def is_numeric(schema):\n return 'type' in schema and schema['type'] in ['number', 'integer']\n if isinstance(s_cols, dict):\n if is_numeric(s_cols):\n self._keep_cols = []\n else:\n self._keep_cols = [*range(n_columns)]\n else:\n assert isinstance(s_cols, list)\n self._keep_cols = [i for i in range(n_columns)\n if not is_numeric(s_cols[i])]\n return self\n\n def transform(self, X, y=None):\n if isinstance(X, np.ndarray):\n result = X[:, self._keep_cols]\n elif isinstance(X, pd.DataFrame):\n result = X.iloc[:, self._keep_cols]\n else:\n assert False, f'case for type {type(X)} value {X} not implemented'\n s_X = lale.datasets.data_schemas.to_schema(X)\n s_result = self.transform_schema(s_X)\n return lale.datasets.data_schemas.add_schema(result, s_result)\n\n def transform_schema(self, s_X):\n s_row = s_X['items']\n s_cols = s_row['items']\n n_columns = len(self._keep_cols)\n if isinstance(s_cols, dict):\n s_cols_result = s_cols\n else:\n s_cols_result = [s_cols[i] for i in self._keep_cols]\n s_result = {\n **s_X,\n 'items': {\n **s_row,\n 'minItems': n_columns, 'maxItems': n_columns,\n 'items': s_cols_result}}\n return s_result\n\n_hyperparams_schema = {\n 'description': 'Hyperparameter schema for KeepNonNumbers transformer.',\n 'allOf': [\n { 'description':\n 'This first sub-object lists all constructor arguments with their '\n 'types, one at a time, omitting cross-argument constraints.',\n 'type': 'object',\n 'additionalProperties': False,\n 'relevantToOptimizer': [],\n 'properties': {}}]}\n\n_input_fit_schema = {\n 'description': 'Input data schema for training KeepNonNumbers.',\n 'type': 'object',\n 'required': ['X'],\n 'additionalProperties': False,\n 'properties': {\n 'X': {\n 'description': 'Features; the outer array is over samples.',\n 'type': 'array',\n 'items': {\n 'type': 'array',\n 'items': {\n 'anyOf':[{'type': 'number'}, {'type':'string'}]}}},\n 'y': {\n 'description': 'Target class labels; the array is over samples.'}}}\n\n_input_predict_schema = {\n 'description': 'Input data schema for transformation using KeepNonNumbers.',\n 'type': 'object',\n 'required': ['X'],\n 'additionalProperties': False,\n 'properties': {\n 'X': {\n 'description': 'Features; the outer array is over samples.',\n 'type': 'array',\n 'items': {\n 'type': 'array',\n 'items': {\n 'anyOf':[{'type': 'number'}, {'type':'string'}]}}}}}\n\n_output_schema = {\n 'description': 'Output data schema for transformed data using KeepNonNumbers.',\n 'type': 'array',\n 'items': {\n 'type': 'array',\n 'items': {\n 'anyOf':[{'type': 'number'}, {'type':'string'}]}}}\n\n_combined_schemas = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'Combined schema for expected data and hyperparameters.',\n 'documentation_url': 'https://github.ibm.com/aimodels/lale',\n 'type': 'object',\n 'tags': {\n 'pre': ['categoricals'],\n 'op': ['transformer'],\n 'post': []},\n 'properties': {\n 'hyperparams': _hyperparams_schema,\n 'input_fit': _input_fit_schema,\n 'input_predict': _input_predict_schema,\n 'output': _output_schema }}\n\nif (__name__ == '__main__'):\n lale.helpers.validate_is_schema(_combined_schemas)\n\nKeepNonNumbers = lale.operators.make_operator(KeepNonNumbersImpl, _combined_schemas)\n","sub_path":"lale/lib/lale/keep_non_numbers.py","file_name":"keep_non_numbers.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"476803874","text":"import string\nimport random\nimport os\nimport base64\nimport re\n\nfrom io import BytesIO\nfrom PIL import Image\n\nfrom django import forms\nfrom django.utils.translation import ugettext as _\n\nfrom glamazer.core.helpers import get_object_or_None\nfrom glamazer.listings.models import Listing, Tags, ListingTags\nfrom glamazer.settings import MEDIA_ROOT, DURATION\n\n\nclass EditListing(forms.Form):\n\n title = forms.CharField(required=True, widget=forms.TextInput())\n description = forms.CharField(required=True, widget=forms.TextInput())\n price = forms.CharField(required=True, widget=forms.NumberInput())\n tags = forms.CharField(required=True, widget=forms.TextInput(attrs={\"class\": \"listing_edit\", \"value\": \" \", \"data-option\": \"LONDON\"}))\n duration = forms.ChoiceField(widget=forms.Select(), choices=DURATION)\n cover = forms.CharField(required=False, widget=forms.HiddenInput(), initial=0)\n gender = forms.ChoiceField(widget=forms.RadioSelect(), choices=((0, 'Male'), (2, 'Female')))\n deleted = forms.CharField(required=False, widget=forms.HiddenInput())\n\n class Meta:\n model = Listing\n\n def clean_price(self):\n data = self.cleaned_data\n price = data['price']\n if not (len(price) in range(5) and price.isdigit()):\n raise forms.ValidationError(_('Please enter a valid price.'))\n\n return price\n\n def save(self, listing, FILES):\n data = self.cleaned_data\n pictures = FILES.getlist('files')\n hash_name = ''.join(random.choice(string.ascii_lowercase + string.digits)for x in range(6))\n\n my_dir = MEDIA_ROOT + listing.picture[7:]\n\n deletes_files = data['deleted']\n if deletes_files:\n deletes_files = data['deleted'].split(',')[:-1]\n for d in deletes_files:\n os.remove(d)\n\n os.chdir(my_dir)\n\n cover = data[\"cover\"]\n\n artist_id = str(listing.artist_id)\n\n for index, picture in enumerate(pictures):\n dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')\n my_file = dataUrlPattern.match(picture).group(2)\n\n hash_name = ''.join(random.choice(string.ascii_lowercase + string.digits)for x in range(6))\n\n if cover.isdigit() and index == int(cover):\n full_path = MEDIA_ROOT + 'artists/' + artist_id + '/listings/' + listing.metadata + '/' + hash_name + '.jpeg'\n cover = full_path\n else:\n full_path = MEDIA_ROOT + 'artists/' + artist_id + '/listings/' + listing.metadata + '/' + hash_name + '.jpeg'\n\n #if the folder doesn't exist, create on\n d = os.path.dirname(full_path)\n if not os.path.exists(d):\n os.makedirs(d)\n\n im = Image.open(BytesIO(base64.b64decode(my_file.encode('ascii'))))\n im.save(full_path, 'JPEG')\n\n ListingTags.objects.filter(listing=listing).delete()\n tags = data['tags'].split(',')\n for tag in tags:\n tag = tag.lower()\n current_tag = get_object_or_None(Tags, tag=tag)\n if not current_tag:\n current_tag = Tags.objects.create(tag=tag)\n\n ListingTags.objects.create(listing=listing, tags=current_tag)\n\n if cover:\n listing.picture_cover = cover\n listing.title = data['title']\n listing.description = data['description']\n listing.price = data['price']\n listing.duration = int(data['duration'])\n listing.gender = int(data['gender'])\n listing.save()\n\n return listing\n","sub_path":"glamazer/listings/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"3466352","text":"#\n# Copyright (c) 2013-2015 QuarksLab.\n# This file is part of IRMA 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 in the top-level directory\n# of this distribution and at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# No part of the project, including this file, may be copied,\n# modified, propagated, or distributed except according to the\n# terms contained in the LICENSE file.\n\nimport config.parser as config\nfrom lib.irma.database.nosqlobjects import NoSQLDatabaseObject\nfrom frontend.helpers.format import IrmaFormatter\n\ncfg_dburi = config.get_db_uri()\ncfg_dbname = config.frontend_config['mongodb'].dbname\n\n\ncfg_coll_prefix = '{0}_'.format(config.get_nosql_db_collections_prefix())\n\n\nclass ProbeRealResult(NoSQLDatabaseObject):\n _uri = cfg_dburi\n _dbname = cfg_dbname\n _collection = '{0}probe_real_result'.format(cfg_coll_prefix)\n\n def __init__(self,\n name=None,\n type=None,\n version=None,\n status=None,\n duration=None,\n results=None,\n dbname=None,\n **kwargs):\n if dbname:\n self._dbname = dbname\n self.name = name\n self.type = type\n self.version = version\n self.status = status\n self.duration = duration\n self.results = results\n super(ProbeRealResult, self).__init__(**kwargs)\n\n def to_json(self, formatted):\n res = self.to_dict()\n res.pop(\"_id\")\n # apply or not IrmaFormatter\n if formatted:\n res = IrmaFormatter.format(self.name, res)\n return res\n","sub_path":"frontend/models/nosqlobjects.py","file_name":"nosqlobjects.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"390384370","text":"'''\n2번 복붙\nCNN으로 딥하게 구성\n2개의 모델 구성 하나는 보통 오토인코더 하나는 딥하게 만든 것\n2개의 성능비교\n\nConV2D\nmaxpool\nConV2D\nmaxpool \nConV2D\nmaxpool -> encoder\n\nconV2D\nUpSamplung2D\nConV2D\nUpSamplung2D\nConV2D\nUpSamplung2D\nConV2D(1,) -> Decoder\n\n'''\n\n# 중요하지 않은 특성들을 도태시킴 / 특징이 강한 것을 더 강하게 해주는 것은 아님\n\nimport numpy as np\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.python.keras.layers.pooling import AveragePooling2D\n\n# 1. 데이터\n(x_train, _), (x_test, _) = mnist.load_data()\n\nx_train = x_train.reshape(60000, 28, 28, 1).astype('float')/255\nx_test = x_test.reshape(10000, 28, 28, 1).astype('float')/255\nx_train2 = x_train.reshape(60000, 28 * 28)\n\n# 2. 모델\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import Dense, Input, Conv2D, MaxPooling2D, GlobalAvgPool2D, Flatten\nfrom tensorflow.python.keras.layers.convolutional import UpSampling2D\n\ndef autoencoder(hidden_layer_size):\n model = Sequential()\n model.add(Conv2D(filters=hidden_layer_size, kernel_size=(2, 2), input_shape=(28, 28, 1), activation='relu', padding='same'))\n model.add(MaxPooling2D())\n model.add(Conv2D(128, (2, 2), activation='relu', padding='same'))\n model.add(MaxPooling2D())\n model.add(Conv2D(256, (2, 2), activation='relu', padding='same'))\n model.add(GlobalAvgPool2D())\n model.add(Dense(1024, activation='relu'))\n model.add(Dense(784, activation='sigmoid'))\n\n return model\n\ndef autoencoder2(hidden_layer_size):\n model = Sequential()\n model.add(Conv2D(filters=hidden_layer_size, kernel_size=(2, 2), input_shape=(28, 28, 1), activation='relu', padding='same'))\n model.add(UpSampling2D(size=(2,2)))\n model.add(MaxPooling2D())\n model.add(Conv2D(128, (2, 2), activation='relu', padding='same'))\n model.add(MaxPooling2D())\n model.add(Conv2D(256, (2, 2), activation='relu', padding='same'))\n model.add(MaxPooling2D())\n model.add(Conv2D(512, (2, 2), activation='relu', padding='same'))\n model.add(Flatten())\n model.add(Dense(1024, activation='relu'))\n model.add(Dense(784, activation='sigmoid'))\n return model\n\n\nmodel = autoencoder(hidden_layer_size=104) # pca 95%\n\nmodel.compile(optimizer='adam', loss='mse')\n\nmodel.fit(x_train, x_train2, epochs=10)\n\noutput = model.predict(x_test)\n\nfrom matplotlib import pyplot as plt\nimport random\n\nfig, ((ax1, ax2, ax3, ax4, ax5), (ax6, ax7, ax8, ax9, ax10)) = plt.subplots(2, 5, figsize=(20, 7))\n\n\n# 이미지 5개를 무작위로 고른다.\nrandom_images = random.sample(range(output.shape[0]), 5)\n\n# 원본(입력) 이미지를 맨 위에 그린다.\nfor i, ax in enumerate([ax1, ax2, ax3, ax4, ax5]):\n ax.imshow(x_test[random_images[i]].reshape(28, 28), cmap='gray')\n if i == 0:\n ax.set_ylabel(\"INPUT\", size=20)\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\n# 오토인코더가 출력한 이미지를 아래에 그린다.\nfor i, ax in enumerate([ax6, ax7, ax8, ax9, ax10]):\n ax.imshow(output[random_images[i]].reshape(28, 28), cmap='gray')\n if i == 0:\n ax.set_ylabel(\"OUTPUT\", size=20)\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\nplt.tight_layout()\nplt.show()","sub_path":"AE/A05_CAE.py","file_name":"A05_CAE.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104603565","text":"# usage: (py3 a.py < a.in) > a.out\n\nimport time, sys, inspect\n\nlineno = lambda: inspect.currentframe().f_back.f_back.f_lineno\nprint = lambda *a, **k: __builtins__.print(str(lineno())+\":\", *a, file=sys.stderr, **k)\nmap = lambda *a: list(__builtins__.map(*a))\n\n#---------------------------------------------\n\n\"\"\"\ndo we have to do simulation?\n we can test feasibility of that by pre-computing all 10**6 cases\n\nwhen does it cycle?\n is 0 only number that cycles?\n can we detect cycling?\n\nyup, simulation stays easily within the time limit and only 0 cycles\n\nreason: 0 will be last digit for 10*n (10*n ends in 0)\n 1..9 will be leading digit for k-digit multiples\n where k is the smallest number such that 10**k >= n\n since 10**k + n <= 10**k + 10**k = 2 * 10**k\n eg: for numbers between 10 and 100 we are guaranteed 3-digit\n multiples of the form 1xx, 2xx, 3xx, .., 9xx\n simply because 10..100 are less then 100!\n\n\"\"\"\n\ndef run(n):\n\n if n == 0:\n return \"INSOMNIA\"\n\n unseen = [str(x) for x in range(10)]\n cur = 0\n while unseen:\n cur += n\n for c in str(cur):\n if c in unseen:\n unseen.remove(c)\n\n return cur\n\n#---------------------------------------------\n\ndef read_case():\n return int(input())\n\nfor i in range(int(input())):\n outstr = \"Case #\"+str(i+1)+\": \"+str(run(read_case()))\n print(outstr, \" @ t =\", time.clock())\n __builtins__.print(outstr)\n\n\n\n","sub_path":"solutions_5652388522229760_1/Python/xjcl/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"533157078","text":"'''\r\nCode leveraged from SunFounder code included with the car. Specifically,\r\nwe use that code to determine how to interact with the car libraries and\r\nimport the right items. We also use it to determine how to initialize the \r\ncar controls.\r\n'''\r\n\r\nfrom time import sleep\r\nfrom picar import back_wheels, front_wheels\r\nfrom django.http import HttpResponse\r\nimport picar\r\n\r\n# Global Variabls\r\nSPEED = 30\r\nVALID_ACTIONS = set([\"forward\", \"backward\", \"stop\", \"set_speed\", \"turn_right\", \"turn_left\", \"turn_straight\"])\r\n\r\n# Car Setup\r\npicar.setup()\r\ndb_file = \"/home/pi/SunFounder_PiCar-V/remote_control/remote_control/driver/config\"\r\nfw = front_wheels.Front_Wheels(debug=False, db=db_file)\r\nbw = back_wheels.Back_Wheels(debug=False, db=db_file)\r\nbw.ready()\r\nfw.ready()\r\n\r\n# Maintain the state of the car\r\ncarIsMoving = False\r\n\r\n\r\n# Handle Incoming Requests for Errors\r\ndef run(request):\r\n global SPEED\r\n \r\n # Handle speed updates\r\n if 'speed' in request:\r\n speedl = int(request['speed'])\r\n if speedl > 100:\r\n speedl = 100\r\n if speedl < 0:\r\n speedl = 0\r\n SPEED = speedl\r\n\r\n # Handle time requests\r\n time = None\r\n if 'time' in request:\r\n time = request['action']\r\n\r\n # Handle action requests\r\n if 'action' in request:\r\n action = request['action']\r\n \r\n # Make sure the action is valid\r\n if action not in VALID_ACTIONS:\r\n return \"Not a valid action\"\r\n\r\n # Preform the action\r\n return executeCommand(action, time)\r\n\r\n\r\n# Actually Execute The Commands\r\ndef executeCommand(action, time=None):\r\n \r\n global SPEED\r\n global carIsMoving\r\n\r\n # Move car forwards\r\n if action == 'backward':\r\n carIsMoving = True\r\n bw.speed = SPEED\r\n bw.forward()\r\n if time:\r\n sleep(time)\r\n bw.stop()\r\n\r\n # Move car backwards\r\n elif action == 'forward':\r\n carIsMoving = True\r\n bw.speed = SPEED\r\n bw.backward()\r\n if time:\r\n sleep(time)\r\n bw.stop()\r\n\r\n # Stop car\r\n elif action == 'stop':\r\n carIsMoving = False\r\n bw.stop()\r\n\r\n # Turn left\r\n elif action == 'turn_left':\r\n fw.turn_left()\r\n\r\n # Turn right\r\n elif action == 'turn_right':\r\n fw.turn_right()\r\n \r\n # Turn straight\r\n elif action == 'turn_straight':\r\n fw.turn_straight()\r\n \r\n # Set speed\r\n elif action == 'set_speed' and carIsMoving:\r\n bw.speed = SPEED\r\n\r\n\r\n return \"Command Executed\"\r\n","sub_path":"Raspberry-Pi-Source/Controller/piCarCommands.py","file_name":"piCarCommands.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"261507439","text":"# Problem [4008] : [모의 SW 역량 테스트] 숫자 만들기\n\nimport sys\nsys.stdin = open('input.txt')\n\ndef Backtracking(n, v):\n global min_val, max_val\n if n == N:\n min_val = min(min_val, v)\n max_val = max(max_val, v)\n\n for i in range(4):\n if O[i]:\n O[i] -= 1\n if i == 0:\n Backtracking(n+1, v + D[n])\n elif i == 1:\n Backtracking(n+1, v - D[n])\n elif i == 2:\n Backtracking(n+1, v * D[n])\n else:\n if v < 0:\n Backtracking(n+1, -(abs(v)//D[n]))\n else:\n Backtracking(n+1, v // D[n])\n O[i] += 1\n \nif __name__ == \"__main__\":\n T = int(input())\n for tc in range(1, T+1):\n min_val = 100000000\n max_val = -100000000\n N = int(input())\n O = list(map(int,input().split()))\n D = list(map(int,input().split()))\n Backtracking(1,D[0])\n result = max_val - min_val\n print('#{} {}'.format(tc,result))","sub_path":"SWEA/SW_TEST/SWEA_4008/SWEA_4008.py","file_name":"SWEA_4008.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380311422","text":"from selenium import webdriver\nfrom lxml import etree\n\ndriver = webdriver.Chrome('/Users/admin/Downloads/chromedriver 2')\n# driver.fullscreen_window()\ndriver.get('https://www.51job.com/')\ndriver.find_element_by_id('kwdselectid').send_keys('python 爬虫\\n')\nhtml = driver.page_source\nxml = etree.HTML(html)\ntitles = xml.xpath('//p[@class=\"t1 \"]/span/a/@title')\ncompanys = xml.xpath('//span[@class=\"t2\"]/a/@title')\nwages = xml.xpath('//div[@class=\"el\"]/span[@class=\"t4\"]')\nfor i, a, z in zip(titles, companys, wages):\n print(i, a, z.text)\n\n","sub_path":"d盘/pacong/51.py","file_name":"51.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"419702446","text":"from django.shortcuts import get_object_or_404, render\n# from django.http import HttpResponse\n\n# To localise datetime.now() from UTC\nfrom datetime import datetime, timedelta\nimport pytz\nfrom pytz import timezone\nlocalZone = timezone('Asia/Kolkata')\n\nfrom .models import DoctorDetails, PatientSteggedDetails\n\nfrom .forms import PatientDetailsForm\n\nfrom background_task import background\n\n# Background task for checking the status of doctor in or out\n@background(schedule=10)\ndef doctorScheduling():\n doctor_list = DoctorDetails.objects.all()\n for doctor in doctor_list:\n localTime = localZone.localize(datetime.now())\n localTimeNow = localTime.time()\n doctorInTime1 = doctor.doctor_shift_slot1_from\n doctorOutTime1 = doctor.doctor_shift_slot1_to\n doctorInTime2 = doctor.doctor_shift_slot2_from\n doctorOutTime2 = doctor.doctor_shift_slot2_to\n\n if ((localTimeNow > doctorInTime1 and localTimeNow < doctorOutTime1) or (localTimeNow > doctorInTime2 and localTimeNow < doctorOutTime2)):\n # print(True)\n doctor.doctor_availability = True\n doctor.save()\n else:\n # print(False)\n doctor.doctor_availability = False\n doctor.save()\n return 0\n\n# Background task to change state of doctor availability to \"busy\" on start of appointment\n@background(schedule=60)\ndef setBusyOnAppointmentStart(doctorId):\n doctor = DoctorDetails.objects.get(id=doctorId)\n doctor.doctor_availability = False\n doctor.save()\n return 0\n\n# Background task to change state of doctor availability to \"available\" on completion of appointment\n@background(schedule=60)\ndef setAvailableOnAppointmentEnd(doctorId):\n doctor = DoctorDetails.objects.get(id=doctorId)\n doctor.doctor_availability = True\n doctor.save()\n return 0\n\n# handle the calculation of time till appointment commence datetime by converting the datetime to seconds using datetime.timedelta()\ndef getBusy(patientDetails, doctor):\n appointmentFormTime = patientDetails.appointment_form_submission_date_time\n scheduledTime = patientDetails.appointment_date_time\n timeToAppointment = int((scheduledTime - appointmentFormTime).total_seconds()) # IMPORTANT: Background task scheduler has to get arguments in int only and not float\n setBusyOnAppointmentStart(doctor.id, schedule=timeToAppointment) # Pass schedule offset in seconds to background task\n patientCondition = patientDetails.patient_state\n sessionTime = 0\n if patientCondition == 'N':\n sessionTime = 20\n elif patientCondition == 'U':\n sessionTime = 30\n else:\n return 0\n timeTillSwitch = int(timedelta(minutes=(sessionTime+2)).total_seconds() + timeToAppointment)\n setAvailableOnAppointmentEnd(doctor.id, schedule=timeTillSwitch)\n return 0\n\n\ndef index(request): \n doctor_list = DoctorDetails.objects.order_by('-doctor_availability')\n doctorScheduling()\n context = {'doctor_list': doctor_list}\n return render(request, 'frontdesk/home.html', context)\n\ndef doctorDetails(request, id):\n\n doctor = DoctorDetails.objects.get(id=id)\n\n form = PatientDetailsForm(request.POST or None)\n \n if form.is_valid():\n form.save()\n # get latest record of patientdetails saved to db based on form submission auto timestamp\n patientDetails = PatientSteggedDetails.objects.latest('appointment_form_submission_date_time')\n getBusy(patientDetails, doctor)\n\n # form_1 = AppointmentDetailsForm(request.POST or None)\n # if form_1.is_valid():\n # form_1.save()\n \n context = {'doctor': doctor, 'form': form}\n\n return render(request, 'frontdesk/doctorDetails.html', context)\n\ndef doctorBusy(request, id):\n busyDoctor = DoctorDetails.objects.get(id=id)\n return render(request, 'frontdesk/busyDoctor.html', {'busyDoctor': busyDoctor})","sub_path":"hospital/frontdesk/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"400700228","text":"from app.main.service.subcribe_topic_service import delete_subcribe, get_subcribe, subcribe_email, update_subcribe\nfrom flask_jwt_extended.utils import get_jwt_identity\nfrom app.main.util.custom_jwt import Candidate_only\nfrom app.main.util.dto import SubcribeEmailDto\nfrom app.main.util.response import response_object\nfrom flask_restx import Resource\nfrom flask.globals import request\n\napi = SubcribeEmailDto.api\n\nsubcribe_header = api.parser()\nsubcribe_header.add_argument(\"Authorization\", location=\"headers\", required=True)\n\n\n@api.route('')\n@api.response(404, 'Subcribe not found.')\nclass SubcribeEmail(Resource):\n @api.doc('get list subcribe email:')\n @api.expect(subcribe_header)\n @Candidate_only\n def get(self):\n '''get list subcribe email'''\n identity = get_jwt_identity()\n cand_id = identity['id']\n\n subcribe = get_subcribe(cand_id)\n if not subcribe:\n return response_object()\n else:\n return response_object(200, \"Thành công.\", data=subcribe.to_json())\n subcribe_new_header = api.parser()\n subcribe_new_header.add_argument(\"Authorization\", location=\"headers\", required=True)\n subcribe_new_header.add_argument(\"topic\", type=str ,location=\"json\", required=True)\n subcribe_new_header.add_argument(\"province_id\", type=str ,location=\"json\", required=False, default = None)\n @api.doc('subcribe email: (type= 0 daily, 1: week) (statis= 0: inactive, 1: active)')\n @api.expect(subcribe_new_header)\n @Candidate_only\n def post(self):\n '''subcribe email: (type= 0 daily, 1: week) (statis= 0: inactive, 1: active)'''\n identity = get_jwt_identity()\n cand_id = identity['id']\n\n topic = request.json['topic']\n province_id = request.json.get('province_id',None)\n return subcribe_email(cand_id,topic,province_id)\n\n @api.doc('delete subcribe email')\n @api.expect(subcribe_header)\n @Candidate_only\n def delete(self):\n '''Delete subcribe'''\n identity = get_jwt_identity()\n cand_id = identity['id']\n\n return delete_subcribe(cand_id)\n\n\nsubcribe_update_header = api.parser()\nsubcribe_update_header.add_argument(\"Authorization\", location=\"headers\", required=True)\nsubcribe_update_header.add_argument(\"topic\", type=str ,location=\"json\", required=True)\nsubcribe_update_header.add_argument(\"province_id\", type=str ,location=\"json\", required=True)\nsubcribe_update_header.add_argument(\"type\", type=int ,location=\"json\", required=True)\nsubcribe_update_header.add_argument(\"status\", type=int ,location=\"json\", required=True, default = 1)\n@api.route('/update')\n@api.response(404, 'Subcribe not found.')\nclass UpdateSubcribe(Resource):\n @api.doc('update subcribe email: (type= 0 daily, 1: week) (statis= 0: inactive, 1: active) ')\n @api.expect(subcribe_update_header)\n @Candidate_only\n def post(self):\n '''update subcribe: (type= 0 daily, 1: week) (statis= 0: inactive, 1: active)'''\n identity = get_jwt_identity()\n cand_id = identity['id']\n\n data = request.json\n\n topic = data['topic']\n province_id = data['province_id']\n type_sub = data['type']\n status = data['status']\n\n return update_subcribe(cand_id,topic,province_id,type_sub,status)","sub_path":"app/main/controller/subcribe_email_controller.py","file_name":"subcribe_email_controller.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"523407908","text":"info = {\n 'host': 'ws1',\n 'domain': 'rootcap.in',\n 'desc': 'web server',\n 'app': 'apache httpd',\n 'version': 2.2\n}\n\nitem = 'version'\n\nif item in info: # validate for the key\n info[item] = 3.6 # update\n\ninfo['arch'] = 'x86_64' # add an element into the dict\nprint(info)","sub_path":"day2/psdict3.py","file_name":"psdict3.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"141493362","text":"'''\nAndrew Lucero\nCS 1114 HW 6\nProfessor Itay Tal\n\nQ5)\nWrite a program that reads an English word from the user and prints\nhow many vowels and consonants it contains.\n\n\n'''\n\n\ndef main():\n word = input(\"Enter a word: \")\n vowels = 0\n consonants = 0\n for letter in word:\n if letter in \"aeiou\":\n vowels += 1\n else:\n consonants += 1\n print(word, \"has\", vowels, \"vowels and\", consonants, \"consonants.\")\n\n\nmain()\n","sub_path":"HW 6/al4991_hw6_q5.py","file_name":"al4991_hw6_q5.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"236144339","text":"import glob\nimport os\nimport re\nimport itertools\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nfrom astropy.io import fits\nimport numpy as np\nimport subprocess\n\ndef flatten(listOfLists):\n \"Flatten one level of nesting\"\n return itertools.chain.from_iterable(listOfLists)\n\ndef reduceifu(datadirectory, rawdatadictionary):\n \"\"\"Something\"\"\"\n datadir = datadirectory\n rawdata = rawdatadictionary\n\n\n\n # Put to each the data dir and print hte quadran\n for k,v in rawdata.items():\n try:\n rawdata[k] = datadir+v\n except:\n temp = [datadir+i for i in v]\n rawdata[k] = temp\n\n t = fits.open(rawdata['IFU_SCIENCE'])[0]\n quadrant = t.header['HIERARCH ESO OCS CON QUAD']\n print('Quadrant {}'.format(quadrant))\n \n \n \n ##Create bias\n \n outdir = datadir+'quadrant'+str(quadrant)\n\n #Create outdir if it doesnt exist\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n\n filenamebias = outdir+'/bias.sof'\n with open(filenamebias,'w') as file:\n for bias in rawdata['BIAS'][0:]:\n cat = 'BIAS'\n string = '{} {}\\n'.format(bias,cat)\n file.write(string)\n \n \n \n stackmethod = '--StackMethod=Average'\n #esorexpath = '/bin/esorex'\n esorexpath = '/home/mmarcano/Documents/VIMOS/NGC6652/esorex/bin/esorex'\n routine = 'vmbias'\n outputdir = '--output-dir={}'.format(outdir)\n logdir = '--log-dir={}'.format(outdir)\n \n commandbias = '{} {} {} {} {}'.format(esorexpath,outputdir,logdir,routine, filenamebias)\n print(commandbias)\n #os.system(commandbias)\n subprocess.run(commandbias,shell=True,check=True)\n \n os.rename(outdir+'/esorex.log',outdir+'/'+routine+'.log')\n \n rawdata['MASTER_BIAS'] = outdir+'/master_bias.fits'\n \n \n ##Calib\n \n inputfilescalib = ['IFU_SCREEN_FLAT','IFU_ARC_SPECTRUM','LINE_CATALOG','IFU_IDENT','MASTER_BIAS']\n\n filenamecalib = outdir+'/calib.sof'\n with open(filenamecalib,'w') as file:\n for i in inputfilescalib:\n tmpfile = rawdata[i]\n if isinstance(tmpfile, list): \n for j in tmpfile:\n string = '{} {}\\n'.format(j,i)\n file.write(string)\n else:\n string = '{} {}\\n'.format(tmpfile,i)\n file.write(string)\n\n\n # Define the routine and call it\n routine = 'vmifucalib'\n\n commandcalib = '{} {} {} {} {}'.format(esorexpath,outputdir,logdir,routine, filenamecalib)\n print(commandcalib)\n subprocess.run(commandcalib,shell=True)\n \n os.rename(outdir+'/esorex.log',outdir+'/'+routine+'.log')\n\n rawdata['IFU_IDS'] = outdir+'/ifu_ids.fits'\n rawdata['IFU_TRACE'] = outdir+'/ifu_trace.fits'\n rawdata['IFU_TRANSMISSION'] = outdir+'/ifu_transmission.fits'\n \n \n ##Standard\n inputfilesstandard = ['IFU_STANDARD','MASTER_BIAS','IFU_IDS','IFU_TRACE','IFU_TRANSMISSION','EXTINCT_TABLE','STD_FLUX_TABLE']\n\n filenamestandard = outdir+'/ifustandard.sof'\n with open(filenamestandard,'w') as file:\n for i in inputfilesstandard:\n tmpfile = rawdata[i]\n if isinstance(tmpfile, list): \n for j in tmpfile:\n string = '{} {}\\n'.format(j,i)\n file.write(string)\n else:\n string = '{} {}\\n'.format(tmpfile,i)\n file.write(string)\n\n routine = 'vmifustandard'\n\n commandstandard = '{} {} {} {} {}'.format(esorexpath,outputdir,logdir,routine, filenamestandard)\n print(commandstandard)\n subprocess.run(commandstandard,shell=True)\n os.rename(outdir+'/esorex.log',outdir+'/'+routine+'.log')\n\n #Science Soif\n \n rawdata['IFU_SPECPHOT_TABLE'] = outdir+'/ifu_specphot_table.fits'\n\n inputfilesscience = ['IFU_SCIENCE','MASTER_BIAS','IFU_IDS','IFU_TRACE','IFU_TRANSMISSION','EXTINCT_TABLE','IFU_SPECPHOT_TABLE']\n\n filenamescience = outdir+'/ifuscience.sof'\n with open(filenamescience,'w') as file:\n for i in inputfilesscience:\n tmpfile = rawdata[i]\n if isinstance(tmpfile, list): \n for j in tmpfile:\n string = '{} {}\\n'.format(j,i)\n file.write(string)\n else:\n string = '{} {}\\n'.format(tmpfile,i)\n file.write(string)\n \n \n routine = 'vmifuscience'\n\n calibrateflux = '--CalibrateFlux=true'\n\n commandscience = '{} {} {} {} {} {}'.format(esorexpath,outputdir,logdir,routine, calibrateflux ,filenamescience)\n print(commandscience)\n subprocess.run(commandscience,shell=True)\n os.rename(outdir+'/esorex.log',outdir+'/'+routine+'.log')\n\n \n \n \ndef reducecombinecube(datadirectory,typecombine='ifu_science_flux_reduced'):\n \"\"\"Or it can be 'IFU_SCIENCE_REDUCED' \"\"\"\n datadir = datadirectory\n \n \n combinedir = datadir+'Combine'\n\n #Create outdir if it doesnt exist\n if not os.path.exists(combinedir):\n os.makedirs(combinedir)\n\n filenamescombinecube = combinedir+'/ifucombinefov{}.sof'.format(typecombine.lower())\n\n with open(filenamescombinecube,'w') as file:\n for i in [1,2,3,4]:\n fitstemp='{}quadrant{}/{}.fits'.format(datadir,i,typecombine.lower())\n string = '{} {}\\n'.format(fitstemp,typecombine.upper())\n file.write(string)\n\n #esorexpath = '/bin/esorex'\n outputdir = '--output-dir={}'.format(combinedir)\n logdir = '--log-dir={}'.format(combinedir)\n routine = 'vmifucombinecube'\n command = '{} {} {} {} {} '.format(esorexpath,outputdir,logdir,routine, filenamescombinecube)\n print(command)\n subprocess.run(command,shell=True)\n \ndef changewcs(original,destination):\n originalcube = original\n newcube = destination\n \n copyfile = 'cp {} {}'.format(originalcube,newcube)\n os.system(copyfile)\n fits.info(newcube)\n oricube = fits.open(originalcube)\n oricubehearder = oricube[0].header\n ifura = oricubehearder['HIERARCH ESO INS IFU RA']\n ifudec = oricubehearder['HIERARCH ESO INS IFU DEC']\n \n fits.setval(newcube, 'CRVAL1', value=ifura)\n fits.setval(newcube, 'CRVAL2', value=ifudec)","sub_path":"data/NGC6652B5/2003-06-24T06:08:54/Old/oldreducing.py","file_name":"oldreducing.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"501967674","text":"#encoding=utf-8\nimport Tkinter\nimport tkFileDialog\nimport tkMessageBox\nimport xlrd #read xls\nimport xlwt #write xls\nimport os #file operator\nimport math\nimport sys \nreload(sys) \nsys.setdefaultencoding('utf-8') \nprint(sys.getdefaultencoding())\ndef openfile():\n #open fileDialog\n sourec_filename = tkFileDialog.askopenfilename(title='File Open', filetypes=[('excel', '*.xls *.xlsx')])\n text1.delete(1.0,Tkinter.END)\n text1.insert(1.0,sourec_filename)\ndef cutfile():\n sourec_filename=text1.get(1.0,Tkinter.END)\n sourec_filename=sourec_filename.replace(u'\\n','')\n print(sourec_filename)\n cut_number=int(ent1.get())\n if sourec_filename=='':\n tkMessageBox.showinfo('Error','File %s not exists!'%sourec_filename) \n return\n #get the name and path of file except extension\n target_filename_prepaper=os.path.splitext(sourec_filename)[0]\n filename_temp=os.path.splitext(os.path.split(sourec_filename)[1])[0]+'-1.xls'\n #get all filename under the path of source file\n #decide file is cut or not \n if filename_temp in os.listdir(os.path.split(sourec_filename)[0]):\n tkMessageBox.showinfo('Error','File %s exists!'%filename_temp)\n else:\n #open *.xls|*.xlsx to get data\n try:\n data=xlrd.open_workbook(filename=sourec_filename)\n sheet=data.sheets()[0]\n rows=sheet.nrows\n cols=sheet.ncols\n n=(rows-1)//cut_number\n for i in range(n):\n filename_temp=target_filename_prepaper+'-'+str(i+1)+'.xls'\n file_temp=xlwt.Workbook()\n work_sheet=file_temp.add_sheet('Sheet1') \n #write the header of table\n for k in range(cols):\n work_sheet.write(0,k,sheet.row_values(0)[k]) \n for j in range(cut_number):\n for k in range(cols):\n #write data by every cell\n work_sheet.write(j+1,k,sheet.row_values(i*cut_number+j+1)[k])\n file_temp.save(filename_temp)\n #deal last one piece\n if (rows-1)%cut_number!=0:\n filename_temp=target_filename_prepaper+'-'+str(n+1)+'.xls'\n file_temp=xlwt.Workbook()\n work_sheet=file_temp.add_sheet('Sheet1') \n for k in range(cols):\n work_sheet.write(0,k,sheet.row_values(0)[k]) \n for j in range(rows-n*cut_number-1):\n for k in range(cols):\n work_sheet.write(j+1,k,sheet.row_values(n*cut_number+j+1)[k])\n file_temp.save(filename_temp)\n tkMessageBox.showinfo(message='Success! File: \\n%s \\nhas been cut into %d files!'%(os.path.split(sourec_filename)[1],math.ceil((rows-1)/float(cut_number))))\n except Exception as err:\n tkMessageBox.showinfo(message='Error! Mssage :\\n %s \\nPlesae try again!'%err)\n\n\n#main function \nglobal sourec_filename,cut_number\nsourec_filename=''\nroot = Tkinter.Tk()\nroot.resizable(0,0)\nroot.title('APP for Cutting')\nroot.geometry(\"320x180+%d+%d\"\\\n%((root.winfo_screenwidth()-320)//2,(root.winfo_screenheight()-180)//2 ) )\nfm1=Tkinter.Frame(root,bg='red',height=60)\nfm2=Tkinter.Frame(root,bg='blue',height=60)\nfm3=Tkinter.Frame(root,bg='green',height=60)\n\nbtn1 = Tkinter.Button(fm1, text='File Select', command=openfile)\nbtn2 = Tkinter.Button(fm2, text='File Cut', command=cutfile)\ntext1=Tkinter.Text(fm1,height=3,state='normal',width=36)\ntex1=Tkinter.StringVar()\ntex2=Tkinter.StringVar()\ntex3=Tkinter.StringVar()\n\nent1=Tkinter.Entry(fm2,textvariable=tex1)\nent2=Tkinter.Entry(fm2,textvariable=tex2,state='disabled')\nent3=Tkinter.Entry(fm3,textvariable=tex3,state='disabled')\ntex1.set('500')\ntex2.set('Number Of Each Pieces:')\ntex3.set('App for cutting *.xls|*.xlsx to pieces!')\n\nfm3.pack(side='top',fill='x')\nfm1.pack(side='top',fill='x')\nfm2.pack(side='top',fill='x')\ntext1.pack(side='left',fill='both')\nbtn1.pack(side='left',fill='both')\nbtn2.pack(side='right',fill='both')\nent2.pack(side='left',fill='both')\nent1.pack(side='left',fill='both')\nent3.pack(fill='both')\nprint(''.encode('utf-8'))\nroot.mainloop()\n\n#eee\n","sub_path":"GUI_For_Cutting_File.py","file_name":"GUI_For_Cutting_File.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"555563619","text":"# -*- coding: utf-8 -*-\nimport sys\nimport functools\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n\nfrom Ui_tablebrowser import *\nfrom table.view_table import *\nfrom general import *\n\nfrom new_exceptions import *\n\n\n\nclass tablebrowser(QDialog, Ui_tablebrowser):\n def __init__(self, view_tables):\n super(tablebrowser, self).__init__()\n self.setupUi(self)\n \n self.tablePath=None\n self.view_tables=view_tables\n self.table=None\n self.column=None\n \n# self.connect(self.openButton, SIGNAL(\"clicked()\"), self.browser)\n self.connect(self.tableBox, SIGNAL(\"currentIndexChanged(QString)\"),self.updateColumnsList)\n \n \n #Generating table list comboBox\n index=0\n for key, val in view_tables.iteritems():\n text=unicode(key)[-50:]\n self.tableBox.addItem(text, QVariant(key))\n self.tableBox.setItemData(index,unicode(key), Qt.ToolTipRole)\n index +=1\n \n self.connect(self.columnsBox, SIGNAL(\"currentIndexChanged(QString)\"), self.updateColumnSelected)\n #self.connect(self.columnsBox, SIGNAL(\"currentIndexChanged()\"), self.updateColumnSelected)\n self.updateColumnsList(0)\n \n# def browser(self):\n# dir = os.path.dirname(\".\")\n# fName = unicode(QFileDialog.getOpenFileName(self, \"File open \", dir,TABLEFORMAT))\n# if (fName==\"\"):\n# return\n# self.tablePath=unicode(fName)\n# self.table=view_table(fName)\n# try:\n# self.table.loadTable()\n# except:\n# return\n# self.tablePathLabel.setText(self.tablePath)\n# for index, title in enumerate(self.table.getColumnTitles()):\n# self.columnsBox.addItem(title, QVariant(index))\n\n def updateColumnsList(self,index):\n item=self.tableBox.itemData(self.tableBox.currentIndex(), Qt.ToolTipRole)\n text=self.tableBox.itemData(self.tableBox.currentIndex(), Qt.DisplayRole)\n text=unicode(text.toString())\n item=unicode(item.toString())\n self.tablePathLabel.setText(text)\n self.tablePathLabel.setToolTip(item)\n if item:\n currentTable=item\n self.table=self.view_tables[currentTable]\n columnTitles=self.view_tables[currentTable].getColumnTitles()\n numericColumns=self.view_tables[currentTable].getNumericColumns()\n self.columnsBox.clear()\n for index, title in enumerate(columnTitles):\n if numericColumns[index]:\n self.columnsBox.addItem(title, QVariant(index))\n \n def updateColumnSelected(self, item):\n col=self.columnsBox.itemData(self.columnsBox.currentIndex()).toInt()[0]\n colList=self.table.getColumn(col)\n if colList !=None:\n self.column= map ( lambda x: unicode(x), colList)\n \n","sub_path":"gipsyClasses/tablebrowser.py","file_name":"tablebrowser.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"632514907","text":"def duplicate(string):\n lower_case = string.lower()\n array = list(lower_case)\n encoded = []\n\n for c in array:\n if len(array) > 1 and array.count(c) > 1:\n encoded.append(')')\n else:\n encoded.append('(')\n\n return ''.join(encoded)\n","sub_path":"lib/duplicate.py","file_name":"duplicate.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"351841580","text":"import random\nimport time\n\nclass text_break(object):\n\n def __init__(self, tfile = None, chars = None):\n self.allowed_char = chars #allowed characters for word generation\n self.letter_freq = {} #dictionary of dictionaries that contain letter frequencies\n self.file = tfile #file to operate on\n self.word_length = {} #dictionary containing counts of word lengths\n\n if self.file != None:\n with open(self.file) as f:\n self.contents = f.read()\n self.contents = self.contents.lower()\n \n else:\n self.contents = None\n \n\n def set_file(self, filename):\n self.file = filename\n\n def get_file(self):\n return self.file\n\n def set_chars(self, chars):\n self.allowed_char = chars\n\n def get_chars(self):\n return self.allowed_char\n\n def get_letter_freq(self):\n return self.letter_freq\n\n def get_word_len(self):\n return self.word_length\n\n def __histogram(self, contents, allowed_chars): #creates dictionary within dictionary for each letter in allowed_char\n chars = {}\n for char in contents:\n if char in allowed_chars and char not in chars.keys():\n chars[char] = {}\n\n return chars\n\n def __next_letter(self, contents, allowed_chars, chars): #add the count of letter y following letter x to letter x's dictionary\n #start = time.time()\n '''\n #this is the old, very slow code, running an order of magnitude slower\n for key in chars.keys():\n for i in range(len(contents) - 1):\n if contents[i + 1] in allowed_chars and contents[i] == key:\n if contents[i + 1] in chars[key]:\n chars[key][contents[i + 1]] += 1\n\n else:\n chars[key][contents[i + 1]] = 1\n print(time.time() - start)\n return chars\n '''\n for i in range(len(contents) - 1):\n try:\n if contents[i + 1] in chars[contents[i]] and contents[i + 1] in allowed_chars:\n chars[contents[i]][contents[i + 1]] += 1\n\n else:\n chars[contents[i]][contents[i + 1]] = 1\n except KeyError:\n #print(\"key DNE\")\n pass\n \n #print(time.time() - start)\n return chars\n\n def __letter_percentages(self, chars): #changes letter y's count to a percentage of the total\n for key in chars.keys():\n total = 0\n \n for letter in chars[key].keys(): #adding up total for each letters subsequent letters\n total += chars[key][letter]\n\n for letter in chars[key].keys(): #calculating percentage of total for each letter\n chars[key][letter] = chars[key][letter]/total\n\n return chars\n\n def __word_break(self): #breaks contents into a list of words and makes sure word only contain allowed letters\n lines = self.contents.split(\"\\n\")\n words = []\n\n for line in lines:\n for word in line.split(\" \"):\n cleaned_word = \"\"\n for char in word:\n if char in self.allowed_char:\n cleaned_word += char\n \n words.append(cleaned_word)\n\n return words\n\n def run_word_len(self): #counts amount of word length n and adds it to n's value in self.word_length\n words = self.__word_break()\n\n for word in words:\n if len(word) in self.word_length.keys() and len(word) > 0:\n self.word_length[len(word)] += 1\n\n elif len(word) > 0:\n self.word_length[len(word)] = 1\n\n def run(self):\n\n self.letter_freq = self.__histogram(self.contents, self.allowed_char)\n self.letter_freq = self.__next_letter(self.contents, self.allowed_char, self.letter_freq)\n self.letter_freq = self.__letter_percentages(self.letter_freq)\n","sub_path":"text_break.py","file_name":"text_break.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316560044","text":"#coding:utf-8\n\nfrom tornado.web import RequestHandler\nimport json\nfrom util.exception import ParamExist\nimport logging\n\nfrom util import convert\nfrom api.base_auth import auth_api_login\nfrom logic.school import SchoolLogic\nfrom logic.gradelogic import GradeLogic\nfrom logic.classlogic import ClassLogic\nfrom logic.teacher import TeacherLogic\nfrom logic.student import StudentLogic\nfrom logic.relative import RelativeLogic\nfrom logic.relation import RelationLogic\nfrom logic.teacher_history import Teacher_HistoryLogic\nfrom logic.student_history import Student_HistoryLogic\nfrom util import util_excel\n\nLOG = logging.getLogger(__name__)\n\nclass CombinationHandler(RequestHandler):\n def initialize(self, static_path, excel_path, **kwds):\n self.static_path = static_path\n self.excel_path = excel_path\n\n @auth_api_login\n def post(self, combination):\n try:\n if combination == \"student_relative\":\n self.student_relative()\n if combination == \"bath_update_relative\":\n self.bath_update_relative()\n if combination == \"delete_student_relative\":\n self.delete_student_relative()\n if combination == \"batch_teacher_excel\":\n self.batch_teacher_excel()\n if combination == \"batch_student_excel\":\n self.batch_student_excel()\n\n except Exception as ex:\n LOG.error(\"combination %s error:%s\"%(combination, ex))\n self.finish(json.dumps({'state': 10, 'message': 'combination input error'}))\n\n def _save_student_relative(self, student_relative_info):\n name = student_relative_info.get('name', '')\n sex = student_relative_info.get('sex')\n birthday = student_relative_info.get('birthday', '')\n class_id = student_relative_info.get('class_id', '')\n relation_number = student_relative_info.get(\"relation_number\")\n relative_list = student_relative_info.get(\"relative_list\", [])\n\n stu_op = StudentLogic()\n relative_op = RelativeLogic()\n relation_op = RelationLogic()\n student_info = stu_op.input(name=name, sex=sex, birthday=birthday, class_id=class_id,\n relation_number=relation_number)\n if not student_info:\n #self.finish(json.dumps({'state': 1, 'message': 'student info error'}))\n return 1, '%s:student info error.'%name\n for relative in relative_list:\n relative_info = relative_op.input(\n name=convert.bs2utf8(relative.get(\"name\", \"\")),\n sex=relative.get(\"sex\", 0),\n birthday=convert.bs2utf8(relative.get(\"birthday\", \"\")),\n phone=convert.bs2utf8(relative.get(\"phone\", \"\")))\n if not relative_info:\n #self.finish(json.dumps({'state': 2, 'message': '%s: relative info error' % relative.get(\"name\", \"\")}))\n return 2, '%s: relative info error.' % relative.get(\"name\", \"\")\n relation_op.input(relative.get(\"relation\", \"\"), student_id=student_info.get(\"id\"),\n relative_id=relative_info.get(\"id\"))\n return 0, 'save student success.'\n\n def _check_student_relative(self, student_relative_info):\n name = student_relative_info.get('name', '')\n birthday = student_relative_info.get('birthday', '')\n class_id = student_relative_info.get('class_id', '')\n relative_list = student_relative_info.get(\"relative_list\", [])\n\n if birthday and not convert.is_date(birthday):\n return 1, '%s: student info error.'%name\n if not name or not class_id:\n return 1, '%s: student info error.'%name\n\n relative_op = RelativeLogic()\n for relative_info in relative_list:\n relative_birthday = relative_info.get(\"birthday\", \"\")\n if relative_birthday and not convert.is_date(convert.bs2utf8(relative_birthday)):\n return 2, '%s: relative info error.' % relative_info.get(\"name\", \"\")\n phone = convert.bs2utf8(relative_info.get(\"phone\", \"\"))\n if phone and not convert.is_mobile(phone):\n return 2, '%s: relative info error.' % relative_info.get(\"name\", \"\")\n name = convert.bs2utf8(relative_info.get(\"name\", \"\"))\n if not name:\n return 2, '%s: relative info error.' % relative_info.get(\"name\", \"\")\n if phone:\n db_relative_list = relative_op.info_by_phone(phone=phone)\n if db_relative_list and convert.bs2utf8(db_relative_list[0].get(\"name\", \"\")) != name:\n LOG.info(\"relative info, phone:%s and name:%s error\"%(phone, name))\n return 2, '%s: relative info error.' % relative_info.get(\"name\", \"\")\n return 0, 'relative ok'\n\n\n def student_relative(self):\n name = convert.bs2utf8(self.get_argument('name', ''))\n sex = int(self.get_argument('sex', 0))\n birthday = convert.bs2utf8(self.get_argument('birthday', ''))\n class_id = convert.bs2utf8(self.get_argument('class_id', ''))\n relation_number = int(self.get_argument('relation_number', 3))\n str_relative_list = convert.bs2utf8(self.get_argument('relative_list', '[]'))\n relative_list = json.loads(str_relative_list)\n\n student_relative_info = {\n \"name\": name,\n \"sex\": sex,\n \"birthday\": birthday,\n \"class_id\": class_id,\n \"relation_number\": relation_number,\n \"relative_list\": relative_list\n }\n\n #check params\n _check = self._check_student_relative(student_relative_info)\n if _check[0] != 0:\n self.finish(json.dumps({'state': _check[0], 'message': _check[1]}))\n return\n\n _save = self._save_student_relative(student_relative_info)\n self.finish(json.dumps({'state': _save[0], 'message': _save[1]}))\n\n\n def bath_update_relative(self):\n message = \"\"\n student_id = convert.bs2utf8(self.get_argument('student_id', ''))\n relative_list = convert.bs2utf8(self.get_argument('relative_list', '[]'))\n relative_list = json.loads(relative_list)\n relative_op = RelativeLogic()\n relation_op = RelationLogic()\n for relative_info in relative_list:\n try:\n relative_id = relative_info.pop(\"id\", \"\")\n relation = relative_info.pop(\"relation\", \"\")\n if relative_id:\n #update relative, relation\n _ = relative_op.update(id=relative_id, **relative_info)\n if not _:\n message += \"update relative error:%s\" % relative_info.get(\"name\", \"\")\n continue\n relation_info = relation_op.update(relative_id=relative_id, student_id=student_id, relation=relation)\n if not relation_info:\n message += \"update relation error:%s, %s\"%(relative_info.get(\"name\", \"\"), relation)\n continue\n else:\n #add relative, relation\n _ = relative_op.input(name=convert.bs2utf8(relative_info.get(\"name\", \"\")),\n sex=relative_info.get(\"sex\", 0),\n birthday=convert.bs2utf8(relative_info.get(\"birthday\", \"\")),\n phone=convert.bs2utf8(relative_info.get(\"phone\", \"\")))\n if not _:\n message += \"add relative error:%s\" % relative_info.get(\"name\", \"\")\n continue\n relation_info = relation_op.input(relation, student_id=student_id, relative_id=_.get(\"id\"))\n if not relation_info:\n message += \"add relation error:%s, %s\"%(relative_info.get(\"name\", \"\"), relation)\n continue\n except Exception as ex:\n LOG.error(\"update error: %s, %s\"%(relative_info.get(\"name\", \"\"), ex))\n message += \"update error:%s\" %relative_info.get(\"name\", \"\")\n if not message:\n self.finish(json.dumps({'state': 0, 'message': 'update relative success'}))\n else:\n self.finish(json.dumps({'state': 1, 'message': message}))\n\n def delete_student_relative(self):\n student_id = convert.bs2utf8(self.get_argument('student_id', ''))\n stu_op = StudentLogic()\n stu_op.combination_delete(id=student_id)\n message = self.finish(json.dumps({'state': 0, 'message': 'success'}))\n if not message:\n self.finish(json.dumps({'state': 0, 'message': 'delete student success'}))\n else:\n self.finish(json.dumps({'state': 1, 'message': message}))\n\n def batch_teacher_excel(self):\n school_id = convert.bs2utf8(self.get_argument('school_id', ''))\n teacher_excels = self.request.files.get('teacher_excel', '')\n if not school_id or not teacher_excels:\n LOG.error(\"teacher or school_id excel is none: %s\"%school_id)\n self.finish(json.dumps({'state': 2, 'message': 'excel or school_id is none'}))\n return\n teacher_excel = teacher_excels[0]\n filename = teacher_excel['filename']\n filename = \"teacher\" + \".\" + filename.rpartition(\".\")[-1]\n file_path = self.static_path + self.excel_path + filename\n\n with open(file_path, 'wb') as up:\n up.write(teacher_excel['body'])\n\n teacher_data = util_excel.read_teacher_excel(school_id, file_path)\n teacher_op = TeacherLogic()\n _ = teacher_op.batch_input(teacher_data)\n if _[0]:\n self.finish(json.dumps({'state': 0, 'message': _[1]}))\n else:\n self.finish(json.dumps({'state': 1, 'message': _[1]}))\n\n def batch_student_excel(self):\n school_id = convert.bs2utf8(self.get_argument('school_id', ''))\n class_id = convert.bs2utf8(self.get_argument('class_id', ''))\n student_excels = self.request.files.get('student_excel', '')\n if not school_id or not student_excels:\n LOG.error(\"teacher or school_id excel is none: %s\" % school_id)\n self.finish(json.dumps({'state': 2, 'message': 'excel or school_id is none'}))\n return\n student_excel = student_excels[0]\n filename = student_excel['filename']\n filename = \"student\" + \".\" + filename.rpartition(\".\")[-1]\n file_path = self.static_path + self.excel_path + filename\n\n with open(file_path, 'wb') as up:\n up.write(student_excel['body'])\n student_data = util_excel.read_student_excel(school_id, class_id, file_path)\n\n #check info\n error_message = \"\"\n for student_relative in student_data:\n _ = self._check_student_relative(student_relative)\n if _[0] != 0:\n error_message += _[1]\n if error_message:\n self.finish(json.dumps({'state': 1, 'message': error_message}))\n return\n\n for student_relative in student_data:\n _ = self._save_student_relative(student_relative)\n if _[0] != 0:\n error_message += _[1]\n\n # 及时有错误,也把认为批量提交成功,但提供了部分错误信息。\n self.finish(json.dumps({'state': 0, 'message': error_message}))\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"api/combination_input.py","file_name":"combination_input.py","file_ext":"py","file_size_in_byte":11411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"506623424","text":"import datetime\nimport gspread\nimport os\nimport pandas as pd\n\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nfrom src.data_models.SmartsAlertsDataModel import SmartsAlertsDataModel\n\n\nclass AlertsUpdates(object):\n \"\"\"\n Send official alerts information to specific Slack channel.\n \"\"\"\n alert_id_mapping = {\n 1001: '1001-Unusual Price Movement Intra-Day',\n 2011: '2011-Unusual Volume Intra-Day',\n 4009: '4009-Painting the Tape',\n 4011: '4011-Crossing at Short Term High/Low',\n 4012: '4012-Price Driver',\n 4022: '4022-Bait and Switch',\n 4023: '4023-Layering Repeat',\n 4032: '4032-Multi Order Spoofing with Bait and Switch',\n 4040: '4040-Wash Sales A - A',\n 4041: '4041-Wash Sales A - B - A',\n 4042: '4042-Wash Sales A - B - A (Money Pass)',\n 4045: '4045-Collusion',\n 4047: '4047-Pre-arranged Trade'\n }\n\n def __init__(self):\n self.evaluation_date = datetime.date.today() - datetime.timedelta(days=1)\n\n def get_daily_alerts(self, evaluation_date=None):\n \"\"\"\n Get daily alerts from SMARTS backend database.\n \"\"\"\n if not evaluation_date:\n evaluation_date = self.evaluation_date\n\n other_condition = 'isreissue is False'\n\n daily_alerts = (SmartsAlertsDataModel()\n .initialize(evaluation_date=evaluation_date, other_condition=other_condition)\n .evaluate())\n\n alerts_count_by_group = daily_alerts.groupby('code')['id'].count().reset_index(name='Official')\n alerts_count_by_group['code'] = alerts_count_by_group['code'].map(self.alert_id_mapping)\n alerts_count_by_group = alerts_count_by_group.rename(columns={'code': 'Name'})\n\n # dataframe to report\n alert_data_frame = pd.DataFrame({'Name': list(self.alert_id_mapping.values())})\n alert_data_frame = alert_data_frame.merge(alerts_count_by_group, how='left', on='Name').fillna(0)\n alert_data_frame['Official'] = alert_data_frame['Official'].astype('int64')\n\n # add total to dataframe\n alert_data_frame.loc['sum'] = alert_data_frame['Official'].sum()\n alert_data_frame.loc[alert_data_frame.index[-1], 'Name'] = 'total_alerts'\n\n return alert_data_frame\n\n def update_alerts_on_gsheet(self, date_set, evaluation_date=None, google_sheet='SMARTS_alerts_records', work_sheet='Sheet1'):\n if not evaluation_date:\n evaluation_date = self.evaluation_date\n evaluation_date = str(evaluation_date)\n\n # initialize object with operating google sheet on google drive\n scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(os.getcwd() + '/google_credential.json', scope)\n gs = gspread.authorize(credentials)\n\n gsheet = gs.open(google_sheet)\n wsheet = gsheet.worksheet(work_sheet)\n available_row = self.next_available_row(wsheet)\n daily_alert_counts = date_set['Official'].tolist()\n\n # order mush be matched up with the alert_type listed in google sheet\n wsheet.update_cell(available_row, 1, evaluation_date)\n for index_, alert_count in enumerate(daily_alert_counts):\n wsheet.update_cell(available_row, index_ + 2, alert_count)\n\n def next_available_row(self, worksheet):\n str_list = list(filter(None, worksheet.col_values(1)))\n return len(str_list) + 1\n\n\nif __name__ == '__main__':\n model = AlertsUpdates()\n alerts = model.get_daily_alerts()\n model.update_alerts_on_gsheet(alerts)\n","sub_path":"src/google_drive/AlertsUpdates.py","file_name":"AlertsUpdates.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"385613468","text":"# coding: utf-8\nfrom django.conf import settings\nfrom th_trello.models import Trello\nfrom th_trello.forms import TrelloProviderForm, TrelloConsumerForm\nfrom django_th.tests.test_main import MainTest\n\n\nclass TrelloTest(MainTest):\n\n \"\"\"\n TrelloTest Model\n \"\"\"\n\n def test_get_config_th(self):\n \"\"\"\n does this settings exists ?\n \"\"\"\n self.assertTrue(settings.TH_TRELLO)\n self.assertIn('consumer_key', settings.TH_TRELLO)\n self.assertIn('consumer_secret', settings.TH_TRELLO)\n\n def test_get_config_th_cache(self):\n self.assertIn('th_trello', settings.CACHES)\n\n def test_get_services_list(self):\n th_service = ('th_trello.my_trello.ServiceTrello',)\n for service in th_service:\n self.assertIn(service, settings.TH_SERVICES)\n\n def create_trello(self):\n trigger = self.create_triggerservice(consumer_name='ServiceTrello')\n board_name = 'Trigger Happy'\n list_name = 'To Do'\n status = True\n return Trello.objects.create(trigger=trigger,\n board_name=board_name,\n list_name=list_name,\n status=status)\n\n def test_trello(self):\n t = self.create_trello()\n self.assertTrue(isinstance(t, Trello))\n self.assertEqual(t.show(), \"My Trello %s %s %s\" % (t.board_name,\n t.list_name,\n t.card_title))\n self.assertEqual(t.__str__(), \"%s %s %s\" % (t.board_name,\n t.list_name,\n t.card_title))\n\n \"\"\"\n Form\n \"\"\"\n # provider\n\n def test_valid_provider_form(self):\n t = self.create_trello()\n data = {'board_name': t.board_name, 'list_name': t.list_name}\n form = TrelloProviderForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid_provider_form(self):\n form = TrelloProviderForm(data={})\n self.assertFalse(form.is_valid())\n\n # consumer\n def test_valid_consumer_form(self):\n t = self.create_trello()\n data = {'board_name': t.board_name, 'list_name': t.list_name}\n\n form = TrelloConsumerForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid_consumer_form(self):\n form = TrelloConsumerForm(data={})\n self.assertFalse(form.is_valid())\n\n def test_read_data(self):\n r = self.create_trello()\n from th_trello.my_trello import ServiceTrello\n kwargs = {'trigger_id': r.trigger_id}\n t = ServiceTrello()\n t.read_data(**kwargs)\n data = list()\n self.assertTrue(type(data) is list)\n self.assertTrue('trigger_id' in kwargs)\n\n \"\"\"def test_process_data(self):\n r = self.create_trello()\n from th_trello.my_trello import ServiceTrello\n\n kwargs = {'trigger_id': r.trigger_id}\n\n self.assertTrue('trigger_id' in kwargs)\n\n kw = {'cache_stack': 'th_trello',\n 'trigger_id': str(kwargs['trigger_id'])}\n\n self.assertTrue('cache_stack' in kw)\n self.assertTrue('trigger_id' in kw)\n\n s = ServiceTrello()\n data = s.process_data(**kw)\n\n self.assertTrue(type(data) is list)\"\"\"\n","sub_path":"th_trello/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"603712714","text":"from django.http import HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.utils.decorators import method_decorator\nfrom utility.query_builder import QueryBuilder\nfrom django.views.decorators.csrf import csrf_exempt\nfrom configConstants.messages import Messages\nfrom cerberus import Validator\nfrom utility.request_error_format import request_error_messages_formate\n\n\n# Create your views here.\n\n# This function is used to search cars\n@api_view(['GET'])\ndef search_cars(request):\n try:\n request.page_number = int(request.GET[\"page_number\"]) if request.GET[\"page_number\"] else 0\n request.page_limit = int(request.GET[\"page_limit\"]) if request.GET[\"page_limit\"] else 100\n\n schema = {\n \"search_text\": {'type': 'string', 'required': True, 'empty':True},\n \"page_limit\": {'type': 'integer', 'required': True, 'empty': True},\n \"page_number\": {'type': 'integer', 'required': True, 'empty': True}\n }\n instance = {\n \"search_text\":request.GET['search_text'],\n \"page_limit\": request.page_limit,\n \"page_number\": request.page_number\n }\n v = Validator()\n if not v.validate(instance, schema):\n return Response(request_error_messages_formate(v.errors), status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n return Response({'error':str(e)}, status=status.HTTP_400_BAD_REQUEST)\n try:\n res = []\n page_limit = request.page_limit\n page_number = request.page_number\n db = QueryBuilder()\n db.cursor.callproc('get_car_detail', [request.GET['search_text'],page_limit,page_number])\n result = db.cursor.fetchall()\n for row in result:\n fetchResult={'cars': row[0]}\n res.append(fetchResult)\n if len(res) > 0:\n return Response({'data':res,'message':Messages.RECORD_FOUND}, status=status.HTTP_200_OK)\n else:\n return Response({'data':res,'message':Messages.NO_RECORD_FOUND}, status=status.HTTP_404_NOT_FOUND)\n except Exception as e:\n print(str(e))\n return Response({'error': Messages.SOMETHING_WENT_WRONG}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\n\n \n \n\n\n","sub_path":"cars/car_detail/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"549749238","text":"import logging\nimport logging.config\n\nimport datadog\nimport raven\nimport structlog\n\n\ndef init_app(config):\n setup_logging(config)\n setup_datadog(config)\n client = setup_sentry(config)\n return client\n\n\ndef setup_datadog(config):\n if config.DEBUG:\n return\n\n datadog.statsd.__dict__.update(**config.DATADOG_CONFIG)\n\n\ndef setup_sentry(config):\n return raven.Client(\n dsn=config.SENTRY_DSN, environment=config.DEPLOYMENT_ENV\n )\n\n\ndef setup_logging(config):\n timestamper = structlog.processors.TimeStamper(\n fmt=\"%Y-%m-%d %H:%M:%S\", utc=False\n )\n logging.config.dictConfig(\n {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'logstash': {\n '()': 'logstash_formatter.LogstashFormatterV1',\n },\n 'dev': {\n '()': structlog.stdlib.ProcessorFormatter,\n 'processor': structlog.dev.ConsoleRenderer(\n colors=config.DEBUG\n ),\n 'foreign_pre_chain': [\n structlog.stdlib.add_log_level, timestamper,\n ]\n }\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'dev' if config.DEBUG else 'logstash',\n 'filters': [] if config.DEBUG else []\n }\n },\n 'loggers': {\n '': {\n 'handlers': ['console'],\n 'level': 'DEBUG' if config.DEBUG else 'INFO',\n 'propagate': False,\n },\n 'sanic': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': False\n },\n 'raven': {\n 'handlers': ['console'],\n 'level': 'WARNING',\n 'propagate': False\n },\n 'datadog': {\n 'handlers': ['console'],\n 'level': 'WARNING',\n 'propagate': False,\n },\n 'eventsourcing_helpers': {\n 'handlers': ['console'],\n 'level': 'DEBUG' if config.DEBUG else 'WARNING',\n 'propagate': False,\n },\n 'confluent_kafka_helpers': {\n 'handlers': ['console'],\n 'level': 'DEBUG' if config.DEBUG else 'WARNING',\n 'propagate': False,\n }\n }\n }\n )\n structlog.configure(\n processors=[\n structlog.stdlib.add_log_level,\n timestamper,\n structlog.processors.format_exc_info,\n structlog.stdlib.ProcessorFormatter.wrap_for_formatter,\n ],\n context_class=dict,\n logger_factory=structlog.stdlib.LoggerFactory(),\n wrapper_class=structlog.stdlib.BoundLogger,\n cache_logger_on_first_use=True,\n )\n","sub_path":"app/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"182380891","text":"import numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom algo_dqn import DQN_PARAMS\nfrom algo_dqn import DQN\n\nimport random\nimport math\n\nfrom absl import app\nfrom absl import flags\nimport sys\n\n# possible agents :\nfrom agent_super import SuperAgent\n\nflags.DEFINE_string(\"train\", \"none\", \"Which agent to train.\")\nflags.DEFINE_string(\"directory\", \"none\", \"run directory\")\nflags.DEFINE_string(\"useGpu\", \"True\", \"Which device to run nn on.\")\nflags.DEFINE_string(\"episodes2Train\", \"all\", \"num of episodes to train.\")\nflags.DEFINE_string(\"trainStart\", \"0\", \"num of episodes to train.\")\nflags.DEFINE_string(\"saveLearning\", \"False\", \"if to save offline learning.\")\nflags.DEFINE_string(\"newLearning\", \"False\", \"reset agent learning\")\n\n\ndef StateValues(decisionMaker, numStates = 100):\n \n allValues = []\n for i in range(numStates):\n s = decisionMaker.DrawStateFromHist()\n values = decisionMaker.ActionsValues(s)\n allValues.append(values)\n\n avgValues = np.average(allValues,axis = 0)\n return avgValues\n\ndef FullTrain(decisionMaker, newLearning, saveLearning): \n episodes2Train = flags.FLAGS.episodes2Train\n if episodes2Train == \"all\":\n episodes2Train = math.inf\n else:\n episodes2Train = int(episodes2Train)\n\n print(\"get history\")\n allHist = decisionMaker.historyMngr.GetAllHist().copy()\n \n print(\"reset data\")\n if newLearning:\n decisionMaker.ResetAllData(resetHistory=False) \n decisionMaker.ResetHistory(dump2Old=False)\n # init history mngr and resultFile without saving to files\n print(\"start learning...\\n\\n\")\n\n decisionMaker.historyMngr.__init__(decisionMaker.params)\n decisionMaker.resultFile = None\n history = decisionMaker.AddHistory()\n\n startTrainEpisodeNums = list(map(int, flags.FLAGS.trainStart.split(',')))\n\n episodeNum = 0\n \n idxHist = 0\n rTerminal = []\n rTerminalSum = []\n\n allValues = []\n allValuesEpNum = []\n\n for startEpisodeNum in startTrainEpisodeNums:\n episodeInTrain = 0\n cotinueTrain = True\n while cotinueTrain:\n terminal = False\n steps = 0\n while not terminal:\n s = allHist[\"s\"][idxHist]\n a = allHist[\"a\"][idxHist]\n r = allHist[\"r\"][idxHist]\n s_ = allHist[\"s_\"][idxHist]\n terminal = allHist[\"terminal\"][idxHist]\n \n history.learn(s, a, r, s_, terminal)\n steps += 1\n idxHist += 1\n \n rTerminal.append(r)\n decisionMaker.end_run(r, 0, steps)\n episodeNum += 1\n if episodeNum >= startEpisodeNum:\n episodeInTrain += 1\n if episodeInTrain >= episodes2Train:\n cotinueTrain = False \n\n if decisionMaker.trainFlag:\n if episodeNum >= startEpisodeNum:\n print(\"\\n\\t\\t episode num =\", episodeNum, \"episode in train =\", episodeInTrain)\n decisionMaker.Train()\n print(\"training agent episode #\", episodeNum)\n stateValues = StateValues(decisionMaker)\n allValues.append(stateValues)\n else:\n vals = np.zeros(decisionMaker.params.numActions)\n vals.fill(np.nan)\n allValues.append(vals)\n\n decisionMaker.trainFlag = False\n allValuesEpNum.append(episodeNum)\n\n\n if len(rTerminal) > 200:\n rTerminal.pop(0)\n\n if len(rTerminal) == 200:\n rTerminalSum.append(np.average(rTerminal))\n\n if saveLearning:\n decisionMaker.decisionMaker.Save() \n\n plt.subplot(2,2,1)\n plt.plot(rTerminalSum)\n\n plt.subplot(2,2,2)\n plt.plot(allValuesEpNum, allValues)\n\n plt.subplot(2,2,3)\n plt.plot(allValuesEpNum, np.average(allValues, axis = 1))\n plt.show()\n\nif __name__ == \"__main__\":\n flags.FLAGS(sys.argv)\n\n directoryName = flags.FLAGS.directory\n \n configDict = eval(open(directoryName + \"\\config.txt\", \"r+\").read())\n configDict[\"directory\"] = directoryName\n agent = SuperAgent(configDict=configDict)\n\n useGpu = bool(eval(flags.FLAGS.useGpu))\n saveLearning = bool(eval(flags.FLAGS.saveLearning))\n newLearning = bool(eval(flags.FLAGS.newLearning))\n\n if not useGpu:\n # run from cpu\n import os\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n \n \n\n agentName = flags.FLAGS.train\n\n decisionMaker = agent.decisionMaker.GetDecisionMakerByName(agentName)\n \n if decisionMaker != None: \n print(\"start training...\\n\\n\")\n FullTrain(decisionMaker, newLearning, saveLearning)\n else:\n print(\"error in loading the nn\")\n\n\n \n \n","sub_path":"learnOffline.py","file_name":"learnOffline.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"497236371","text":"# -*- coding: utf-8 -*-\nimport re\nimport unicodedata\nimport sys\nfrom fnmatch import fnmatch, fnmatchcase\n\ndef MyReplace():\n line = 'asdf fjdk; afed, fjek,asdf, foo'\n #ret = re.split(\"[;,\\s]\\s*\", line)\n #ret = re.split(\"(;|,|\\s)\\s*\", line)\n ret = re.split(\"(?:;|,|\\s)\\s*\", line)\n print (ret)\n\n text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'\n # retText, n = re.subn(r'(\\d+)/(\\d+)/(\\d+)', r'\\3-\\2-\\1', text)\n com = re.compile(r'(\\d+)/(\\d+)/(\\d+)')\n retText, n = com.subn( r'\\3-\\2-\\1', text)\n print (retText)\n print (n)\n\ndef FileNameMatch():\n nameList = ['abc.txt', \"ABC.TXT\", 'abC.Txt', 'def.jpg']\n isMatch = fnmatchcase(\"abc.Txt\", \"*.Txt\")\n print [(name for name in nameList if (fnmatch(name, \"*.txt\")))]\n\n print (isMatch)\n\ndef MyGreedRe():\n line = '''a\"sdf fjdk \n \"afed \"fjekasdf \n fo\"o'\n '''\n # comp = re.compile(r\"\\\"(?:.|\\n)*?\\\"\")\n comp = re.compile(r\"\\\".*?\\\"\")\n list = comp.findall(line)\n print (list)\n\ndef MyTranslate():\n s = 'pýtĥöñ\\fis\\tawesome\\r\\n'\n Mymap = {ord('\\f'): \" \",\n ord('\\t'): \" \",\n ord('\\r'): ' '\n }\n\n cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))\n\n b = unicodedata.normalize('NFD', s)\n\n b = b.translate(cmb_chrs)\n print(b)\n\n\ndef main():\n ''' this is test main '''\n MyTranslate()\n\n\n\nif __name__ == \"__main__\":\n #print(\">>%s<<\" %(main.__doc__))\n main()","sub_path":"python/PythonStudy/MyPackage/py_22_translate.py","file_name":"py_22_translate.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"351999240","text":"import re\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport glob\nimport math\nimport matplotlib.ticker as mtick\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.preprocessing import StandardScaler, FunctionTransformer\nfrom sklearn.decomposition import NMF, PCA\nfrom sklearn.pipeline import make_pipeline, make_union, FeatureUnion\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.metrics import confusion_matrix\nfrom sphandles.sphandle import sphandle\n\nplt.style.use('seaborn-notebook')\n\nclass mltrain:\n \n #bootstrapping method\n # parsing DF for test dataset\n @staticmethod\n def holdoutdata(df, perc):\n #making hold out data\n dfnat = df[df.index == 'Natural']\n dfeng = df[df.index == 'Engineered']\n\n msk = np.random.rand(len(dfnat)) < perc\n mske = np.random.rand(len(dfeng)) < perc\n holdoutdatanat = dfnat[~msk]\n holdoutdataeng = dfeng[~mske]\n trainingdatanat = dfnat[msk]\n trainingdataeng = dfeng[mske]\n\n #combining holdout data together and labels\n holdoutdata = pd.concat([holdoutdatanat, holdoutdataeng], axis=0)\n holdoutlabels = holdoutdata.index.get_level_values(level='newlabel')\n return holdoutdata, holdoutlabels, trainingdatanat, trainingdataeng\n \n @staticmethod\n def plot_confusion_matrix(y_true, y_pred, classes,\n normalize=False,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n\n # Compute confusion matrix\n cm = confusion_matrix(y_true, y_pred, classes)\n \n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n title=title,\n ylabel='True label',\n xlabel='Predicted label')\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax\n\n @staticmethod\n def evaluate_model(clf, df, labels):\n model_name = '->'.join(next(zip(*clf.steps)))\n print(\"Model: %s\" % model_name)\n scores = cross_val_score(clf, df, labels, cv=3)\n mean_score = scores.mean()\n std_score = scores.std()\n print(\"Accuracy: [%0.4f, %0.4f] (%0.4f +/- %0.4f)\"\n % (mean_score - std_score, mean_score + std_score, mean_score, std_score))\n y_pred = cross_val_predict(clf, df, labels, cv=3)\n y_prob = cross_val_predict(clf, df, labels, cv=3, method='predict_proba')\n mltrain.plot_confusion_matrix(labels, y_pred, labels.unique())\n return y_pred, y_prob, labels, df\n\n @staticmethod\n def evaluate_modelrfe(clf, df, labels):\n model_name = '->'.join(next(zip(*clf.steps)))\n print(\"Model: %s\" % model_name)\n scores = cross_val_score(clf, df, labels, cv=3)\n mean_score = scores.mean()\n std_score = scores.std()\n print(\"Accuracy: [%0.4f, %0.4f] (%0.4f +/- %0.4f)\"\n % (mean_score - std_score, mean_score + std_score, mean_score, std_score))\n y_pred = cross_val_predict(clf, df, labels, cv=3)\n y_prob = cross_val_predict(clf, df, labels, cv=3, method='predict')\n return y_pred, y_prob, labels, df\n\n \n @staticmethod\n def graphmaker(df, label, upperbound, name, natdf, savefigs, opencircles = False):\n toppercent = sphandle.conditional_probabilities(sphandle.just_data(df[df[label] > upperbound]), '48Ti')\n bottompercent = sphandle.conditional_probabilities(sphandle.just_data(df[df[label] < upperbound]), '48Ti')\n percentdf = pd.DataFrame([toppercent, bottompercent]).T\n percentdf.columns = ['toppercent', 'bottompercent']\n percentdf.reset_index(inplace = True)\n percentdf = pd.melt(percentdf[1:13], id_vars = ['index'], value_vars = ['toppercent', 'bottompercent'])\n\n fig, axs = plt.subplots(1, 2, figsize=(16,4), dpi=300, gridspec_kw={'width_ratios': [2.5, 1]})\n ax1 = sns.barplot('index', 'value', 'variable', data = percentdf, ax = axs[0], palette = ['green', 'orange', 'red'])\n ax1.set_ylabel('Isotope Frequency', fontsize = 16)\n ax1.tick_params(axis='both', which='major', labelsize=14)\n ax1.set_xlabel('')\n ax1.set_ylim([10**-3, 1])\n ax1.legend_.remove()\n ax1.set_yscale('log')\n\n #if you want unassociated Ti as a separate category\n if opencircles == True:\n #make the df pure ti df\n Pure = sphandle.isotope_pure(sphandle.just_data(df).drop(columns = '46Ti'), '48Ti')\n percentdfpure = df.loc[Pure.index]\n df.drop(percentdfpure.index, inplace = True)\n\n #parse particles by confidence probability to the correct category\n top = df[df[label] > upperbound]\n puretop = percentdfpure[percentdfpure[label] > upperbound]\n bot = df[df[label] < upperbound]\n purebot = percentdfpure[percentdfpure[label] < upperbound]\n \n axs[1].scatter(bot['48Ti'], bot[label], linewidths = 0.75, edgecolors = 'white', facecolors = 'orange')\n axs[1].scatter(top['48Ti'], top[label], linewidths = 0.75, edgecolors = 'white', facecolors = 'green')\n axs[1].scatter(purebot['48Ti'], purebot[label], linewidths = 0.75, edgecolors = 'orange', facecolors = 'white')\n axs[1].scatter(puretop['48Ti'], puretop[label], linewidths = 0.75, edgecolors = 'green', facecolors = 'white')\n axs[1].set_xscale('log')\n axs[1].yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n axs[1].set_xlim([min(natdf['48Ti']), 10**-13])\n axs[1].set_xlabel('Ti Mass (g)')\n axs[1].set_ylabel('Prediction Probability of ' + str(label) + ' Category')\n axs[1].set_ylim(0.0)\n if savefigs == None:\n plt.savefig('figures/fingerprints' + str(label) + str(name) + '.png', dpi = 300)\n \n @staticmethod\n def graphmakerm(df, label, upperbound, lowerbound, name, natdf, savefigs, opencircles = False):\n toppercent = sphandle.conditional_probabilities(sphandle.just_data(df[df[label] > upperbound]), '48Ti')\n middlepercent = df[df[label] < upperbound]\n middlepercent = sphandle.conditional_probabilities(sphandle.just_data(middlepercent[middlepercent[label] > lowerbound]), '48Ti')\n bottompercent = sphandle.conditional_probabilities(sphandle.just_data(df[df[label] < lowerbound]), '48Ti')\n percentdf = pd.DataFrame([toppercent, middlepercent, bottompercent]).T\n percentdf.columns = ['toppercent', 'middlepercent', 'bottompercent']\n percentdf.reset_index(inplace = True)\n percentdf = pd.melt(percentdf[1:13], id_vars = ['index'], value_vars = ['toppercent', 'middlepercent', 'bottompercent'])\n\n fig, axs = plt.subplots(1, 2, figsize=(18,4), dpi=300, gridspec_kw={'width_ratios': [3, 1]})\n ax1 = sns.barplot('index', 'value', 'variable', data = percentdf, palette = 'Blues', ax = axs[0])\n ax1.set_ylabel('Isotope Frequency')\n ax1.tick_params(axis='both', which='major', labelsize=12)\n ax1.set_xlabel('')\n ax1.legend_.remove()\n ax1.set_yscale('log')\n\n #if opencircles == True:\n #Pure = isotope_pure(just_data(df).drop(columns = '46Ti'), label)\n\n top = df[df[label] > upperbound]\n top['category'] = 'Top ' + str(100-upperbound*100) + '%'\n middle = df[df[label] < upperbound]\n middle = middle[middle[label] > lowerbound]\n middle['category'] = 'Middle' + str((upperbound - lowerbound)*100) + '%'\n bot = df[df[label] < lowerbound]\n bot['category'] = 'Bottom ' + str(upperbound*100) + '%'\n\n\n df = pd.concat([bot, middle, top], axis = 0)\n\n ax2 = sns.scatterplot('48Ti', label, 'category', data = df, palette = 'Blues_d', ax = axs[1])\n Pure = sphandle.isotope_pure(sphandle.just_data(df).drop(columns = '46Ti'), '48Ti')\n percentdfpure = df.loc[Pure.index]\n ax2 = sns.scatterplot('48Ti', label, 'category', data = percentdfpure, palette = 'Blues_d', ax = axs[1], markers= '+')\n ax2.set_xscale('log')\n ax2.set_xlim([min(natdf['48Ti']), 10**-13])\n ax2.set_xlabel('Ti Mass (g)')\n ax2.legend_.remove()\n ax2.set_ylabel('Prediction Probability of ' + str(label) + ' Category')\n if savefigs == None:\n plt.savefig('figures/fingerprints' + str(label) + str(name) + '.png', dpi = 300)\n\n @staticmethod\n #This is to get the specific Ti column in the sample data frame. Please specify which index the column lies in. For this specific set of columns, it is 6. \n def get_ti(x):\n return x[:, [6]]\n\n @staticmethod\n def MLsimulation(data, keys, labels, iterations, tolerance, naturalkeys, engineeredkeys, flag, savefigs, returns = None):\n \n print(keys, pd.DataFrame(np.ones_like(labels), columns=['count'], index=labels).groupby('newlabel').sum())\n #hold out some data for testing\n holdoutdata1, holdoutlabels, trainingdatanat, trainingdataeng = mltrain.holdoutdata(data, 0.8)\n #combine the left out training dataset and heldout labels. \n trainingdata = pd.concat([trainingdatanat, trainingdataeng], axis=0)\n traininglabels = trainingdata.index.get_level_values(level='newlabel')\n\n #Logistic Regression with NMF and StandardScalar\n clf = make_pipeline(\n StandardScaler(with_mean=False),\n FeatureUnion([('nmf', NMF(n_components = 10)), \n ('functiontransformer', FunctionTransformer(mltrain.get_ti))\n ]),\n LogisticRegressionCV(tol=tolerance, cv=5, max_iter=iterations)\n )\n y_pred, y_prob, y_true, df = mltrain.evaluate_model(clf, trainingdata, traininglabels)\n if savefigs == None:\n plt.savefig('figures/confusionmatrix' + str(keys) + '.png', dpi =300)\n\n #fitting the model given the trained dataset\n clf = clf.fit(df, traininglabels)\n #predict the probability of trained datapoint\n y_prob = clf.predict_proba(df)\n #get the test_score of the test dataset\n test_score = clf.score(holdoutdata1, holdoutlabels)\n #print('test score: ' + str(test_score * 100))\n\n #Analyze trained components\n compcoeff = clf.named_steps['logisticregressioncv'].coef_ \n nmf = clf.named_steps['featureunion'].transformer_list[0][1]\n comps = pd.DataFrame(nmf.components_.T, index=data.columns)\n\n Ticolumn = np.zeros((clf.named_steps['featureunion'].transformer_list[0][1].components_[0].shape))\n Ticolumn[5] = 1\n Ticolumndf = pd.DataFrame(Ticolumn.T, index=data.columns)\n comps = pd.concat([comps, Ticolumndf], axis = 1)\n comps.columns = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Ti']\n \n #multiply coefficient by componenets\n multipliedcomps = (compcoeff[0] * comps)\n\n\n #Loading dataset with prob_obs_group\n label_prob = pd.DataFrame(y_prob, columns=sorted(labels.unique()))\n df_with_prob = df.reset_index().join(label_prob)\n df_with_prob['prob_obs_group'] = df_with_prob.Natural.apply(lambda p: float(\"{:0.1f}\".format(p))) \n df_with_prob.append(df_with_prob)\n\n #Multiply the occurence of the element with the Ti particles by the importance\n multipliedcompscor =multipliedcomps.apply(lambda x: x *\n sphandle.conditional_probabilities(\n sphandle.just_data(df_with_prob), '48Ti')).reindex(multipliedcomps.index).sum(axis=1)\n\n mc = sphandle.non_zero_data(pd.DataFrame(multipliedcompscor))\n mc['label'] = ['Eng' if mc.loc[i,0] < 0 else 'Nat' for i in mc.index]\n mc[0] = abs(mc[0])\n\n color = []\n for i in mc.sort_values(by = 0, ascending = False)['label']:\n if i == 'Nat':\n color.append('r')\n else:\n color.append('b')\n\n\n fig, ax = plt.subplots(1,1, figsize = [7,3], dpi = 300)\n ax.barh(mc.sort_values(by = 0, ascending = False)[:10].index, mc.sort_values(by = 0, ascending = False)[:10][0], color = color)\n ax.text(0.9, 0.9, keys, horizontalalignment = 'right', verticalalignment = 'center', transform = ax.transAxes)\n ax.set_xlabel('Magnitude')\n\n plt.tight_layout()\n if savefigs == None:\n plt.savefig('figures/elementalimportance' + str(keys) + '.png', dpi = 300) \n\n\n #Finding the composition of Misclassification\n Nat_df_with_prob = df_with_prob[df_with_prob['newlabel'] == 'Natural']\n Nat_df_with_prob_mis = Nat_df_with_prob[Nat_df_with_prob['Natural'] < 0.5]\n Eng_df_with_prob = df_with_prob[df_with_prob['newlabel'] == 'Engineered']\n Eng_df_with_prob_mis = Eng_df_with_prob[Eng_df_with_prob['Engineered'] < 0.5]\n\n #Printing the size distribution of natural and engineered\n print(naturalkeys, (((( Nat_df_with_prob['48Ti']*(48+32)/48)/ 4.23 * 10 **21)*6/math.pi)**(1/3)).mean(), \n ((((Nat_df_with_prob['48Ti']*(48+32)/48)/ 4.23 * 10 **21)*6/math.pi)**(1/3)).std())\n print(engineeredkeys, (((( Eng_df_with_prob['48Ti']*(48+32)/48)/ 4.23 * 10 **21)*6/math.pi)**(1/3)).mean(), \n ((((Eng_df_with_prob['48Ti']*(48+32)/48)/ 4.23 * 10 **21)*6/math.pi)**(1/3)).std())\n\n #Printing purity of TiO2 of natural and engineered\n print(naturalkeys, sphandle.probability_pure(sphandle.just_data(Nat_df_with_prob).drop(columns = '46Ti'), '48Ti'))\n print(engineeredkeys, sphandle.probability_pure(sphandle.just_data(Eng_df_with_prob).drop(columns = '46Ti'), '48Ti'))\n\n\n #Finding the composition of Misclassification\n Nat_df_with_prob = df_with_prob[df_with_prob['newlabel'] == 'Natural']\n Eng_df_with_prob = df_with_prob[df_with_prob['newlabel'] == 'Engineered']\n Nat = sphandle.category_split(Nat_df_with_prob, 'Natural', 0.85, 0.15)\n Eng = sphandle.category_split(Eng_df_with_prob, 'Engineered', 0.85, 0.15)\n total_correct = (len(Nat[0]) + len(Eng[0]))/ len(df_with_prob)\n total_engcorrect = (len(Eng[0]))/ len(Eng_df_with_prob)\n total_uncertain = (len(Nat[1]) + len(Eng[1]))/ len(df_with_prob)\n total_mis = (len(Nat[2]) + len(Eng[2]))/ len(df_with_prob)\n print('Total correct = ' + str(total_correct))\n print('Total Engineered Correct =' + str(total_engcorrect))\n print('Total uncertain = ' + str(total_uncertain))\n print('Total misclassified = ' + str(total_mis))\n piechart_data = [total_correct, total_uncertain, total_mis]\n #piechart_data_labels = 'Classified', 'Uncertain', 'Misclassified'\n\n #get the top and bottom percent of Nat and Eng\n #parse particles by confidence probability to the correct category\n Nat_df_pure = Nat_df_with_prob.loc[sphandle.isotope_pure(sphandle.just_data(Nat_df_with_prob).drop(columns = '46Ti'), '48Ti').index]\n Eng_df_pure = Eng_df_with_prob.loc[sphandle.isotope_pure(sphandle.just_data(Eng_df_with_prob).drop(columns = '46Ti'), '48Ti').index]\n\n topnat = Nat_df_with_prob[Nat_df_with_prob['Natural'] > 0.85]\n puretopnat = Nat_df_pure[Nat_df_pure['Natural'] > 0.85]\n botnat = Nat_df_with_prob[Nat_df_with_prob['Natural'] < 0.85]\n purebotnat = Nat_df_pure[Nat_df_pure['Natural'] < 0.85]\n\n topeng = Eng_df_with_prob[Eng_df_with_prob['Engineered'] > 0.85]\n puretopeng = Eng_df_pure[Eng_df_pure['Engineered'] > 0.85]\n boteng = Eng_df_with_prob[Eng_df_with_prob['Engineered'] < 0.85]\n pureboteng = Eng_df_pure[Eng_df_pure['Engineered'] < 0.85]\n\n #Plot Ti\n xy_line = (0.15, 0.15)\n yz_line = (0.85, 0.85)\n fig, axs = plt.subplots(1, 3, figsize=(16,5), dpi=300)\n #axs[0].scatter(Nat_df_with_prob.loc[:,'48Ti'], Nat_df_with_prob.loc[:,'Natural'], color = 'brown')\n axs[0].scatter(topnat['48Ti'], topnat['Natural'], linewidths = 0.75, edgecolors = 'white', facecolors = 'green')\n axs[0].scatter(puretopnat['48Ti'], puretopnat['Natural'], linewidths = 0.75, edgecolors = 'green', facecolors = 'white')\n axs[0].scatter(botnat['48Ti'], botnat['Natural'], linewidths = 0.75, edgecolors = 'white', facecolors = 'orange')\n axs[0].scatter(purebotnat['48Ti'], purebotnat['Natural'], linewidths = 0.75, edgecolors = 'orange', facecolors = 'white')\n axs[0].set_xlim(min(Nat_df_with_prob['48Ti']), 1E-13)\n axs[0].set_xscale('log')\n axs[0].set_xlabel('Ti Mass (g)', fontsize = 16)\n axs[0].tick_params(axis = 'both', which = 'major', labelsize = 18)\n #axs[0].set_ylabel('Prediction probability of Natural category', fontsize = 16)\n axs[0].yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n axs[0].set_title(naturalkeys)\n axs[0].plot(yz_line, 'r--', color = 'black')\n axs[0].set_ylim(0.0, 1.1)\n plt.legend(labels, loc='best')\n #axs[1].scatter(Eng_df_with_prob.loc[:,'48Ti'], Eng_df_with_prob.loc[:,'Engineered'], color = 'blue')\n axs[1].scatter(topeng['48Ti'], topeng['Engineered'], linewidths = 0.75, edgecolors = 'white', facecolors = 'green')\n axs[1].scatter(puretopeng['48Ti'], puretopeng['Engineered'], linewidths = 0.75, edgecolors = 'green', facecolors = 'white')\n axs[1].scatter(boteng['48Ti'], boteng['Engineered'], linewidths = 0.75, edgecolors = 'white', facecolors = 'orange')\n axs[1].scatter(pureboteng['48Ti'], pureboteng['Engineered'], linewidths = 0.75, edgecolors = 'orange', facecolors = 'white')\n axs[1].set_xlim(min(Nat_df_with_prob['48Ti']), 1E-13)\n axs[1].set_xscale('log')\n axs[1].set_xlabel('Ti Mass (g)', fontsize = 16)\n axs[1].tick_params(axis = 'both', which = 'major', labelsize = 18)\n #axs[1].set_ylabel('Prediction probability of Engineered category', fontsize = 16)\n axs[1].yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n axs[1].set_title(engineeredkeys)\n axs[1].plot(yz_line, 'r--', color = 'black')\n axs[1].set_ylim(0.0, 1.1)\n fig.tight_layout()\n\n axs[2].pie(piechart_data, colors = ['green', 'orange', 'red'])\n axs[2].axis('equal')\n fig.set_facecolor('white')\n if savefigs == None:\n plt.savefig('figures/Timass' + str(keys) + '.png', dpi =500)\n\n topnat= sphandle.conditional_probabilities(sphandle.just_data(Nat_df_with_prob), '48Ti')[2:12]\n topeng= sphandle.conditional_probabilities(sphandle.just_data(Eng_df_with_prob), '48Ti')[2:12]\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,5), dpi=300)\n ax1.bar(topnat.index, topnat)\n ax1.set_ylabel('Isotope Frequency')\n ax1.tick_params(axis='both', which='major', labelsize=12)\n\n ax2.bar(topeng.index, topeng)\n ax2.set_ylabel('Isotope Frequency')\n ax2.tick_params(axis='both', which='major', labelsize=12)\n\n fig.tight_layout\n if savefigs == None:\n plt.savefig('figures/isotopes' + str(keys) + '.png', dpi = 300)\n\n if flag == 1:\n mltrain.graphmaker(Nat_df_with_prob, 'Natural', 0.85, keys, Nat_df_with_prob, savefigs, opencircles = True)\n mltrain.graphmaker(Eng_df_with_prob, 'Engineered', 0.85, keys, Nat_df_with_prob, savefigs, opencircles = True)\n else:\n mltrain.graphmakerm(Nat_df_with_prob, 'Natural', 0.85, 0.5, keys, Nat_df_with_prob, savefigs, opencircles = True)\n mltrain.graphmakerm(Eng_df_with_prob, 'Engineered', 0.85, 0.5, keys, Nat_df_with_prob, savefigs, opencircles = True)\n\n\n if returns != None:\n return clf, df_with_prob, multipliedcomps, df, labels\n\n\n #bootstrapping process. Holdout some data, predict on it and do that N amount of times. Repeated this procedure M amount of times\n @staticmethod\n def bootstrap(df, N, m):\n #repeat this process M amount of times\n for _ in range(m):\n #holdout 20% of data. \n holdoutdata, holdoutlabels, trainingdatanat, trainingdataeng = mltrain.holdoutdata(df, 0.2)\n #create a NP array from 0.05 to 1.05 with 0.05 step increment\n p = np.arange(0.05, 1.05, 0.05)\n #create an empty dataframe\n df1 = pd.DataFrame()\n #for each 0.05 step from p\n for i in p:\n #create an empty list\n percent = []\n #repeat this N amount of times\n for _ in range(N):\n #sample an i fraction of the training data\n snat = trainingdatanat.sample(frac = i, replace = True)\n seng = trainingdataeng.sample(frac = i, replace = True)\n\n #combine training data and get traininglabels\n\n trainingdata = pd.concat([snat, seng], axis=0)\n traininglabels = trainingdata.index.get_level_values(level='newlabel')\n\n #create the logistic Regression model with 5-fold cross validation with NMF of 10 componenets\n\n clf = make_pipeline(\n StandardScaler(with_mean=False),\n NMF(n_components=10),\n LogisticRegressionCV(cv=5, max_iter=300)\n )\n #fit with fraction of training set\n clf = clf.fit(trainingdata, traininglabels)\n #score with the heldout test set\n y_score = clf.score(holdoutdata, holdoutlabels)\n #append the score to percent\n percent.append(y_score)\n #put it in a dataframe format\n pcdf = pd.DataFrame(percent)\n df1 = pd.concat([df1, pcdf], axis = 1)\n\n df1.columns = np.arange(0.05, 1.05, 0.05)\n\n average = []\n stdev = []\n for i in df1.columns:\n average.append(df1[i].mean())\n stdev.append(df1[i].std())\n plt.errorbar(np.arange(0.05, 1.05, 0.05), average, yerr = stdev)\n plt.xlabel('% of training data')\n plt.ylabel('Accuracy of model (%)')\n \n @staticmethod\n def pca_analysis(df, label):\n pca = PCA()\n X = pca.fit_transform(df)\n x1 = X[:, 0]\n x2 = X[:, 1]\n\n fig, ax = plt.subplots()\n ax.plot(x1, x2, '.')\n ax.set(\n xlabel=\"First component\",\n ylabel=\"Second component\",\n title=\"%s: projected onto first two components\" % label,\n )\n\n components = pd.DataFrame(pca.components_.T, index=df.columns)\n print_until = 0.9999\n cumulative_explained_variance = 0\n i = 0\n while cumulative_explained_variance < print_until:\n explained = pca.explained_variance_ratio_[i]\n print(\"=> COMPONENT %d explains %0.2f%% of the variance\" % (i, 100*explained))\n top_components = components[i].sort_values(ascending=False)\n top_components = top_components[abs(top_components) > 0.0]\n print(top_components)\n i += 1\n cumulative_explained_variance += explained\n return components","sub_path":"src/sphandles/ML_Train.py","file_name":"ML_Train.py","file_ext":"py","file_size_in_byte":24613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"217562408","text":"count = 0\r\nnp = 0\r\n\r\nwhile True:\r\n while True:\r\n try:\r\n num = int(input(\"Digite um número inteiro maior que 0: \"))\r\n\r\n count += 1 #contador de números digitados\r\n\r\n if num % 2 == 1 and num >=3:\r\n print(\"{} é um número primo\".format(num))\r\n np += 1 #contador de números primos\r\n\r\n else:\r\n print(\"{} não é número primo\".format(num))\r\n break\r\n except:\r\n print(\"\\nERRO: Digite apenas valor númerico\")\r\n\r\n\r\n\r\n resp = input(\"\\nDeseja digitar outro número ? (S/N): \")\r\n if resp.upper() != \"S\":\r\n print(\"Programa encerrado!\")\r\n break\r\nprint(\"Quantidade de números digitados: {}\".format(count))\r\nprint(\"\\nQuantidade de números primos digitados: {}\".format(np))\r\n","sub_path":"Exercicio 2 - Numeros primos.py","file_name":"Exercicio 2 - Numeros primos.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"149846458","text":"# 给定一个可包含重复数字的序列,返回所有不重复的全排列。 \n# \n# 示例: \n# \n# 输入: [1,1,2]\n# 输出:\n# [\n# [1,1,2],\n# [1,2,1],\n# [2,1,1]\n# ] \n# Related Topics 回溯算法 \n# 👍 372 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n res = []\n\n def bk(nums, tem):\n if not nums:\n res.append(tem)\n return\n visi = set()\n for i in range(len(nums)):\n if nums[i] in visi:\n continue\n else:\n bk(nums[:i] + nums[i + 1:], tem + [nums[i]])\n visi.add(nums[i])\n\n bk(nums, [])\n return res\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_03/[47]全排列 II.py","file_name":"[47]全排列 II.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"390774143","text":"class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n\n def recur(s,t):\n if t == \"\": # t遍历完了,说明完成了匹配,因为只有前面的字符匹配了,t才会往下走,如\"babgbag\",和\"t\",程序结束,\"t\"都没有遍历\n return 1\n elif s == \"\": # s串遍历完了,t不为空,说明t还没有匹配完\n return 0\n ans = 0\n for i in range(len(s)):\n if s[i] == t[0]:\n ans += recur(s[i + 1 : ], t[1 : ])\n return ans\n\n return recur(s,t)\n\n\n\n def numDistinct1(self, s: str, t: str) -> int:\n s = \" \" + s\n t = \" \" + t\n size_s = len(s)\n size_t = len(t)\n dp = [[0 for j in range(size_s)] for i in range(size_t)]\n\n for col in range(size_s): # 第一行和第一列初始化,第一列除了[0][0]为1,其他的默认都是0\n dp[0][col] = 1\n\n for row in range(1, size_t):\n for col in range(1, size_s):\n if s[col] != t[row]:\n dp[row][col] = dp[row][col - 1]\n elif s[col] == t[row]:\n dp[row][col] = dp[row][col - 1] + dp[row - 1][col - 1]\n return dp[-1][-1]\n\n\n\n\nprint(Solution().numDistinct1(\"baf\", \"\"))\n","sub_path":"动态规划dp/115. 不同的子序列.py","file_name":"115. 不同的子序列.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"648616131","text":"#!C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37\\python.exe\r\nprint(\"Content-type:text/html\\n\")\r\n\r\n#print(\"Content-type:image/png\\n\")\r\n\r\nimport pymysql as pms\r\nconn = pms.connect(\"localhost\",\"root\",\"mysroot\",\"finaln\")\r\na=conn.cursor()\r\nb=conn.cursor()\r\n\r\nq1=\"select adaptability from file where username = (select user_name from curr_user)\";\r\na.execute(q1)\r\ndata1=a.fetchall()\r\n\r\nimport os\r\nimport cgi\r\nimport cgitb; cgitb.enable();\r\nos.environ['HOME'] = '/tmp/'\r\n\r\nab=[]\r\nperform=[]\r\nfor i in range(0,len(data1)):\r\n ab.append(data1[i][0])\r\n perform.append(f\"Task{i}\")\r\nprint (ab)\r\nprint(perform)\r\n\r\nfrom matplotlib.pyplot import figure\r\nimport mpld3\r\nfig = figure()\r\nax = fig.gca()\r\nax.bar(perform,ab,tick_label=perform)\r\nmpld3.show(fig)\r\n\r\n\r\n","sub_path":"ProgressGraphsPython/ada.py","file_name":"ada.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380496784","text":"import nltk\nfrom nltk.tokenize import word_tokenize\nimport random\nfrom nltk.classify.scikitlearn import SklearnClassifier\nimport pickle\n\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\n\nprint(\"Reading training corpus...\")\n\npositive = open(\"raw/positive.txt\", \"r\").read()\nnegative = open(\"raw/negative.txt\", \"r\").read()\n\nprint(\"Building documents and words...\")\n\nall_words = []\ndocuments = []\n\n# j is adject, r is adverb, and v is verb\n# allowed_word_types = [\"J\",\"R\",\"V\"]\nallowed_word_types = [\"J\"]\n\nfor p in positive.split(\"\\n\"):\n documents.append((p, \"pos\"))\n words = word_tokenize(p)\n pos = nltk.pos_tag(words)\n for w in pos:\n if w[1][0] in allowed_word_types:\n all_words.append(w[0].lower())\n\nfor n in negative.split(\"\\n\"):\n documents.append((n, \"neg\"))\n words = word_tokenize(n)\n pos = nltk.pos_tag(words)\n for w in pos:\n if w[1][0] in allowed_word_types:\n all_words.append(w[0].lower())\n\nprint(\"Saving documents...\")\n\nsave_documents = open(\"pickled/documents.pickle\", \"wb\")\npickle.dump(documents, save_documents)\nsave_documents.close()\n\nall_words = nltk.FreqDist(all_words)\n\nword_features = list(all_words.keys())[:5000]\n\nprint(\"Saving words...\")\n\nsave_word_features = open(\"pickled/word_features5k.pickle\", \"wb\")\npickle.dump(word_features, save_word_features)\nsave_word_features.close()\n\n\ndef find_features(document):\n words = word_tokenize(document)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n\n return features\n\n\nfeaturesets = [(find_features(rev), category) for (rev, category) in documents]\nrandom.shuffle(featuresets)\n\nsave_featureset = open(\"pickled/featuresets.pickle\", \"wb\")\npickle.dump(featuresets, save_featureset)\nsave_featureset.close()\n\nprint(\"Feature-set created of length ->\", len(featuresets))\n\ntraining_set = featuresets[:10000]\ntesting_set = featuresets[10000:]\n\nprint(\"Starting training different algorithms...\")\n\norig_classifier = nltk.NaiveBayesClassifier.train(training_set)\nprint(\"Original_classifier Accuracy ->\", (nltk.classify.accuracy(orig_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/originalnaivebayes5k.pickle\", \"wb\")\npickle.dump(orig_classifier, save_classifier)\nsave_classifier.close()\n\nMNB_classifier = SklearnClassifier(MultinomialNB())\nMNB_classifier.train(training_set)\nprint(\"MNB_classifier Accuracy ->\", (nltk.classify.accuracy(MNB_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/MNB_classifier5k.pickle\", \"wb\")\npickle.dump(MNB_classifier, save_classifier)\nsave_classifier.close()\n\nBernoulliNB_classifier = SklearnClassifier(BernoulliNB())\nBernoulliNB_classifier.train(training_set)\nprint(\"BernoulliNB_classifier Accuracy ->\", (nltk.classify.accuracy(BernoulliNB_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/BernoulliNB_classifier5k.pickle\", \"wb\")\npickle.dump(BernoulliNB_classifier, save_classifier)\nsave_classifier.close()\n\nLogisticRegression_classifier = SklearnClassifier(LogisticRegression())\nLogisticRegression_classifier.train(training_set)\nprint(\"LogisticRegression_classifier Accuracy ->\", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/LogisticRegression_classifier5k.pickle\", \"wb\")\npickle.dump(LogisticRegression_classifier, save_classifier)\nsave_classifier.close()\n\nSGDClassifier_classifier = SklearnClassifier(SGDClassifier())\nSGDClassifier_classifier.train(training_set)\nprint(\"SGDClassifier_classifier Accuracy ->\", (nltk.classify.accuracy(SGDClassifier_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/SGDC_classifier5k.pickle\", \"wb\")\npickle.dump(SGDClassifier_classifier, save_classifier)\nsave_classifier.close()\n\n# SVC_classifier = SklearnClassifier(SVC())\n# SVC_classifier.train(training_set)\n# print(\"SVC_classifier Accuracy ->\", (nltk.classify.accuracy(SVC_classifier, testing_set))*100)\n\nLinearSVC_classifier = SklearnClassifier(LinearSVC())\nLinearSVC_classifier.train(training_set)\nprint(\"LinearSVC_classifier Accuracy ->\", (nltk.classify.accuracy(LinearSVC_classifier, testing_set)) * 100)\n\nsave_classifier = open(\"pickled/LinearSVC_classifier5k.pickle\", \"wb\")\npickle.dump(LinearSVC_classifier, save_classifier)\nsave_classifier.close()\n\n# NuSVC_classifier = SklearnClassifier(NuSVC())\n# NuSVC_classifier.train(training_set)\n# print(\"NuSVC_classifier Accuracy ->\", (nltk.classify.accuracy(NuSVC_classifier, testing_set)) * 100)\n\n# custom_classifier = CustomClassifier(SGDClassifier, LinearSVC_classifier, LogisticRegression_classifier,\n# BernoulliNB_classifier, MNB_classifier)\n# print(\"Custom_classifier Accuracy ->\", (nltk.classify.accuracy(custom_classifier, testing_set)) * 100)\n","sub_path":"SentimentAnalysis/Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"357496856","text":"\"\"\"disclaimer: this code is provide as is.\nfeel free to copy, modify or reuse it\n\"\"\"\nimport matplotlib\n# Make sure that we are using QT5\nmatplotlib.use('Qt5Agg')\nfrom PySide2 import QtCore, QtWidgets\nfrom numpy import arange, sin, pi\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n\nclass Scope(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\n\n def __init__(self, parent=None, width=5, height=4, dpi=100, refresh_period=1000,share_data=None):\n self.fig = Figure(figsize=(width, height), dpi=dpi)\n self.share_data=share_data\n self.axes = self.fig.add_subplot(111)\n FigureCanvas.__init__(self, self.fig)\n FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n self.timer = QtCore.QTimer(self)\n self.timer.timeout.connect(self.update_data)\n self.timer.start(refresh_period)\n def int_plot(self):\n n=10 ##DataShare.get_xlim()\n self.axes.plot([0]*n)\n self.draw() \n def update_data(self):\n data=self.share_data.get_data()\n self.axes.cla()\n if len(data)!=0:\n self.axes.plot(data[0])\n self.draw()\n def change_refresh_periode(self, period):\n self.timer.stop()\n self.timer.setInterval(period)\n self.timer.start()\n \n \n","sub_path":"scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554984065","text":"from django.db import models\nfrom club.models import Club\nfrom terrain.models import Terrain\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\ndef check_maximum(count, maximum):\n if count >= maximum:\n raise ValidationError(\"Course is full.\")\n\n\n# Create your models here.\n@python_2_unicode_compatible\nclass Course(models.Model):\n name = models.CharField(max_length=64, blank=False, help_text=\"The name of the course.\")\n start_date = models.DateTimeField(auto_now_add=True,\n help_text=\"The start date of the course in format dd/mm/yyyy hh:mm:ss.\")\n interval = models.IntegerField(default=7, verbose_name='interval',\n help_text=\"The weekly interval of a course (e.g. 1x a week = 7).\")\n sessions = models.IntegerField(default=10,verbose_name='sessions',\n help_text=\"The amount of sessions a course has.\")\n maximum = models.IntegerField(default=4, verbose_name='maximum',\n help_text=\"The maximum amount of students a course has.\")\n price = models.IntegerField(default=100, verbose_name='price',\n help_text='The price of the course in total.This amount will be divided by the amount of participants.')\n tutor = models.ForeignKey(settings.AUTH_USER_MODEL,\n editable=False,\n verbose_name='tutor',\n related_name='tutor',\n null=False,\n help_text=\"The tutor of the course.\"\n )\n club = models.ForeignKey(Club,\n editable=True,\n verbose_name='course',\n related_name='courses',\n null=False,\n help_text=\"The club a course is given at.\"\n )\n terrain = models.ForeignKey(Terrain,\n editable=True,\n verbose_name='terrain',\n related_name='terrain',\n null=False,\n help_text=\"The terrain a course takes place at.\"\n )\n\n students = models.ManyToManyField(settings.AUTH_USER_MODEL, editable=True,\n related_name='students',\n verbose_name='students',\n null=True,\n help_text='The students of the course.')\n\n def __str__(self):\n return \"%s at %s\" % (self.name, self.club)\n\n","sub_path":"tennis_factory/course/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"233690240","text":"import discord\nimport os\n\nfrom replit import db\nfrom dotenv import load_dotenv\nfrom discord.ext import commands, tasks\n\nfrom keep_alive import keep_alive\n\nload_dotenv()\nTOKEN = os.getenv(\"TOKEN\")\n\nbot = commands.Bot(\n command_prefix=\"!\",\n description=\"Bark bot is a general purpose bot.\")\n\n@bot.event\nasync def on_ready():\n activity = discord.Game(name=\"!help\")\n await bot.change_presence(status=discord.Status.online, activity=activity)\n print(\"Bot is ready!\")\n\n@bot.command(name=\"server\", help=\"Gets support server link\")\nasync def server(ctx):\n await ctx.send(\"https://discord.gg/Tayz2DWE2D\")\n\nkeep_alive()\n\nbot.run(TOKEN)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"572782738","text":"\"\"\"02 Question GUI version 2\ncontinues on from Question GUI version 1 but is now\nconnected to the Main Menu GUI\nButtons on the main menu are not disabled when the question GUI is opened\nthis will need to be fixed in version 3\n\n\"\"\"\n\nfrom tkinter import *\nfrom functools import partial # To prevent unwanted additional windows\n\n\nclass MathQuiz:\n def __init__(self):\n # Formatting variables\n background_color = \"#66FFFF\" # light blue\n\n # Main menu GUI frame\n self.main_menu_frame = Frame(width=300, height=300,\n bg=background_color, pady=10)\n self.main_menu_frame.grid()\n\n # Math Quiz heading (row 0)\n self.MathQuiz_label = Label(self.main_menu_frame,\n text=\"Math Quiz\",\n font=(\"Arial\", \"16\", \"bold\"),\n bg=background_color,\n padx=10, pady=10)\n self.MathQuiz_label.grid(row=0)\n\n # Simple instructions given\n self.intstruction_label = Label(self.main_menu_frame,\n text=\"Pick one area of math\"\n \" to work on \\n and answer \"\n \"the 10 questions given.\",\n font=(\"Arial\", \"12\", \"italic\"),\n bg=background_color,\n padx=10, pady=10)\n self.intstruction_label.grid(row=1)\n\n # Addition button (row 2)\n self.addition_button = Button(self.main_menu_frame, text=\"Addition\",\n font=(\"Arial\", \"14\"),\n padx=10, pady=10,\n width=10,\n bg=\"#008CFF\", # darker blue\n fg=\"white\",\n command=self.math_addition)\n self.addition_button.grid(row=2)\n\n # Subtraction button (row 3)\n self.subtraction_button = Button(self.main_menu_frame,\n text=\"Subtraction\",\n font=(\"Arial\", \"14\"),\n padx=10, pady=10,\n width=10,\n bg=\"#008CFF\", # darker blue\n fg=\"white\",\n command=self.math_subtraction)\n self.subtraction_button.grid(row=3)\n\n # All combined button (row 4)\n self.combined_button = Button(self.main_menu_frame,\n text=\"All Combined\",\n font=(\"Arial\", \"14\"),\n padx=10, pady=10,\n width=10,\n bg=\"#008CFF\", # darker blue\n fg=\"white\",\n command=self.all_combined)\n self.combined_button.grid(row=4)\n\n def math_addition(self):\n print(\"1 + 1 = \") # print statement to check function works\n get_question = QuestionGUI(self)\n get_question.question_label.configure(text=\"1 + 1 = \")\n\n def math_subtraction(self):\n print(\"1 - 1 = \") # print statement to check function works\n get_question = QuestionGUI(self)\n get_question.question_label.configure(text=\"1 - 1 = \")\n\n def all_combined(self):\n print(\"1 + / - 1 = \") # print statement to check function works\n get_question = QuestionGUI(self)\n get_question.question_label.configure(text=\"1 + / - 1 = \")\n\n\nclass QuestionGUI:\n def __init__(self, partner):\n # Formatting variables\n background_color = \"#3399FF\" # darker blue\n\n # sets up child window (ie: help box)\n self.question_box = Toplevel()\n\n # if users press at top, closes help and 'releases' help button\n self.question_box.protocol('WM_DELETE_WINDOW',\n partial(self.close_question, partner))\n # Question Frame\n self.question_frame = Frame(self.question_box, width=300,\n bg=background_color)\n self.question_frame.grid()\n\n # Question Heading (row 0)\n self.question_heading_label = Label(self.question_frame,\n text=\"Question 1/10\",\n font=\"Arial 16 bold\",\n bg=background_color,\n padx=10, pady=10)\n self.question_heading_label.grid(row=0)\n\n # User question to answer (row 1)\n self.question_label = Label(self.question_frame,\n text=\"1 + 1 = \",\n font=\"Arial 12 bold\", wrap=250,\n justify=CENTER, bg=background_color,\n padx=10, pady=10)\n self.question_label.grid(row=1)\n\n # Answer entry box (row 2)\n self.answer_entry = Entry(self.question_frame, width=20,\n font=\"Arial 14 bold\",\n bg=\"white\")\n self.answer_entry.grid(row=2)\n\n # Incorrect or correct statement (row 3)\n self.evaluator_label = Label(self.question_frame,\n font=\"Arial 14 bold\",\n fg=\"green\",\n bg=background_color,\n pady=10, text=\"Correct\")\n self.evaluator_label.grid(row=3)\n\n # Sets up new frame for buttons to get a nice layout\n self.button_frame = Frame(self.question_box, width=300,\n bg=background_color)\n self.button_frame.grid(row=1)\n\n # Close button (row 0, column 0)\n self.close_button = Button(self.button_frame, text=\"Close\",\n width=8, bg=\"light grey\",\n font=\"arial 10 bold\",\n command=partial(self.close_question,\n partner))\n self.close_button.grid(row=0, column=0)\n\n # Enter button (row 0, column 1)\n self.enter_button = Button(self.button_frame, text=\"Enter\",\n width=8, bg=\"light grey\",\n font=\"arial 10 bold\",\n command=partial(self.enter_question))\n self.enter_button.grid(row=0, column=1)\n\n # Next button (row 0, column 2)\n self.next_button = Button(self.button_frame, text=\"Next\",\n width=8, bg=\"light grey\",\n font=\"arial 10 bold\",\n command=partial(self.next_question))\n self.next_button.grid(row=0, column=2)\n\n def close_question(self, partner):\n # Put close button back to normal...\n partner.addition_button.config(state=NORMAL)\n self.question_box.destroy()\n\n def enter_question(self):\n print(\"Wrong answer\") # prints to test button\n\n def next_question(self):\n print(\"Next question\") # prints to test button\n\n\n# main routine\nif __name__ == \"__main__\":\n root = Tk()\n root.title(\"Math Quiz\")\n something = MathQuiz()\n root.mainloop()\n","sub_path":"02_Question_GUI_v2.py","file_name":"02_Question_GUI_v2.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"499693877","text":"\"\"\"\nYou will be given an array of integers and a target value. Determine the number of pairs of array elements that have a\ndifference equal to a target value.\n\nFor example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the condition: 2-1=1,\n 3-2=1 and 4-3=1.\n\"\"\"\n\ndef pairs(k, arr):\n \"\"\"\n\n :param k: integer, the target difference\n :param arr: an array of integers\n :return: integer representing the number of element pairs having the required difference.\n \"\"\"\n\n arr.sort()\n i=0\n j=1\n count=0\n\n while j < len(arr):\n diff = arr[j] - arr[i]\n if k == diff:\n count += 1\n j += 1\n elif k < diff:\n i += 1\n else:\n j += 1\n\n return count\n\nif __name__ == '__main__':\n print(pairs(2, [1, 5, 3, 4, 2]))","sub_path":"Search/pairs.py","file_name":"pairs.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"599296919","text":"# local dev settings\n\nfrom common_settings import *\nimport socket\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'cityfusion_dev', # Or path to database file if using sqlite3.\n 'USER': 'cityfusion_dev', # Not used with sqlite3.\n 'PASSWORD': 'forfusion', # Not used with sqlite3.\n 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n}\n\nhost_ip = socket.gethostbyname(socket.gethostname())\n\nif host_ip == '127.0.0.1':\n FACEBOOK_APP_ID = '536513936402579'\n FACEBOOK_APP_SECRET = 'f0aea33f1319a8e238a419ea57a671d5'\n\n ADMINS = (\n ('alexandr', 'alexandr.chigrinets@silkcode.com'),\n )\n\n MANAGERS = ADMINS\n\nelif host_ip == '69.164.208.181':\n FACEBOOK_APP_ID = '1406987966191446'\n FACEBOOK_APP_SECRET = '349b9b850b503a02b490148333b6d917'\n GOOGLE_ANALYTICS_CODE = 'UA-43571619-1'\n\n TWILIO_ACCOUNT_SID = 'ACe1055ea325ab5273147cab8ee7f0a856'\n TWILIO_AUTH_TOKEN = '11743ce6dbac27165c433e2fe901383b'\n TWILIO_NUMBER = \"+13069883370\"\n\n MAMONA_BACKENDS_SETTINGS = {\n 'paypal': {\n 'url': 'https://www.paypal.com/cgi-bin/webscr',\n 'email': 'ray@cityfusion.ca',\n }\n }\n\n DEBUG = True\n GEARS_DEBUG = False","sub_path":"alpha/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"557886291","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[21]:\n\n\nfrom utils import *\nfrom network import *\n\n\n# In[22]:\n\ndef train(n_epochs = N_EPOCHS, pairs_file = PAIRS_FILE, test_users = None ):#opt\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n weights = load_pretrained_weights()\n\n model = VggVox(weights=weights)\n model = model.to(device)\n\n criterion = ContrastiveLoss()\n criterion = criterion.to(device)\n\n loss_list = []\n best_loss = torch.autograd.Variable(torch.tensor(np.inf)).float()\n\n# LEARNING_RATE = 1e-3\n# N_EPOCHS = 1 #15\n# N_EPOCHS = int(opt.n_epochs)\n# N_EPOCH = n_epochs\n# BATCH_SIZE = 64\n\n optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\n # model, _, optimizer = load_saved_model(\"checkpoint_20181211-030043_0.014894404448568821.pth.tar\", test=False)\n\n# test_users = opt.test_users\n\n voxceleb_dataset = VoxCelebDataset(pairs_file, test_users = test_users)#PAIRS_FILE\n train_dataloader = DataLoader(voxceleb_dataset, batch_size=BATCH_SIZE, shuffle=True,\n num_workers=4)\n n_batches = int(len(voxceleb_dataset) / BATCH_SIZE)\n\n print(\"training unique users\", len(voxceleb_dataset.training_users))\n print(\"training samples\", len(voxceleb_dataset))\n print(\"batches\", int(len(voxceleb_dataset) / BATCH_SIZE))\n\n for epoch in range(1, N_EPOCHS+1):\n running_loss = torch.zeros(1)\n\n for i_batch, data in enumerate(train_dataloader, 1):\n mfcc1, mfcc2, label = data['spec1'], data['spec2'], data['label']\n mfcc1 = Variable(mfcc1.float(), requires_grad=True).to(device)\n mfcc2 = Variable(mfcc2.float(), requires_grad=True).to(device)\n label = Variable(label.float(), requires_grad=True).to(device)\n\n output1, output2 = model(mfcc1.float(), mfcc2.float())\n\n optimizer.zero_grad()\n\n loss = criterion(output1, output2, label.float())\n\n # assert mfcc1.dim() == mfcc2.dim() == 4\n # assert output1.dim() == output2.dim() == 2\n # assert loss.requires_grad and output1.requires_grad and output2.requires_grad\n # assert loss.grad_fn is not None and output1.grad_fn is not None and output2.grad_fn is not None\n\n # print(\"loss\", loss, loss.requires_grad, loss.grad_fn)\n # print(\"output1\", output1.shape, output1.requires_grad, output1.grad_fn, output1.device)\n # print(\"output2\", output2.shape, output2.requires_grad, output2.grad_fn, output2.device)\n\n loss.backward()\n\n # assert mfcc1.requires_grad and mfcc2.requires_grad\n # for name, param in model.named_parameters():\n # assert param.requires_grad and param.grad is not None, (name, param.requires_grad, param.grad)\n\n optimizer.step()\n\n loss_list.append(loss.item())\n running_loss += loss.item()\n if i_batch % int(n_batches/min(20,n_batches)) == 0:\n print(\"Epoch {}/{} Batch {}/{} \\nCurrent Batch Loss {}\\n\".format(epoch, N_EPOCHS, i_batch, n_batches, loss.item()))\n epoch_loss = running_loss / len(voxceleb_dataset)\n print(\"==> Epoch {}/{} Epoch Loss {}\".format(epoch, N_EPOCHS, epoch_loss.item()))\n\n is_best = epoch_loss < best_loss\n if is_best:\n best_loss = epoch_loss\n\n save_checkpoint({'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optim_dict': optimizer.state_dict()},\n loss=epoch_loss)\n else:\n print(\"### Epoch Loss did not improve\\n\")\n\n# plt.plot(loss_list[50:])\n# plt.show()\n\n\n\nif __name__ == '__main__':\n# \tget_id_result()\n parser = argparse.ArgumentParser()\n# \tsubparsers = parser.add_subparsers()\n# \tparser_train = subparsers.add_parser('train')\n# \tparser_train.add_argument('--test_users', nargs='*', default = None)#, default = 'data/wav/enroll/19-enroll.wav')\n# \tparser_train.add_argument('--n_epochs', default = 1)#, default = 'data/wav/test/19-test.wav')\n# # \tparser_scoring.add_argument('--metric', default = 'cosine')\n# # \tparser_scoring.add_argument('--threshold', default = 0.1)\n# \tparser_train.set_defaults(func=train)\n# \topt = parser.parse_args()\n# \topt.func(opt)\n# parser.add_argument('--augment',\n# default=False, action=\"store_true\",\n# help=\"Train with augmented data\")\n\n parser.add_argument('--test-users', nargs='*', default = None,\n help=\"Leave out test sets from train sets\")#, default = 'data/wav/enroll/19-enroll.wav')\n parser.add_argument('--n-epochs', default = 1,\n help = 'Set the number of epochs')\n parser.add_argument('--pairs-file', default = os.path.join(TRAIN_PATH,'../',PAIRS_FILE),\n help = 'Pairs csv file path')\n\n args = parser.parse_args()\n \n train(n_epochs = args.n_epochs, pairs_file = args.pairs_file, test_users = args.test_users)","sub_path":"model/modelv2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"447686156","text":"import collections\nimport itertools\n\nfrom django.http import HttpResponse, HttpResponsePermanentRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.cache import cache_page\n\nfrom tower import ugettext as _, ugettext_lazy as _lazy\nimport jingo\nimport product_details\n\nimport amo.utils\nfrom addons.models import Addon, Category\nfrom amo.urlresolvers import reverse\nfrom addons.views import HomepageFilter\nfrom translations.query import order_by_translation\n\n\nlanguages = dict((lang.lower(), val)\n for lang, val in product_details.languages.items())\n\n\ndef locale_display_name(locale):\n \"\"\"\n Return (english name, native name) for the locale.\n\n Raises KeyError if the locale can't be found.\n \"\"\"\n if not locale:\n raise KeyError\n\n if locale.lower() in languages:\n v = languages[locale.lower()]\n return v['English'], v['native']\n else:\n # Take out the regional portion and try again.\n hyphen = locale.rfind('-')\n if hyphen == -1:\n raise KeyError\n else:\n return locale_display_name(locale[:hyphen])\n\n\nLocale = collections.namedtuple('Locale', 'locale display native dicts packs')\n\n\ndef language_tools(request):\n types = (amo.ADDON_DICT, amo.ADDON_LPAPP)\n q = (Addon.objects.public().exclude(target_locale='')\n .filter(type__in=types, target_locale__isnull=False))\n addons = [a for a in q.all() if request.APP in a.compatible_apps]\n\n for addon in addons:\n locale = addon.target_locale.lower()\n try:\n english, native = locale_display_name(locale)\n # Add the locale as a differentiator if we had to strip the\n # regional portion.\n if locale not in languages:\n native = '%s (%s)' % (native, locale)\n addon.locale_display, addon.locale_native = english, native\n except KeyError:\n english = u'%s (%s)' % (addon.name, locale)\n addon.locale_display, addon.locale_native = english, ''\n\n locales = {}\n for locale, addons in itertools.groupby(addons, lambda x: x.target_locale):\n addons = list(addons)\n dicts = [a for a in addons if a.type_id == amo.ADDON_DICT]\n packs = [a for a in addons if a.type_id == amo.ADDON_LPAPP]\n addon = addons[0]\n locales[locale] = Locale(addon.target_locale, addon.locale_display,\n addon.locale_native, dicts, packs)\n\n locales = sorted(locales.items(), key=lambda x: x[1].display)\n\n search_cat = '%s,0' % amo.ADDON_DICT\n\n return jingo.render(request, 'browse/language_tools.html',\n {'locales': locales, 'search_cat': search_cat})\n\n# Placeholder for the All category.\n_Category = collections.namedtuple('Category', 'name count slug')\n\n\nclass AddonFilter(object):\n \"\"\"\n Support class for sorting add-ons. Sortable fields are defined as\n (value, title) pairs in ``opts``. Pass in a request and a queryset and\n AddonFilter will figure out how to sort the queryset.\n\n self.sorting: the field we're sorting by\n self.opts: all the sort options\n self.qs: the sorted queryset\n \"\"\"\n opts = (('name', _lazy(u'Name')),\n ('updated', _lazy(u'Updated')),\n ('created', _lazy(u'Created')),\n ('downloads', _lazy(u'Downloads')),\n ('rating', _lazy(u'Rating')))\n\n def __init__(self, request, queryset, default):\n self.sorting = self.options(request, default)\n self.qs = self.sort(queryset, self.sorting)\n\n def __iter__(self):\n \"\"\"Cleverness: this lets you unpack the class like a tuple.\"\"\"\n return iter((self.sorting, self.opts, self.qs))\n\n def options(self, request, default):\n opts_dict = dict(self.opts)\n if 'sort' in request.GET and request.GET['sort'] in opts_dict:\n sort = request.GET['sort']\n return sort\n else:\n return default\n\n def sort(self, qs, field):\n if field == 'updated':\n return qs.order_by('-last_updated')\n if field == 'created':\n return qs.order_by('-created')\n elif field == 'downloads':\n return qs.order_by('-weekly_downloads')\n elif field == 'rating':\n return qs.order_by('-bayesian_rating')\n else:\n return order_by_translation(qs, 'name')\n\n\ndef themes(request, category=None):\n q = Category.objects.filter(application=request.APP.id,\n type=amo.ADDON_THEME)\n categories = order_by_translation(q, 'name')\n\n addons, filter, unreviewed = _listing(request, amo.ADDON_THEME)\n total_count = addons.count()\n\n if category is None:\n selected = _Category(_('All'), total_count, '')\n else:\n selected = dict((c.slug, c) for c in categories)[category]\n addons = addons.filter(categories__slug=category)\n\n themes = amo.utils.paginate(request, addons)\n\n # Pre-selected category for search form\n search_cat = '%s,0' % amo.ADDON_THEME\n\n return jingo.render(request, 'browse/themes.html',\n {'categories': categories, 'total_count': total_count,\n 'themes': themes, 'selected': selected,\n 'sorting': filter.sorting,\n 'sort_opts': filter.opts,\n 'unreviewed': unreviewed,\n 'search_cat': search_cat})\n\n\ndef _listing(request, addon_type, default='downloads'):\n # Set up the queryset and filtering for themes & extension listing pages.\n status = [amo.STATUS_PUBLIC]\n\n unreviewed = 'on' if request.GET.get('unreviewed', False) else None\n if unreviewed:\n status.append(amo.STATUS_UNREVIEWED)\n\n qs = (Addon.objects.listed(request.APP, *status)\n .filter(type=addon_type).distinct())\n filter = AddonFilter(request, qs, default)\n return filter.qs, filter, unreviewed\n\n\ndef extensions(request, category=None):\n TYPE = amo.ADDON_EXTENSION\n\n if category is not None:\n q = Category.objects.filter(application=request.APP.id, type=TYPE)\n category = get_object_or_404(q, slug=category)\n\n if 'sort' not in request.GET and category:\n return category_landing(request, category)\n\n addons, filter, unreviewed = _listing(request, TYPE)\n\n if category:\n addons = addons.filter(categories__id=category.id)\n\n addons = amo.utils.paginate(request, addons)\n\n search_cat = '%s,%s' % (TYPE, category.id if category else 0)\n\n return jingo.render(request, 'browse/extensions.html',\n {'category': category, 'addons': addons,\n 'unreviewed': unreviewed,\n 'sorting': filter.sorting,\n 'sort_opts': filter.opts,\n 'search_cat': search_cat})\n\n\nclass CategoryLandingFilter(HomepageFilter):\n\n opts = (('featured', _lazy('Featured')),\n ('created', _lazy('Recently Added')),\n ('downloads', _lazy('Top Downloads')),\n ('rating', _lazy('Top Rated')))\n\n def __init__(self, request, base, category, key, default):\n self.category = category\n super(CategoryLandingFilter, self).__init__(request, base, key,\n default)\n\n def _filter(self, field):\n qs = Addon.objects\n if field == 'created':\n return qs.order_by('-created')\n elif field == 'downloads':\n return qs.order_by('-weekly_downloads')\n elif field == 'rating':\n return qs.order_by('-bayesian_rating')\n else:\n return qs.filter(addoncategory__feature=True,\n addoncategory__category=self.category)\n\n\ndef category_landing(request, category):\n base = (Addon.objects.listed(request.APP).exclude(type=amo.ADDON_PERSONA)\n .filter(categories__id=category.id))\n filter = CategoryLandingFilter(request, base, category,\n key='browse', default='featured')\n\n search_cat = '%s,%s' % (category.type_id, category.id)\n\n return jingo.render(request, 'browse/category_landing.html',\n {'category': category, 'filter': filter,\n 'search_cat': search_cat})\n\n\ndef creatured(request, category):\n TYPE = amo.ADDON_EXTENSION\n q = Category.objects.filter(application=request.APP.id, type=TYPE)\n category = get_object_or_404(q, slug=category)\n addons = Addon.objects.public().filter(addoncategory__feature=True,\n addoncategory__category=category)\n return jingo.render(request, 'browse/creatured.html',\n {'addons': addons, 'category': category})\n\n\nclass PersonasFilter(HomepageFilter):\n\n opts = (('up-and-coming', _lazy('Up & Coming')),\n ('created', _lazy('Recently Added')),\n ('popular', _lazy('Most Popular')),\n ('rating', _lazy('Top Rated')))\n\n def _filter(self, field):\n qs = Addon.objects\n if field == 'created':\n return qs.order_by('-created')\n elif field == 'popular':\n return qs.order_by('-persona__popularity')\n elif field == 'rating':\n return qs.order_by('-bayesian_rating')\n else:\n return qs.order_by('-persona__movers')\n\n\ndef personas(request, category=None):\n TYPE = amo.ADDON_PERSONA\n q = Category.objects.filter(application=request.APP.id,\n type=TYPE)\n categories = order_by_translation(q, 'name')\n\n base = Addon.objects.valid().filter(type=TYPE)\n featured = base & Addon.objects.featured(request.APP)\n is_homepage = category is None and 'sort' not in request.GET\n\n if category is not None:\n category = get_object_or_404(q, slug=category)\n base = base.filter(categories__id=category.id)\n\n filter = PersonasFilter(request, base, key='sort', default='up-and-coming')\n\n if 'sort' in request.GET:\n template = 'grid.html'\n else:\n template = 'category_landing.html'\n\n # Pass the count from base instead of letting it come from\n # filter.qs.count() since that would join against personas.\n addons = amo.utils.paginate(request, filter.qs, 30, count=base.count())\n\n search_cat = '%s,%s' % (TYPE, category.id if category else 0)\n\n return jingo.render(request, 'browse/personas/' + template,\n {'categories': categories, 'category': category,\n 'filter': filter, 'addons': addons,\n 'featured': featured, 'is_homepage': is_homepage,\n 'search_cat': search_cat})\n\n\ndef search_engines(request, category=None):\n return HttpResponse(\"Search providers browse page stub.\")\n\n\n@cache_page(60 * 60 * 24 * 365)\ndef legacy_redirects(request, type_, category=None):\n type_slug = amo.ADDON_SLUGS.get(int(type_), 'extensions')\n if not category or category == 'all':\n url = reverse('browse.%s' % type_slug)\n else:\n cat = get_object_or_404(Category.objects, id=category)\n url = reverse('browse.%s' % type_slug, args=[cat.slug])\n mapping = {'updated': 'updated', 'newest': 'created', 'name': 'name',\n 'weeklydownloads': 'popular', 'averagerating': 'rating'}\n if 'sort' in request.GET and request.GET['sort'] in mapping:\n url += '?sort=%s' % mapping[request.GET['sort']]\n return HttpResponsePermanentRedirect(url)\n","sub_path":"apps/browse/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"299791980","text":"# -*- coding: utf-8 -*-\n# MegEngine is Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.\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 ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nimport collections\nfrom typing import Callable, Iterable, Optional, Tuple\n\nimport numpy as np\n\nfrom .._internal.opr import param_pack_split\nfrom ..core import Parameter, Tensor\nfrom .module import Module\n\n\nclass ParamPack(Module):\n r\"\"\"Pack module's parameters by gathering their memory to continuous address.\n Using (device, dtype, requires_grad) as key, for example ('gpu0', float32, True),\n parameters with same key will be packed togather.\n It helps a lot for multimachine training by speeding up allreduce gradients.\n\n :param model: the module you want to pack parameters.\n :param nr_ignore_first: how many parameters will be unpacked at first.\n :param max_size_per_group: upper bound of packed parameters' size in MB.\n :param max_nr_params_per_group: upper bound of the number of parameters of each group.\n\n \"\"\"\n\n def __init__(\n self,\n model: Module,\n nr_ignore_first: int = 8,\n max_size_per_group: int = 10,\n max_nr_params_per_group: int = 100,\n group_func: Callable = lambda name, param: 0,\n ):\n super().__init__()\n self._model = model\n self._nr_ignore_first = nr_ignore_first\n self._max_size_per_group = max_size_per_group\n self._max_nr_params_per_group = max_nr_params_per_group\n self._group_func = group_func\n self._grouped_params = []\n self._packed_params = []\n\n params = model.named_parameters()\n self._pack_params(params)\n\n def parameters(self, requires_grad: Optional[bool] = None) -> Iterable[Parameter]:\n for param in self._packed_params:\n if requires_grad is None or param.requires_grad == requires_grad:\n yield param\n\n def named_parameters(\n self, requires_grad: Optional[bool] = None\n ) -> Iterable[Tuple[str, Parameter]]:\n for idx, param in enumerate(self._packed_params):\n if requires_grad is None or param.requires_grad == requires_grad:\n yield \"packed_param_\" + str(idx), param\n\n def _pack_params(self, params: Iterable[Tuple[str, Parameter]]):\n groups = collections.defaultdict(list)\n ignored = 0\n param_id = 0\n for name, param in params:\n if self._nr_ignore_first > ignored:\n ignored += 1\n self._grouped_params.append([{\"shape\": param.shape, \"id\": param_id}])\n param.pack_group_key = self._group_func(name, param)\n self._packed_params.append(param)\n else:\n key = (\n param.dtype,\n param.device,\n param.requires_grad,\n self._group_func(name, param),\n )\n groups[key].append({\"tensor\": param, \"id\": param_id})\n param_id += 1\n for (dtype, device, requires_grad, group_key) in groups.keys():\n dtype_sz = np.dtype(dtype).itemsize\n align = device.mem_align\n if align < dtype_sz:\n align = 1\n else:\n assert align % dtype_sz == 0\n align //= dtype_sz\n\n group = groups[(dtype, device, requires_grad, group_key)]\n while group:\n aligned_pos = []\n offset = 0\n params = []\n idx = 0\n while idx < len(group):\n param = group[idx]\n assert param[\"tensor\"].device == device\n padding = (align - (offset & (align - 1))) & (align - 1)\n offset += padding\n aligned_pos.append(offset)\n params.append(param)\n offset += int(np.prod(param[\"tensor\"].shape))\n idx += 1\n\n if (\n offset * dtype_sz >= self._max_size_per_group * 1024 * 1024\n or idx >= self._max_nr_params_per_group\n ):\n break\n group = group[idx:]\n if idx == 1:\n # ignore param packs with only one item\n params[0][\"tensor\"].pack_group_key = group_key\n self._packed_params.append(params[0][\"tensor\"])\n self._grouped_params.append(\n [{\"shape\": params[0][\"tensor\"].shape, \"id\": params[0][\"id\"]}]\n )\n continue\n\n packed_value = np.zeros((offset,), dtype=dtype)\n for param, pos in zip(params, aligned_pos):\n val = param[\"tensor\"].numpy()\n packed_value[pos : pos + val.size] = val.flatten()\n new_param = Parameter(\n value=packed_value,\n device=device,\n dtype=dtype,\n requires_grad=requires_grad,\n )\n new_param.pack_group_key = group_key\n self._packed_params.append(new_param)\n self._grouped_params.append(\n [{\"shape\": i[\"tensor\"].shape, \"id\": i[\"id\"]} for i in params]\n )\n\n def forward(self, *args, **kwargs):\n replace_param = dict()\n for i in range(len(self._packed_params)):\n packed_param = self._packed_params[i]\n grouped_params = self._grouped_params[i]\n if len(grouped_params) == 1:\n continue\n split = param_pack_split(\n packed_param._symvar, [i[\"shape\"] for i in grouped_params]\n )\n split = [\n Parameter(Tensor(i, requires_grad=packed_param.requires_grad))\n for i in split\n ]\n for j in range(len(split)):\n replace_param[grouped_params[j][\"id\"]] = split[j]\n self._model.replace_param(replace_param, 0)\n\n return self._model.forward(*args, **kwargs)\n","sub_path":"python_module/megengine/module/parampack.py","file_name":"parampack.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264239742","text":"# Homework 2 code -- Dylan Brewer\n\n# Clear all\nfrom IPython import get_ipython\nget_ipython().magic('reset -sf')\n\n# Import packages\nimport os\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as sc\nimport scipy.optimize as opt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nimport statsmodels.api as sm\n\n# Set working directories and seed\ndatapath = r'C:\\Users\\dbrewer30\\Dropbox\\teaching\\Courses\\BrewerPhDEnv\\Homeworks\\phdee-2021-homework\\homework2'\noutputpath = r'C:\\Users\\dbrewer30\\Dropbox\\teaching\\Courses\\BrewerPhDEnv\\Homeworks\\phdee-2021-answers\\homework2\\output'\n\nos.chdir(datapath)\n\nrandom.seed(65377037781)\nnp.random.seed(480971)\n\n# Import homework data\nkwh = pd.read_csv('kwh.csv')\n\n# Question 1 ------------------------------------------------------------------\n\n## These will be referenced later\nvarlist = ['electricity', 'sqft', 'temp']\n\n## Get means\nmean0 = kwh[ kwh[ 'retrofit' ] == 0 ].mean().drop('retrofit')\nmean1 = kwh[ kwh[ 'retrofit' ] == 1 ].mean().drop('retrofit')\n\n## Get difference in means\ndiff = mean0-mean1\n\n## Get standard deviations\nsd0 = kwh[ kwh[ 'retrofit' ] == 0 ].std().drop('retrofit')\nsd1 = kwh[ kwh[ 'retrofit' ] == 1 ].std().drop('retrofit')\n\n## Perform difference in means test\ntval, pval = sc.ttest_ind(kwh[ kwh[ 'retrofit' ] == 0 ].drop('retrofit',1) , kwh[ kwh[ 'retrofit' ] == 1 ].drop('retrofit',1) , equal_var = False) # Get p value\npval = pd.Series(pval,varlist)\n\n## Observations\nncontrol = pd.Series(kwh[ kwh[ 'retrofit' ] == 0 ].count().min())\nntreat = pd.Series(kwh[ kwh[ 'retrofit' ] == 1 ].count().min())\nnobs = pd.Series(kwh.count().min())\n\n## Construct table\n### Construct row names and column names\nrowlist = varlist + ['Observations']\nrownames = pd.concat([pd.Series(x.capitalize() for x in rowlist),pd.Series([' ',' ',' '])],axis = 1).stack() # Note this stacks an empty list and capitalizes the variable list\ncolumnnames = [('Control','(s.d.)'),('Treatment','(s.d.)'),('Difference','(p val)')] # Two levels of column names\n\n### Display means and differences to two decimal places\nmean0 = mean0.map('{:.2f}'.format)\nmean1 = mean1.map('{:.2f}'.format)\ndiff = diff.map('{:.2f}'.format)\n\n### Display standard deviations to two decimal places and add parentheses\nsd0 = sd0.map('({:.2f})'.format)\nsd1 = sd1.map('({:.2f})'.format)\npval = pval.map('({:.2f})'.format)\n\n### Align std deviations under means and pvalues under differences\ncol0 = pd.concat([mean0,sd0,ncontrol],axis = 1,keys = ['mean','std dev','obs']).stack() # Align std deviations under means\ncol1 = pd.concat([mean1,sd1,ntreat],axis = 1,keys = ['mean','std dev','obs']).stack()\ncol2 = pd.concat([diff,pval,nobs],axis = 1,keys = ['difference','p value','obs']).stack()\n\n### Get rid of Pandas indices\ncol0 = col0.reset_index(drop = True)\ncol1 = col1.reset_index(drop = True)\ncol2 = col2.reset_index(drop = True)\n\n### Finally put the pieces together and export to LaTeX\nbtable = pd.concat([col0,col1,col2], axis = 1)\nbtable.columns = pd.MultiIndex.from_tuples(columnnames)\nbtable.index = rownames\n\nprint(btable.to_latex())\n\nos.chdir(outputpath) # Output directly to LaTeX folder\n\nbtable.to_latex('btable.tex')\n\n# Question 2 -----------------------------------------------------------------\n\n## I used Seaborn because it seemed hip\n\nsns.distplot(kwh[ kwh[ 'retrofit' ] == 0 ]['electricity'], hist=False, label='Did not receive retrofit')\nsns.distplot(kwh[ kwh[ 'retrofit' ] == 1 ]['electricity'], hist=False, label='Received retrofit')\nplt.xlabel('Electricity use (KwH)')\nplt.savefig('treatmenthist.eps',format='eps') # I suggest saving to .eps for highest quality\nplt.show()\n\n# Question 3------------------------------------------------------------------\n\n## Part (a)\n### Set up Numpy matrices for OLS:\nYvar = kwh['electricity'].to_numpy()\nnobsa, = Yvar.shape\nconstant = np.ones((nobsa,1)) # Vector of ones for the constant\nXvar = kwh.drop('electricity',axis = 1).to_numpy()\nXvar = np.concatenate([constant,Xvar],axis = 1) # Add the constant\n\n### Run the regression\nbetaolsa = np.matmul(np.linalg.inv((np.matmul(Xvar.T, Xvar))), np.matmul(Xvar.T, Yvar))\n\n## Part (b)\n### Set up objective function\n\ndef my_leastsq(beta,Y,X):\n return np.sum((Y-np.matmul(X,beta))**2)\n\n### Set up the solver\nbetaolsb = opt.minimize(my_leastsq,np.array([0,1,1,1]).T, args = (Yvar, Xvar)).x # I had to play with the initial conditions to get it to converge\nnobsb, = Yvar.shape\n\n## Part (c)\n### Simply call the statsmodels function. Now there is an (arguably) easier way to do this using R-style syntax with an equation.\nolsc = sm.OLS(kwh['electricity'],Xvar).fit()\nbetaolsc = olsc.params.to_numpy()\nnobsc = olsc.nobs\n\n## Output table\n\n### Row and column names\nxvarlist = ['Constant', 'Sqft', 'Retrofit', 'Temperature','Observations']\n\nrownames3 = pd.Series(xvarlist)\ncolnames3 = pd.Series(['(a)','(b)','(c)'])\n\n### Put outputs and observations together\noutputtable3 = pd.DataFrame((np.append(betaolsa,nobsa),np.append(betaolsb,nobsb),np.append(betaolsc,nobsc))).T\noutputtable3.index = rownames3\noutputtable3.columns = colnames3\n\noutputtable3 = outputtable3.reindex(index = ['Retrofit', 'Sqft', 'Temperature', 'Constant','Observations'])\n\n### Format to three decimal places and change order\nfor z in colnames3 :\n outputtable3[z] = outputtable3[z].map('{:.3f}'.format)\n outputtable3.loc['Observations',z] = \"{0:.0f}\".format(float(outputtable3.loc['Observations',z])) # This cannot be the most efficient or elegant way to do this.\n\noutputtable3.to_latex('outputtable3.tex')","sub_path":"homework2/code/HW2_answercode.py","file_name":"HW2_answercode.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"522967690","text":"class Node:\n \n def __init__(self, data):\n\n self.data = data\n self.next = None\n\nclass LinkedList:\n\n def __init__(self):\n\n self.head = None\n\n def push(self,data):\n\n node = Node(data)\n node.next = self.head\n self.head = node\n\n def reverse(self,node):\n\n if node.next is None:\n self.head = node\n node.next = None\n return\n\n self.reverse(node.next)\n node.next.next = node\n node.next = None\n\n \n\n\n \n\nif __name__ == '__main__':\n\n ll = LinkedList()\n ll.push(1)\n ll.push(2)\n ll.push(3)\n ll.push(4)\n ll.push(5)\n ll.push(6)\n ll.push(7)\n ll.push(8)\n print(ll.head.data)\n ll.reverse(ll.head)\n print(ll.head.data)\n","sub_path":"LinkedList/reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216675977","text":"'''\n Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.\n\nExample 1:\nInput:nums = [1,1,1], k = 2\nOutput: 2\nNote:\nThe length of the array is in range [1, 20,000].\nThe range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].\n Hide Hint #1 \nWill Brute force work here? Try to optimize it.\n Hide Hint #2 \nCan we optimize it by using some extra space?\n Hide Hint #3 \nWhat about storing sum frequencies in a hash table? Will it be useful?\n Hide Hint #4 \nsum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.\n\n'''\n\nfrom collections import defaultdict\n\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n sums_so_far = defaultdict(int)\n our_sum = 0\n num_subarrays = 0\n for v in nums:\n our_sum += v\n if our_sum == k:\n num_subarrays += 1\n if (our_sum - k) in sums_so_far:\n num_subarrays += sums_so_far[our_sum - k]\n sums_so_far[our_sum] += 1\n return num_subarrays\n","sub_path":"Day-22.py","file_name":"Day-22.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27929262","text":"# coding: utf-8\n\n\"\"\"\nFile Name:\nexp20-parsed_testing_determined_regime_corrected_iYS.py\n\nBased on:\nexp07-three_source_multi_parsed.py\nexp07-three_source_multi.py\nexp11-online_update.py\nexp13-three_source_multi_parsed.py\nexp14-three_source_multi_parsed_02.py\nexp15-parsed_testing.py\nexp16-parsed_testing_stable.py\nF12_IYSDetection_parse_determ_regm.py\nF13_IYSDetection_parse_determ_regm_corrected_iYS.py\n\n\nAuthor: Lingqing Gan @ Stony Brook University\n\n01/06/2020 notes (exp20)\nA version that corrected the iYS prob function.\n\n01/06/2020 notes (exp19)\nnot sure if this is gonna work, since the length of the\nregimes might not be independent.\nAlso, I found that there was an error with the formula of\nthe iYS likelihood function.\nSo I will work on exp20 first, where I correct the iYS\nlikelihood formula.\n\n01/04/2020 notes (exp19)\nBecause the results in exp18 still didn't work\nwith >3 node networks, and a lot of debugging still\ndidn't make it work. So now I'm trying out plan B.\n\nThe inspiration came from a discussion with Prof. this\npast Thursday(01/02/2020). Professor mentioned that we\nhaven't accounted for the variation involved while we\nestimate the parameter rho. This reminded me of something\nthat I thought might have influenced the accuracy of the\nmodel selection results. When we are deciding whether the\nneighboring nodes are influencing the node of interest,\nwe do a separate Gibbs sampling for each node-neighbor\npair. Might there be any overfitting?\n\nSo the idea here is, for each node of interest, we estimate\nthe parameter rho using only its regimes that has definitely\nno influencer. Then we use this same estimated rho value\nfor all model selection pertaining to this node.\n\n\n01/02/2019 notes (exp18)\nFor now it only works on two node network. For 3\nnode it doesn't work correctly.\n\n12/29/2019 notes (exp18)\nThis version is based on the stable version exp16.\nThe improvement is to make the fixed total time\nslots a varying variable, and we only control the\ntotal number of (unambiguous) regimes each\nnode-neighbor pair uses. Once the number of regimes\nreaches the threshold, we stop model selection with\nthis pair.\n\nFor this reason, we need to change the detection class\nthat we originally used from F11_IYSDetection_parse_03.py.\nInstead, we use a new file, F12_IYSDetection_parse_determ_regm.py\nfor IYS model selection.\n\n12/23/2019 notes (exp16)\nNow we make a stable version of the code.\n1. We run it under various scenarios to collect data;\n2. We try running it on real data.\n\n12/02/2019 note\ndevelopment after exp14.\nThe code finally worked. Now we need further tests.\n1. adjust the details so it works on multi-node scenarios (done)\n2. see if it's correct\n\n10/31/2019 note\nwe alter the first signal to be all 1s instead of all 0s.\n\n09/23/2019 note\nPlan of changes to this version:\n1. parse all the sequences so that only \"pure\" sequences are considered.\n2. a pure sequence: the regimes of a node during which only one of the\n neighbors have changed their regime. Thus during this regime, the node\n of interest can only be influenced by one neighbor.\n3. If there is no new regime among the neighbors during a regime of the\n node of interest, we also keep track of it. This helps us better\n estimate the value of rho for the node of interest.\n4. We would use the detection class to keep track of the number of pure\n sequences for each model for each node of interest. This would be\n important to understanding the required length of time instants\n in order to acquire sufficient data to carry out the Gibbs sampling\n procedure.\n5. A parameter: effective_regime_number\n designated number of regimes that need to be satisfied to make the\n Gibbs sampling procedure effective. e.g. effective_regime_number = 20\n\nPast Description:\n1. Run the three node models multiple times;\n2. Collect data according to the given format;\n3. Save the data into a pickle data file.\n4. The data file will be read and plotted by exp09.py.\n\n09/06/2019 notes\nadded the code to save the original signals.\nThen we can analyze it.\n\"\"\"\n\nimport numpy as np\nimport time\nimport pickle\nimport os\nfrom os.path import join\n\n\nfrom functions.F07_IYSNetwork_stable_02 import IYSNetwork\nfrom functions.F13_IYSDetection_parse_determ_regm_corrected_iYS import IYSDetection_parse_dtm_rgm_crtd_iYS\n\n\n\ndef main():\n \"\"\"\n Main function.\n \"\"\"\n # =================================================\n # PARAMETERS\n # =================================================\n network_size = 3\n\n total_rep = 1\n gibbs_rep = 20000\n rho = 0.75\n regimes_required = 20\n time_string = time.strftime(\"%Y%m%d-%H%M%S\", time.localtime())\n\n # data section of the dict to be saved\n data_dict = {}\n\n for rep_exp_index in range(0, total_rep):\n print(\"Current repetition: rep=\", rep_exp_index)\n\n # =================================================\n # MODEL\n # =================================================\n\n # generate network topology\n # (directed network)\n # item[i][j]=1 means node i influences node j, 0 otherwise\n # item[i][i]=0 all the time though each node technically\n # influences themselves\n adjacency_matrix = np.zeros((network_size, network_size))\n adjacency_matrix[0, 1] = 1\n adjacency_matrix[0, 2] = 1\n # adjacency_matrix[1, 0] = 1\n\n # create the i-YS network object instance\n network = IYSNetwork(adjacency_matrix, rho=rho)\n\n # create the i-YS detection object instance\n regime_detection = IYSDetection_parse_dtm_rgm_crtd_iYS(network_size,\n gibbs_rep, regimes_required)\n\n # evolve the network and detection objects\n # before the required regimes are reached\n while not regime_detection.regime_reached:\n\n # generate the network signal for the next time instant\n new_signal = network.next_time_instant()\n\n # run model selection online update\n regime_detection.read_new_time(np.copy(new_signal))\n\n # save the model selection results\n # each experiment is saved separately\n aprob_history = regime_detection.aprob_history\n rho_history = regime_detection.rho_history\n signal_history = regime_detection.signal_history\n\n data_dict[rep_exp_index] = {}\n data_dict[rep_exp_index][\"aprob\"] = aprob_history\n data_dict[rep_exp_index][\"rho\"] = rho_history\n data_dict[rep_exp_index][\"signals\"] = signal_history\n\n # =================================================\n # SAVE THE DATA\n # =================================================\n # create the dict to save\n # parameter section and data section\n save_dict = {\"parameters\": {\"network size\": network_size,\n \"adjacency matrix\": adjacency_matrix,\n \"required regimes\": regimes_required,\n \"total number of MC simulations\": total_rep,\n \"Gibbs sampling iterations\": gibbs_rep,\n \"rho true value\": rho,\n \"data format\": \"rep, i, j\"\n },\n \"data\": data_dict}\n\n # absolute dir the script is in\n script_dir = os.path.dirname(__file__)\n rel_path_temp = \"result_temp\"\n\n # the file name\n file_name = \"exp20-data-\" + time_string + \"(determined_regime_corrected_iYS).pickle\"\n complete_file_name = join(script_dir, rel_path_temp, file_name)\n print(\"Saved file name: \", file_name)\n # save the file\n with open(complete_file_name, 'wb') as handle:\n pickle.dump(save_dict, handle,\n protocol=pickle.HIGHEST_PROTOCOL)\n print(\"Data saved successfully!\")\n\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exp20-parsed_testing_determined_regime_corrected_iYS.py","file_name":"exp20-parsed_testing_determined_regime_corrected_iYS.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"448326293","text":"# -*- coding:utf-8 -*-\r\n\r\nfrom os.path import *\r\nimport os\r\n\r\n\r\n#폴더 삭제 함수\r\n#폴더는 안에 내용물이 있을 경우 삭제가 안 되어서 이런 함수 개발이 필요했음.\r\ndef rmDir(path):\r\n\tfor f in os.listdir(path):\r\n\t\tnewPath = path + \"\\\\\" + f\r\n\t\tif os.path.isdir(newPath) == True:\r\n\t\t\trmDir(newPath)\r\n\t\telse:\r\n\t\t\tos.remove(newPath)\r\n\tos.rmdir(path)\r\n\r\n#출력물 삭제 함수 \r\n#Debug, Release 등의 폴더와 .sdf파일을 삭제한다. \r\ndef deleteOutputs(path, ignoreSDF = False):\r\n\tprint(\"checking \" + path)\r\n\tfor name in os.listdir(path):\r\n\t\tif name == \".svn\": \r\n\t\t\tcontinue\r\n\t\tnewPath = path + '\\\\' + name\r\n\t\tif os.path.isdir(newPath):\r\n\t\t\toutputFolders = [\"Debug\", \"Release\", \"Test\", \"ipch\", \"x64\"]\r\n\t\t\t\"\"\"\tisOutput = False;\r\n\t\t\tfor folder in outputFolders:\r\n\t\t\t\tif(folder == name):\r\n\t\t\t\t\tisOutput = True\r\n\t\t\t\t\tbreak\r\n\t\t\tif isOutput:\"\"\"\r\n\t\t\tif name in outputFolders:\r\n\t\t\t\tprint(\"deleting \" + newPath)\r\n\t\t\t\trmDir(newPath)\r\n\t\t\telse:\r\n\t\t\t\tdeleteOutputs(newPath)\r\n\t\telse:\r\n\t\t\tfile = os.path.splitext(name)\r\n\t\t\tif ignoreSDF == False and file[1] == \".sdf\":\r\n\t\t\t\tos.remove(newPath)\r\n\r\ndeleteOutputs(\".\", True)","sub_path":"Cleaner.py","file_name":"Cleaner.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"307961235","text":"from collections import OrderedDict\nfrom datetime import datetime\nfrom copy import copy\nimport pytz\nimport csv\nimport re\nimport os\n\nfrom .handlers import TimeValue, ApiHandler, CalendarHandler, \\\n TranslationHandler, TrainTripIterator\n\nfrom .utils import distance, text_color, clear_directory, \\\n timetable_item_station, compress, print_log\n\nfrom .const import GTFS_HEADERS_TRAIN, SEPARATE_STOPS\nfrom .err import DataAssertion\n\nclass TrainParser:\n \"\"\"Object responsible for parsing train data\n \n :param apikey: Key to the ODPT API\n :type apikey: str\n \"\"\"\n\n def __init__(self, apikey):\n \"\"\"Init the TrainParser\"\"\"\n self.apikey = apikey\n self.api = ApiHandler(self.apikey)\n\n # Set-up separate handlers\n self.today = datetime.now(pytz.timezone(\"Asia/Tokyo\"))\n\n self.translations = TranslationHandler()\n self.calendars = CalendarHandler(self.api, self.today.date())\n\n # Route & Operator data\n self.operators = []\n self.route_data = OrderedDict()\n\n # Trips data\n self.train_blocks = {}\n self.train_directions = {}\n self.train_types = {}\n\n # Stops data\n self.station_positions = {}\n self.station_names = {}\n self.valid_stops = set()\n\n # Postprocess data\n self.remove_trips = set()\n\n def load_routes(self):\n \"\"\"Load route data from data/train_routes.csv\"\"\"\n\n print_log(\"Loading data from train_routes.csv\")\n\n with open(\"data/train_routes.csv\", mode=\"r\", encoding=\"utf8\", newline=\"\") as buffer:\n reader = csv.DictReader(buffer)\n for row in reader:\n\n # Only save info on routes which will have timetables data available\n if not row[\"train_timetable_available\"] == \"1\":\n continue\n\n self.route_data[row[\"route_id\"]] = row\n \n if row[\"operator\"] not in self.operators:\n self.operators.append(row[\"operator\"])\n\n def load_train_types(self):\n \"\"\"Return a dictionary mapping each TrainType to\n a tuple (japanese_name, english_name)\"\"\"\n\n ttypes = self.api.get(\"TrainType\")\n\n for ttype in ttypes:\n ja_name = ttype[\"dc:title\"]\n\n if ttype.get(\"odpt:trainTypeTitle\", {}).get(\"en\", \"\"):\n en_name = ttype.get(\"odpt:trainTypeTitle\", {}).get(\"en\", \"\")\n else:\n en_name = self.translations.get_english(ttype[\"dc:title\"], True)\n\n self.train_types[ttype[\"owl:sameAs\"].split(\":\")[1]] = (ja_name, en_name)\n\n def load_train_directions(self):\n \"\"\"Save a dictionary mapping RailDirection to\n its name to self.train_directions\"\"\"\n tdirs = self.api.get(\"RailDirection\")\n \n for i in tdirs:\n self.train_directions[i[\"owl:sameAs\"]] = i[\"dc:title\"]\n\n def get_stop_name(self, stop_id):\n \"\"\"Returns the name of station with the provided id\"\"\"\n saved_name = self.station_names.get(stop_id)\n\n if saved_name is not None:\n return saved_name\n \n else:\n name = re.sub(r\"(?!^)([A-Z][a-z]+)\", r\" \\1\", stop_id.split(\".\")[-1])\n self.station_names[stop_id] = name\n print_log(f\"no name for stop {stop_id}\", 1)\n return name\n\n @staticmethod\n def get_train_name(names, lang):\n \"\"\"Returns the train_name of given the names and language\"\"\"\n if type(names) is dict: names = [names]\n\n sep = \"・\" if lang == \"ja\" else \" / \"\n name = sep.join([i[lang] for i in names if i.get(lang)])\n\n return name\n\n def get_train_headsigns(self, route_id, trip, destinations, direction):\n \"\"\"Returns the trip_headsign given all trip data\"\"\"\n destination = \"・\".join(destinations)\n destination_en = \" / \".join([self.translations.get_english(i) for i in destinations])\n trip_id = trip[\"owl:sameAs\"].split(\":\")[1]\n\n if route_id == \"JR-East.Yamanote\":\n # Special case - JR-East.Yamanote line\n # Here, we include the direction_name, as it's important to users\n if direction == \"内回り\" and not trip.get(\"odpt:nextTrainTimetable\"):\n trip_headsign = f\"(内回り){destination}\"\n trip_headsign_en = f\"(Inner Loop ⟲) {destination_en}\"\n\n if direction == \"外回り\" and not trip.get(\"odpt:nextTrainTimetable\"):\n trip_headsign = f\"(外回り){destination}\"\n trip_headsign_en = f\"(Outer Loop ⟳) {destination_en}\"\n\n elif direction == \"内回り\":\n trip_headsign = \"内回り\"\n trip_headsign_en = \"Inner Loop ⟲\"\n\n elif direction == \"外回り\":\n trip_headsign = \"外回り\"\n trip_headsign_en = \"Outer Loop ⟳\"\n\n else:\n raise DataAssertion(\n \"error while creating headsign of JR-East.Yamanote line \" \\\n f\"train {trip_id}. please report this issue on GitHub.\"\n )\n\n else:\n trip_headsign = destination\n trip_headsign_en = destination_en\n\n trip_type_id = trip.get(\"odpt:trainType\", \":\").split(\":\")[1]\n trip_type, trip_type_en = self.train_types.get(trip_type_id, (\"\", \"\"))\n\n if trip_type:\n trip_headsign = f\"({trip_type}){destination}\"\n \n if trip_headsign_en and trip_type_en:\n trip_headsign_en = f\"({trip_type_en}) {destination_en}\"\n \n else:\n trip_headsign_en = None\n\n if trip_headsign_en is not None:\n self.translations.set_english(trip_headsign, trip_headsign_en)\n\n return trip_headsign\n\n def agencies(self):\n \"\"\"Load data from operators.csv and export them to agencies.txt\"\"\"\n buffer = open(\"gtfs/agency.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(buffer, GTFS_HEADERS_TRAIN[\"agency.txt\"], extrasaction=\"ignore\")\n writer.writeheader()\n\n print_log(\"Loading data from operators.csv\")\n\n with open(\"data/operators.csv\", mode=\"r\", encoding=\"utf8\", newline=\"\") as add_info_buff:\n additional_info = {i[\"operator\"]: i for i in csv.DictReader(add_info_buff)}\n\n print_log(\"Exporting agencies\")\n\n for operator in self.operators:\n # Get data from operators.csv\n operator_data = additional_info.get(operator, {})\n if not operator_data:\n print_log(f\"no data defined for operator {operator}\", 1)\n\n # Translations\n if \"name_en\" in operator_data:\n self.translations.set_english(operator_data[\"name\"], operator_data[\"name_en\"])\n\n # Write to agency.txt\n writer.writerow({\n \"agency_id\": operator,\n \"agency_name\": operator_data.get(\"name\", operator),\n \"agency_url\": operator_data.get(\"website\", \"\"),\n \"agency_timezone\": \"Asia/Tokyo\",\n \"agency_lang\": \"ja\"\n })\n\n buffer.close()\n\n def feed_info(self):\n \"\"\"Create file gtfs/feed_info.txt\"\"\"\n print_log(\"Exporting feed_info\")\n version = self.today.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n with open(\"gtfs/feed_info.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\\r\\n\") as file_buff:\n file_buff.write(\"feed_publisher_name,feed_publisher_url,feed_lang,feed_version\\n\")\n \n file_buff.write(\n '\"TokyoGTFS (provided by Mikołaj Kuranowski)\",'\n '\"https://github.com/MKuranowski/TokyoGTFS\",'\n f\"pl,{version}\\n\"\n )\n\n def attributions(self):\n \"\"\"Create file gtfs/attributions.txt\"\"\"\n print_log(\"Exporting attributions\")\n\n with open(\"gtfs/attributions.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\\r\\n\") as file_buff:\n file_buff.write(\n \"attribution_id,organization_name,attribution_url\"\n \"is_producer,is_authority,is_data_source\\n\"\n )\n \n file_buff.write(\n '0,\"TokyoGTFS (provided by Mikołaj Kuranowski)\",'\n '\"https://github.com/MKuranowski/TokyoGTFS\",'\n '1,0,0\\n'\n )\n\n file_buff.write(\n '1,\"Open Data Challenge for Public Transportation in Tokyo\",'\n '\"http://tokyochallenge.odpt.org/\",'\n '0,1,1\\n'\n )\n\n def stops(self):\n \"\"\"Parse stops and export them to gtfs/stops.txt\"\"\"\n # Get list of stops\n stops = self.api.get(\"Station\")\n\n # Load fixed positions\n print_log(\"loading train_stations_fixes.csv\")\n position_fixer = {}\n\n with open(\"data/train_stations_fixes.csv\", mode=\"r\", encoding=\"utf8\", newline=\"\") as f:\n for row in csv.DictReader(f):\n position_fixer[row[\"id\"]] = (row[\"lat\"], row[\"lon\"])\n\n # Open files\n print_log(\"Exporting stops\")\n\n buffer = open(\"gtfs/stops.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(buffer, GTFS_HEADERS_TRAIN[\"stops.txt\"])\n writer.writeheader()\n\n broken_stops_buff = open(\"broken_stops.csv\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n broken_stops_wrtr = csv.writer(broken_stops_buff)\n broken_stops_wrtr.writerow([\"stop_id\", \"stop_name\", \"stop_name_en\", \"stop_code\"])\n\n # Iterate over stops\n for stop in stops:\n stop_id = stop[\"owl:sameAs\"].split(\":\")[1]\n stop_code = stop.get(\"odpt:stationCode\", \"\").replace(\"-\", \"\")\n stop_name = stop[\"dc:title\"]\n stop_name_en = stop.get(\"odpt:stationTitle\", {}).get(\"en\", \"\")\n stop_lat, stop_lon = None, None\n\n self.station_names[stop_id] = stop_name\n\n # Stop name translation\n if stop_name_en:\n self.translations.set_english(stop_name, stop_name_en)\n\n # Ignore stops that belong to ignored routes\n if stop[\"odpt:railway\"].split(\":\")[1] not in self.route_data:\n continue\n\n print_log(f\"Exporting stops: {stop_id}\")\n\n # Stop Position\n stop_lat, stop_lon = position_fixer.get(\n stop_id,\n (stop.get(\"geo:lat\"), stop.get(\"geo:long\"))\n )\n\n # Output to GTFS or to incorrect stops\n if stop_lat and stop_lon:\n self.valid_stops.add(stop_id)\n self.station_positions[stop_id] = (float(stop_lat), float(stop_lon))\n writer.writerow({\n \"stop_id\": stop_id, \"stop_code\": stop_code, \"stop_name\": stop_name,\n \"stop_lat\": stop_lat, \"stop_lon\": stop_lon, \"location_type\": 0,\n })\n\n else:\n broken_stops_wrtr.writerow([stop_id, stop_name, stop_name_en, stop_code])\n\n buffer.close()\n broken_stops_buff.close()\n\n def routes(self):\n \"\"\"Parse routes and export them to routes.txt\"\"\"\n routes = self.api.get(\"Railway\")\n\n print_log(\"Exporting routes\")\n\n buffer = open(\"gtfs/routes.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(buffer, GTFS_HEADERS_TRAIN[\"routes.txt\"], extrasaction=\"ignore\")\n writer.writeheader()\n\n for route in routes:\n route_id = route[\"owl:sameAs\"].split(\":\")[1]\n \n if route_id not in self.route_data:\n continue\n\n print_log(f\"Exporting routes: {route_id}\")\n\n # Get color from train_routes.csv\n route_info = self.route_data[route_id]\n operator = route_info[\"operator\"]\n route_color = route_info[\"route_color\"].upper()\n route_text = text_color(route_color)\n\n # Translation\n self.translations.set_english(route_info[\"route_name\"], route_info[\"route_en_name\"])\n\n # Stops\n self.route_data[route_id][\"stops\"] = [\n stop[\"odpt:station\"].split(\":\")[1] for stop in sorted(route[\"odpt:stationOrder\"],\n key=lambda i: i[\"odpt:index\"])\n ]\n\n # Output to GTFS\n writer.writerow({\n \"agency_id\": operator,\n \"route_id\": route_id,\n \"route_short_name\": route_info.get(\"route_code\", \"\"),\n \"route_long_name\": route_info[\"route_name\"],\n \"route_type\": route_info.get(\"route_type\", \"\") or \"2\",\n \"route_color\": route_color,\n \"route_text_color\": route_text\n })\n\n buffer.close()\n\n def blocks(self):\n \"\"\"\n Solve blocks - properly order trains into blocks\n\n This block of code only supports 4 types of ODPT-data blocks:\n 0: No through service\n\n 1: TRIP 1 ━━ ... ━━ TRIP N\n (simple through service)\n\n 2. TRIP A/1 ━━ ... ━━ TRIP A/n ━━┓\n ┣━ TRIP C/1 ━━ ... ━━ TRIP C/n\n TRIP B/1 ━━ ... ━━ TRIP B/n ━━┛\n (2 trips merging into 1 trip)\n\n 3. ┏━ TRIP B/1 ━━ ... ━━ TRIP B/n\n TRIP A/1 ━━ ... ━━ TRIP A/n ━┫\n ┗━ TRIP C/1 ━━ ... ━━ TRIP C/n\n (1 trip splitting into 2 trips)\n\n And also, r/badcode. Seriously, I just can be bothered to write this nicely.\n \"\"\"\n\n trains = TrainTripIterator(self.api, self.today)\n\n self.train_blocks = {}\n\n through_trains = {}\n undef_trains = {}\n block_id = 0\n\n ### LOAD THROUGH TRAIN DATA ###\n for trip in trains:\n trip_id = trip[\"owl:sameAs\"].split(\":\")[1]\n\n print_log(f\"Loading trip to block solver: {trip_id}\")\n\n next_trains = trip.get(\"odpt:nextTrainTimetable\", [])\n prev_trains = trip.get(\"odpt:previousTrainTimetable\", [])\n\n destinations = trip.get(\"odpt:destinationStation\", [])\n origins = trip.get(\"odpt:originStation\", [])\n\n # Convert all to lists\n if type(next_trains) is str: next_trains = [next_trains]\n if type(prev_trains) is str: prev_trains = [prev_trains]\n if type(destinations) is str: destinations = [destinations]\n if type(origins) is str: destinations = [origins]\n\n # Change ids to match GTFS ids\n next_trains = [i.split(\":\")[1] for i in next_trains]\n prev_trains = [i.split(\":\")[1] for i in prev_trains]\n destinations = [i.split(\":\")[1] for i in destinations]\n origins = [i.split(\":\")[1] for i in origins]\n\n # Trains with absolutely no nextTrainTimetable and previousTrainTimetable\n # cannot belong to any blocks.\n if (not next_trains) and (not prev_trains):\n undef_trains[trip_id] = {\n \"previous\" : prev_trains,\n \"next\" : next_trains,\n \"destination\": destinations,\n }\n\n continue\n\n # No splitting AND merging is supported\n if len(origins) > 1 and len(destinations) > 1:\n raise DataAssertion(\n f\"{trip_id} has more then 2 destinations and origins - \"\n \"no idea how to map this to GTFS blocks\"\n )\n\n if len(next_trains) > 1 and len(prev_trains) > 1:\n raise DataAssertion(\n f\"{trip_id} has more then 2 prevTimetables and nextTrains - \"\n \"no idea how to map this to GTFS blocks\"\n )\n\n through_trains[trip_id] = {\n \"previous\" : prev_trains,\n \"next\" : next_trains,\n \"destination\": destinations,\n }\n\n ### SOLVE TRAIN BLOCKS ###\n while through_trains:\n trains_in_block = {}\n block_id += 1\n\n # First Trip\n main_trip, main_tripdata = through_trains.popitem()\n trip, data = main_trip, main_tripdata\n trains_in_block[trip] = data\n\n fetch_trips = set(data[\"previous\"]).union(data[\"next\"])\n failed_fetch = False\n\n print_log(f\"Solving block for: {main_trip}\")\n\n # Save all connected trips into trains_in_block\n while fetch_trips:\n\n trip = fetch_trips.pop()\n try:\n data = through_trains.pop(trip)\n except:\n try:\n data = undef_trains.pop(trip)\n except:\n print_log(\n f\"following through services for {main_trip}\\n\" +\n \" \"*8 + f\"reaches {trip}, \" +\n \"which is already used in a different block\",\n severity=1\n )\n\n failed_fetch = True\n break\n\n trains_in_block[trip] = data\n\n # Look over through_trains to find which trips reference current trip and add them too\n additional_trips = (\n i[0] for i in through_trains.items() if \\\n trip in i[1][\"previous\"] or trip in i[1][\"next\"])\n\n # Add direct references from current trip to additional_trips\n # And remove trips we already fetched\n fetch_trips = fetch_trips.union(data[\"previous\"]) \\\n .union(data[\"next\"]) \\\n .union(additional_trips) \\\n .difference(trains_in_block.keys())\n\n # Failed Fetch\n if failed_fetch:\n continue\n\n # Check how many splits and merges exist in this block\n max_merges = max([len(i[\"previous\"]) for i in trains_in_block.values()])\n max_splits = max([len(i[\"next\"]) for i in trains_in_block.values()])\n\n # Linear Block - No splitting or merging\n if max_splits == 1 and max_merges == 1:\n for trip_id in trains_in_block:\n self.train_blocks[trip_id] = block_id\n\n continue\n\n # Both split & merge - todo, but currently not found in real life\n elif max_splits > 1 and max_merges > 1:\n raise DataAssertion(\n \"the below block of trips both splits and merges - \" \\\n \"handling this logic is not implented.\" \\\n f\"Here's the list of trains in this block: {list(trains_in_block.keys())}\"\n )\n\n ### SPLITTING TRAIN ###\n elif max_splits > 1:\n split_train_id = [i[0] for i in trains_in_block.items() if len(i[1][\"next\"]) > 1]\n\n if len(split_train_id) > 1:\n raise DataAssertion(\n \"encountered a block of trains with more then 2 splits -\" \\\n \"handling this logic is not implemented.\"\n f\"Here's the list of trains in this block: {list(trains_in_block.keys())}\"\n )\n\n elif len(split_train_id) == 0:\n raise RuntimeError(\n \"it's impossible to get here. \"\n \"if you see this error call an exorcist.\"\n )\n\n split_train_id = split_train_id[0]\n split_train_data = trains_in_block.pop(split_train_id)\n\n for train_after_split in split_train_data[\"next\"]:\n\n next_train_id = train_after_split\n next_train_data = trains_in_block.pop(next_train_id)\n\n destination = next_train_data[\"destination\"]\n\n if not destination:\n raise DataAssertion(\n f\"expected train {next_train_id} \" \\\n \"to have destinationStation defined, \" \\\n \"as it's the first trip after a train split\"\n )\n\n # Add block_id to trips after split, while popping them from trains_in_block\n while next_train_id:\n self.train_blocks[next_train_id] = block_id\n\n # Try to find the next train by odpt:nextTrainTimetable\n if next_train_data[\"next\"]:\n next_train_id = next_train_data[\"next\"][0]\n next_train_data = trains_in_block.pop(next_train_id)\n\n # If this fails, try to find the current train in other trips' odpt:previousTrainTimetable\n else:\n for potential_train_id, potential_train_data in trains_in_block.items():\n if next_train_id in potential_train_data[\"previous\"]:\n\n next_train_id = potential_train_id\n next_train_data = potential_train_data\n\n del trains_in_block[next_train_id]\n\n break\n else:\n next_train_id = None\n next_train_data = None\n\n\n # Add the splitting train to block\n if split_train_id not in self.train_blocks:\n self.train_blocks[split_train_id] = []\n\n self.train_blocks[split_train_id].append((block_id, destination))\n\n # Add block_id to trips before split\n if len(split_train_data[\"previous\"]) == 0:\n block_id += 1\n continue\n\n prev_train_id = split_train_data[\"previous\"][0]\n prev_train_data = trains_in_block[prev_train_id]\n\n # Add block_id to trips after split, while popping them from trains_in_block\n while prev_train_id:\n\n if prev_train_id not in self.train_blocks:\n self.train_blocks[prev_train_id] = []\n\n self.train_blocks[prev_train_id].append((block_id, destination))\n\n # Try to find the previous leg by odpt:previousTrainTimetable\n if prev_train_data[\"previous\"]:\n prev_train_id = prev_train_data[\"previous\"][0]\n prev_train_data = trains_in_block[prev_train_id]\n\n # If that fails, try to find prev_train_id in trips' odpt:nextTrainTimetable\n else:\n for potential_train_id, potential_train_data in trains_in_block.items():\n if prev_train_id in potential_train_data[\"next\"]:\n\n prev_train_id = potential_train_id\n prev_train_data = potential_train_data\n\n break\n else:\n prev_train_id = None\n prev_train_data = None\n\n block_id += 1\n\n ### MERGING TRAIN ###\n elif max_merges > 1:\n merge_train_id = [i[0] for i in trains_in_block.items() if len(i[1][\"previous\"]) > 1]\n\n if len(merge_train_id) > 1:\n raise DataAssertion(\n \"encountered a block of trains with more then 2 merges -\" \\\n \"handling this logic is not implemented.\"\n f\"Here's the list of trains in this block: {list(trains_in_block.keys())}\"\n )\n\n elif len(merge_train_id) == 0:\n raise RuntimeError(\n \"it's impossible to get here. \"\n \"if you see this error call an exorcist.\"\n )\n\n merge_train_id = merge_train_id[0]\n merge_train_data = trains_in_block.pop(merge_train_id)\n\n for train_before_split in merge_train_data[\"previous\"]:\n\n prev_train_id = train_before_split\n prev_train_data = trains_in_block.pop(prev_train_id)\n\n # Add block_id to trips before the split, while popping them from trains_in_block\n while prev_train_id:\n self.train_blocks[prev_train_id] = block_id\n\n # Try to find the previous leg by odpt:previousTrainTimetable\n if prev_train_data[\"previous\"]:\n prev_train_id = prev_train_data[\"previous\"][0]\n prev_train_data = trains_in_block.pop(prev_train_id)\n\n # If that fails, try to find next_trip_id in trips' odpt:nextTrainTimetable\n else:\n for potential_train_id, potential_train_data in trains_in_block.items():\n if prev_train_id in potential_train_data[\"next\"]:\n\n prev_train_id = potential_train_id\n prev_train_data = potential_train_data\n\n del trains_in_block[prev_train_id]\n\n break\n else:\n prev_train_id = None\n prev_train_data = None\n\n # Add the merging train to block\n if split_train_id not in self.train_blocks:\n self.train_blocks[split_train_id] = []\n\n self.train_blocks[split_train_id].append((block_id, None))\n\n # Add block_id to trips after merge\n if len(merge_train_data[\"next\"]) == 0:\n block_id += 1\n continue\n\n next_train_id = merge_train_data[\"next\"][0]\n next_train_data = trains_in_block[next_train_id]\n\n # Add block_id to trips after split\n while next_train_id:\n\n if next_train_id not in self.train_blocks:\n self.train_blocks[next_train_id] = []\n\n self.train_blocks[next_train_id].append((block_id, None))\n\n # Try to find the next train by odpt:nextTrainTimetable\n if next_train_data[\"next\"]:\n next_train_id = next_train_data[\"next\"][0]\n next_train_data = trains_in_block[next_train_id]\n\n # If this fails, try to find the current train in other trips' odpt:previousTrainTimetable\n else:\n for potential_train_id, potential_train_data in trains_in_block.items():\n if next_train_id in potential_train_data[\"previous\"]:\n\n next_train_id = potential_train_id\n next_train_data = potential_train_data\n\n break\n else:\n next_train_id = None\n next_train_data = None\n\n\n block_id += 1\n\n def trips(self):\n \"\"\"Parse trips & stop_times\"\"\"\n # Some variables\n self.load_train_directions()\n self.load_train_types()\n main_directions = {}\n\n # Get all trips\n print_log(\"Parsing trips\")\n trips = TrainTripIterator(self.api, self.today)\n\n # Open GTFS trips\n buffer_trips = open(\"gtfs/trips.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer_trips = csv.DictWriter(buffer_trips, GTFS_HEADERS_TRAIN[\"trips.txt\"])\n writer_trips.writeheader()\n\n buffer_times = open(\"gtfs/stop_times.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer_times = csv.DictWriter(buffer_times, GTFS_HEADERS_TRAIN[\"stop_times.txt\"])\n writer_times.writeheader()\n\n # Iteratr over trips\n for trip in trips:\n route_id = trip[\"odpt:railway\"].split(\":\")[1]\n trip_id = trip[\"owl:sameAs\"].split(\":\")[1]\n calendar = trip[\"odpt:calendar\"].split(\":\")[1]\n train_rt_id = trip[\"odpt:train\"].split(\":\")[1] if \"odpt:train\" in trip else \"\"\n\n print_log(f\"Parsing trips: {trip_id}\")\n\n # Ignore ignored routes and non_active calendars\n if route_id not in self.route_data:\n continue\n\n # Add calendar\n service_id = self.calendars.use(route_id, calendar)\n if service_id is None:\n continue\n\n # Destination staion\n if trip.get(\"odpt:destinationStation\") not in [\"\", None]:\n destination_stations = [\n self.get_stop_name(i.split(\":\")[1]) for i in trip[\"odpt:destinationStation\"]\n ]\n\n else:\n destination_stations = [\n self.get_stop_name(timetable_item_station(trip[\"odpt:trainTimetableObject\"][-1]))\n ]\n\n # Block\n block_id = self.train_blocks.get(trip_id, \"\")\n\n # Ignore one-stop that are not part of a block\n if len(trip[\"odpt:trainTimetableObject\"]) < 2 and block_id == \"\":\n continue\n\n # Rail Direction\n if route_id not in main_directions:\n main_directions[route_id] = trip[\"odpt:railDirection\"]\n direction_name = self.train_directions.get(trip[\"odpt:railDirection\"], \"\")\n direction_id = 0 if trip[\"odpt:railDirection\"] == main_directions[route_id] else 1\n\n # Train name\n trip_short_name = trip[\"odpt:trainNumber\"]\n train_names = trip.get(\"odpt:trainName\", {})\n\n train_name = self.get_train_name(train_names, \"ja\")\n train_name_en = self.get_train_name(train_names, \"en\")\n\n if train_name:\n trip_short_name = trip_short_name + \" \" + train_name\n \n if train_name_en:\n trip_short_name_en = trip[\"odpt:trainNumber\"] + \" \" + train_name_en\n self.translations.set_english(trip_short_name, trip_short_name_en)\n\n # Headsign\n trip_headsign = self.get_train_headsigns(route_id, trip,\n destination_stations, direction_name)\n\n # TODO: N'EX route creator\n #tofrom_narita_airport = lambda i: \"odpt.Station:JR-East.NaritaAirportBranch.NaritaAirportTerminal1\" in i.get(\"odpt:originStation\", []) or \\\n # \"odpt.Station:JR-East.NaritaAirportBranch.NaritaAirportTerminal1\" in i.get(\"odpt:destinationStation\", [])\n\n #if rotue_id.startswith(\"JR-East\") and trip_type == \"特急\" and tofrom_narita_airport(trip):\n # route_id = \"JR-East.NaritaExpress\"\n\n # Times\n times = []\n prev_departure = TimeValue(0)\n for idx, stop_time in enumerate(trip[\"odpt:trainTimetableObject\"]):\n stop_id = timetable_item_station(stop_time)\n platform = stop_time.get(\"odpt:platformNumber\", \"\")\n\n if stop_id not in self.valid_stops:\n print_log(f\"reference to a non-existing stop, {stop_id}\", 1)\n continue\n\n # Get time\n arrival = stop_time.get(\"odpt:arrivalTime\")\n departure = stop_time.get(\"odpt:departureTime\")\n\n # Fallback to other time values\n arrival = arrival or departure\n departure = departure or arrival\n\n if arrival: arrival = TimeValue.from_str(arrival)\n if departure: departure = TimeValue.from_str(departure)\n\n # Be sure arrival and departure exist\n if not (arrival and departure): continue\n\n # Fix for after-midnight trips. GTFS requires \"24:23\", while ODPT data contains \"00:23\"\n if arrival < prev_departure: arrival += 86400\n if departure < arrival: departure += 86400\n prev_departure = copy(departure)\n\n times.append({\n \"stop_sequence\": idx, \"stop_id\": stop_id, \"platform\": platform,\n \"arrival_time\": str(arrival), \"departure_time\": str(departure)\n })\n\n # Output\n if type(block_id) is not list:\n writer_trips.writerow({\n \"route_id\": route_id, \"trip_id\": trip_id, \"service_id\": service_id,\n \"trip_short_name\": trip_short_name, \"trip_headsign\": trip_headsign,\n \"direction_id\": direction_id, \"direction_name\": direction_name,\n \"block_id\": block_id, \"train_realtime_id\": train_rt_id\n })\n\n for row in times:\n row[\"trip_id\"] = trip_id\n writer_times.writerow(row)\n\n else:\n for new_block_id, new_dest_ids in block_id:\n new_trip_id = f\"{trip_id}.Block{new_block_id}\"\n\n if new_dest_ids:\n new_dest_stations = [self.get_stop_name(i) for i in new_dest_ids]\n\n new_headsign = self.get_train_headsigns(\n route_id, trip,\n new_dest_stations, direction_name\n )\n\n else:\n new_headsign = trip_headsign\n\n writer_trips.writerow({\n \"route_id\": route_id, \"trip_id\": new_trip_id, \"service_id\": service_id,\n \"trip_short_name\": trip_short_name, \"trip_headsign\": new_headsign,\n \"direction_id\": direction_id, \"direction_name\": direction_name,\n \"block_id\": new_block_id, \"train_realtime_id\": train_rt_id\n })\n\n for row in times:\n row[\"trip_id\"] = new_trip_id\n writer_times.writerow(row)\n\n buffer_trips.close()\n buffer_times.close()\n\n def stops_postprocess(self):\n \"\"\"Process stops and create parent nodes for stations\"\"\"\n stops = OrderedDict()\n names = {}\n avg = lambda i: round(sum(i)/len(i), 8)\n\n # Read file\n print_log(\"Merging stations: loading\")\n\n buffer = open(\"gtfs/stops.txt\", mode=\"r\", encoding=\"utf8\", newline=\"\")\n reader = csv.DictReader(buffer)\n\n for row in reader:\n stop_name_id = row[\"stop_id\"].split(\".\")[-1]\n names[stop_name_id] = row[\"stop_name\"]\n stop_id_suffix = -1\n\n close_enough = False\n while not close_enough:\n stop_id_suffix += 1\n stop_id_wsuffix = stop_name_id + \".\" + str(stop_id_suffix) if stop_id_suffix else stop_name_id\n\n # If there's no stop with such ID, start a new merge group\n if stop_id_wsuffix not in stops:\n stops[stop_id_wsuffix] = []\n close_enough = True\n\n # Special case for stations with the same name that are pretty close, but shouldn't be merged anyway\n elif stop_name_id in SEPARATE_STOPS:\n close_enough = False\n\n # If there is; check distance between current stop and other stop in such merge group\n else:\n saved_location = stops[stop_id_wsuffix][0][\"lat\"], stops[stop_id_wsuffix][0][\"lon\"]\n row_location = float(row[\"stop_lat\"]), float(row[\"stop_lon\"])\n\n # Append current stop to merge group only if it's up to 1km close.\n # If current stop is further, try next merge group\n if distance(saved_location, row_location) <= 1:\n close_enough = True\n\n else:\n close_enough = False\n\n stops[stop_id_wsuffix].append({\n \"id\": row[\"stop_id\"], \"code\": row[\"stop_code\"],\n \"lat\": float(row[\"stop_lat\"]), \"lon\": float(row[\"stop_lon\"])\n })\n\n buffer.close()\n\n # Write new stops.txt\n print_log(\"Merging stations: exporting\")\n\n buffer = open(\"gtfs/stops.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(buffer, GTFS_HEADERS_TRAIN[\"stops.txt\"], extrasaction=\"ignore\")\n writer.writeheader()\n\n for merge_group_id, merge_group_stops in stops.items():\n # If there's only 1 entry for a station in API: just write it to stops.txt\n if len(merge_group_stops) == 1:\n writer.writerow({\n \"stop_id\": merge_group_stops[0][\"id\"],\n \"stop_code\": merge_group_stops[0][\"code\"], \"stop_name\": names[merge_group_id.split(\".\")[0]],\n \"stop_lat\": merge_group_stops[0][\"lat\"], \"stop_lon\": merge_group_stops[0][\"lon\"]\n })\n\n # If there are more then 2 entries, create a station (location_type=1) to merge all stops\n else:\n # Calculate some info about the station\n station_id = \"Merged.\" + merge_group_id\n station_name = names[merge_group_id.split(\".\")[0]]\n station_lat = avg([i[\"lat\"] for i in merge_group_stops])\n station_lon = avg([i[\"lon\"] for i in merge_group_stops])\n\n codes = \"/\".join([i[\"code\"] for i in merge_group_stops if i[\"code\"]])\n\n writer.writerow({\n \"stop_id\": station_id,\n \"stop_code\": codes, \"stop_name\": station_name,\n \"stop_lat\": station_lat, \"stop_lon\": station_lon,\n \"location_type\": 1, \"parent_station\": \"\"\n })\n\n # Dump info about each stop\n for stop in merge_group_stops:\n writer.writerow({\n \"stop_id\": stop[\"id\"],\n \"stop_code\": stop[\"code\"], \"stop_name\": station_name,\n \"stop_lat\": stop[\"lat\"], \"stop_lon\": stop[\"lon\"],\n \"location_type\": 0, \"parent_station\": station_id\n })\n\n buffer.close()\n\n def trips_postprocess(self):\n \"\"\"Process trips.txt and remove trips with inactive services\"\"\"\n print_log(\"Processing trips\")\n os.rename(\"gtfs/trips.txt\", \"gtfs/trips.txt.old\")\n\n # Old file\n in_buffer = open(\"gtfs/trips.txt.old\", mode=\"r\", encoding=\"utf8\", newline=\"\")\n reader = csv.DictReader(in_buffer)\n\n # New file\n out_buffer = open(\"gtfs/trips.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(out_buffer, GTFS_HEADERS_TRAIN[\"trips.txt\"], extrasaction=\"ignore\")\n writer.writeheader()\n\n for row in reader:\n if self.calendars.was_exported(row[\"service_id\"]):\n writer.writerow(row)\n\n else:\n self.remove_trips.add(row[\"trip_id\"])\n\n in_buffer.close()\n out_buffer.close()\n\n os.remove(\"gtfs/trips.txt.old\")\n\n def times_postprocess(self):\n \"\"\"Process stop_times.txt and remove trips with inactive services.\n Has to be called after calling trainparser.trips_postprocess()\"\"\"\n print_log(\"Processing stop_times.txt\")\n os.rename(\"gtfs/stop_times.txt\", \"gtfs/stop_times.txt.old\")\n\n # Old file\n in_buffer = open(\"gtfs/stop_times.txt.old\", mode=\"r\", encoding=\"utf8\", newline=\"\")\n reader = csv.DictReader(in_buffer)\n\n # New file\n out_buffer = open(\"gtfs/stop_times.txt\", mode=\"w\", encoding=\"utf8\", newline=\"\")\n writer = csv.DictWriter(out_buffer, GTFS_HEADERS_TRAIN[\"stop_times.txt\"], extrasaction=\"ignore\")\n writer.writeheader()\n\n for row in reader:\n if row[\"trip_id\"] in self.remove_trips:\n continue\n\n else:\n writer.writerow(row)\n\n in_buffer.close()\n out_buffer.close()\n\n os.remove(\"gtfs/stop_times.txt.old\")\n\n @classmethod\n def parse(cls, apikey, target_file=\"tokyo_trains.zip\"):\n \"\"\"Automatically create Tokyo trains GTFS.\n \n :param apikey: Key to the ODPT API\n :type apikey: str\n\n :param target_file: Path to the result GTFS archive,\n defaults to tokyo_trains.zip\n :type target_file: str or path-like or file-like\n \"\"\"\n clear_directory(\"gtfs\")\n\n self = cls(apikey)\n\n self.load_routes()\n\n self.agencies()\n self.feed_info()\n self.attributions()\n self.stops()\n self.routes()\n self.blocks()\n self.trips()\n self.translations.export()\n self.calendars.export()\n self.stops_postprocess()\n self.trips_postprocess()\n self.times_postprocess()\n\n compress(target_file)\n","sub_path":"src/static_trains.py","file_name":"static_trains.py","file_ext":"py","file_size_in_byte":41556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"163841984","text":"\"\"\"\n API count exceeded - Increase Quota with Membership\n If you encounter an error (API count exceeded - Increase Quota with Membership) you need a VPN\n\n creat by Amir Hossein Tadas & TAHA\n\n instagram = Taha_t_80\n\"\"\"\nimport requests\nimport sys\nimport time\nfrom colorama import Fore\nimport os\nsearch = ['robots.txt',\n 'search/',\n 'admin/',\n 'login/',\n 'sitemap.xml',\n 'sitemap2.xml',\n 'config.php',\n 'wp-login.php',\n 'log.txt',\n 'update.php',\n 'INSTALL.pgsql.txt',\n 'user/login/',\n 'INSTALL.txt',\n 'profiles/',\n 'scripts/',\n 'LICENSE.txt',\n 'CHANGELOG.txt',\n 'themes/',\n 'inculdes/',\n 'misc/',\n 'user/logout/',\n 'user/register/',\n 'cron.php',\n 'filter/tips/',\n 'comment/reply/',\n 'xmlrpc.php',\n 'modules/',\n 'install.php',\n 'MAINTAINERS.txt',\n 'user/password/',\n 'node/add/',\n 'INSTALL.sqlite.txt',\n 'UPGRADE.txt',\n 'INSTALL.mysql.txt']\n\n\ndef __start__():\n try:\n print(Fore.RED+\" [!] Plase Enter WebSite Address \")\n print(Fore.RED+\"\\n [!] for exampel : test.com\\n\")\n url = input(Fore.RED+\" ┌─[\"+Fore.LIGHTGREEN_EX+\"tahat80\"+Fore.BLUE+\"/\"+Fore.WHITE+\"Robots_Scanner\"+Fore.RED+\"\"\"]\n └──╼ \"\"\"+Fore.WHITE+\">> \")\n if 'http' in url:\n pass\n elif 'http' != url:\n url = ('http://'+url)\n\n for i in search:\n time.sleep(0.1)\n\n ur = (url+\"/\"+i)\n reqs = requests.get(ur)\n if reqs.status_code == 200 or reqs.status_code == 405:\n print(Fore.GREEN+\" [+] \" + ur)\n else:\n print(Fore.RED+\" [-] \"+ur)\n try:\n input(Fore.RED+\" [!] \"+Fore.GREEN +\n \"Back To Again (Press Enter...) \")\n except:\n print(\"\")\n sys.exit()\n except:\n print(\"\")\n\n\nif __name__ == '__main__':\n while True:\n try:\n os.system('cls')\n except:\n os.system('clear')\n\n __start__()\n","sub_path":"robots.py","file_name":"robots.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"281060539","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\n# method 4, Morris, time O(n), space O(1)\nclass Solution4(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n res = []\n \n cur = root\n while cur:\n if not cur.left:\n res.append(cur.val)\n cur = cur.right\n else:\n pre = cur.left\n while pre.right and pre.right != cur:\n pre = pre.right\n if not pre.right:\n res.append(cur.val)\n pre.right = cur\n cur = cur.left\n else: # revisit cur, don't update res\n pre.right = None\n cur = cur.right\n \n return res\n\n\n# method 3: iteration, stack\n# time O(n), space O(log(n)) average, worst case O(n)\nclass Solution3(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n res = []\n if not root:\n return res\n \n stack = []\n p = root\n while stack or p:\n if p:\n res.append(p.val)\n stack.append(p)\n p = p.left\n else:\n p = stack.pop()\n p = p.right\n \n return res\n\n\n# recursion, with helper function\nclass Solution2(object):\n def preorderTraversal(self, root):\n \n res = []\n self.preorderHelper(root, res)\n return res\n \n def preorderHelper(self, root, res):\n if not root:\n return\n res.append(root.val)\n for child in [root.left, root.right]:\n self.preorderHelper(child, res)\n\n \n# recursion, no helper function\nclass Solution1(object):\n def preorderTraversal(self, root):\n if not root:\n return []\n res = [root.val]\n res.extend(self.preorderTraversal(root.left))\n res.extend(self.preorderTraversal(root.right))\n return res\n\n\n\"\"\"\nGiven a binary tree, return the preorder traversal of its nodes' values.\n\nExample:\n\nInput: [1,null,2,3]\n 1\n \\\n 2\n /\n 3\n\nOutput: [1,2,3]\nFollow up: Recursive solution is trivial, could you do it iteratively?\n\"\"\"\n","sub_path":"0144. Binary Tree Preorder Traversal.py","file_name":"0144. Binary Tree Preorder Traversal.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"137542171","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nModule implementing MainWindow.\n\"\"\"\n\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QMainWindow\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n# from QT_Test_Tool.Ui_test_tool import Ui_MainWindow\nfrom Ui_test_tool import Ui_MainWindow\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport time\nimport datetime\nimport serial\nimport serial.tools.list_ports\n\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n \"\"\"\n Class documentation goes here.\n \"\"\"\n ser = serial.Serial()\n\n def __init__(self, parent=None):\n \"\"\"\n Constructor\n \n @param parent reference to the parent widget\n @type QWidget\n \"\"\"\n super(MainWindow, self).__init__(parent)\n self.setupUi(self)\n self.init()\n\n\n def init(self):\n now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n self.lineEdit.setText(now_time)\n\n list_ask = [\" \",\"每日抄表\"]\n for ask in list_ask:\n self.comboBox_task.addItem(ask)\n\n list_road = [\"通道1\",\"通道2\",\"通道3\",\"通道4\",\"通道5\",\"通道6\",\"通道7\",\"通道8\"]\n for lr in list_road:\n self.comboBox_2.addItem(lr)\n #\n # def mousePressEvent(self, event):\n # item_text = self.tableWidget.currentItem().text()\n # self.lineEdit_7.setText(item_text)\n\n\n def Check_com(self):\n List_com =[]\n com_port = list(serial.tools.list_ports.comports())\n self.ComboBox_com.clear()\n for lis in com_port:\n List_com.append(lis[0])\n if List_com[0]:\n self.ComboBox_com.addItem(lis[0])\n else:\n self.ComboBox_com.addItem(\"NO Com\")\n\n\n #打开文件,添加文件目录和表地址\n @pyqtSlot()\n def on_toolButton_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n try:\n line_count = 0\n file_path = QtWidgets.QFileDialog.getOpenFileName(self,'打开文件','/')\n file = open(file_path[0])\n self.lineEdit_6.setText(file_path[0])\n for my_date in file.readlines():\n self.tableWidget.setItem(line_count, 0, QTableWidgetItem(str(line_count)))\n self.tableWidget.setItem(line_count, 1, QTableWidgetItem(str(my_date)))\n line_count+=1\n except:\n pass\n\n\n\n #刷新串口,将串口添加到combox中\n @pyqtSlot()\n def on_pushButton_17_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n self.Check_com()\n\n\n #将选择的串口打开\n @pyqtSlot()\n def on_Open_Button_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n self.ser.port = self.ComboBox_com.currentText()\n self.ser.open()\n self.label_11.setStyleSheet(\"image: url(:/Start_Pic/com_open.jpg);\")\n # print(self.ser)\n\n\n @pyqtSlot()\n def on_Close_Button_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n self.ser.close()\n self.label_11.setStyleSheet(\"image: url(:/Start_Pic/com_close.jpg);\")\n\n\n\n #点击单表抄数,发送数据\n @pyqtSlot()\n def on_pushButton_6_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n if self.ser.isOpen():\n send_date = self.lineEdit_7.text()\n self.textEdit_2.append(\"send:\" + send_date)\n send_len = len(send_date)\n self.ser.write(send_date.encode(\"utf-8\"))\n recive_date = self.ser.read(send_len)\n # print(recive_date.decode(\"utf-8\"))\n self.textEdit_2.append(\"recive: \"+str(recive_date.decode(\"utf-8\")))\n\n\n @pyqtSlot()\n def on_pushButton_11_clicked(self):\n \"\"\"\n Slot documentation goes here.\n \"\"\"\n self.textEdit_2.clear()\n\n # @pyqtSlot(QTableWidgetItem)\n # def on_tableWidget_itemPressed(self, item):\n # \"\"\"\n # Slot documentation goes here.\n #\n # @param item DESCRIPTION\n # @type QTableWidgetItem\n # \"\"\"\n # self.lineEdit_7.setText(item.text())\n\n @pyqtSlot(QTableWidgetItem)\n def on_tableWidget_itemDoubleClicked(self, item):\n \"\"\"\n Slot documentation goes here.\n\n @param item DESCRIPTION\n @type QTableWidgetItem\n \"\"\"\n self.lineEdit_7.setText(item.text())\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n sp = QSplashScreen(QPixmap(\"F:\\GitBush\\PyQt5Learner\\QT_Test_Tool\\pic\\log.jpg\"))\n sp.show()\n sp.showMessage(\"程序正在启动。。。。\",Qt.AlignLeft,Qt.green)\n time.sleep(2)\n sp.showMessage(\"正在加载配置文件。。。。\", Qt.AlignLeft, Qt.green)\n time.sleep(2)\n app.processEvents()\n ui = MainWindow()\n ui.show()\n sp.finish(ui)\n sys.exit(app.exec_())\n \n","sub_path":"QT_Test_Tool/test_tool.py","file_name":"test_tool.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"155163223","text":"import codecs as co\n\ndef htmlbuilder(type, content) :\n return '<%s>%s' % (type, content, type)\n\nclass transfiler :\n def __init__(self):\n self.result = ''\n\n def getfilename(self):\n self.filename=input(\"file name:\")\n\n def readfiledata(self):\n with co.open(self.filename, 'r' ,encoding ='utf8') as fd:\n self.data =fd.read()\n print (self.data)\n\n def transfiler(self):\n content=self.data.split('\\n')\n print (content)\n for line in content:\n if len(line) is not 0 and line[0] is '#' :\n con=line.split(\" \")\n tp=\"h\"+str(len(con.pop(0)))\n text=htmlbuilder(tp,con)\n self.result+= text + \"\\n\"\n\n\n def writefile(self):\n filename=self.filename\n list =filename.split(\".\")\n list.pop()\n filename= \" \".join(list) + \".html\"\n with co.open(filename, 'w', encoding ='utf8') as fd:\n fd.write(self.result)\n\nt = transfiler()\nt.getfilename()\nt.readfiledata()\nt.transfiler()\nt.writefile()\n","sub_path":"python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"481349433","text":"import os,re\r\nfrom openpyxl import Workbook,load_workbook\r\n\r\ndef find_plane(txt,sheet,row):\r\n\r\n ans = re.finditer('110,(.*,.*,.*D-?\\d).*\\n(.*,.*,.*D-?\\d).*\\n110,(.*,.*,.*D-?\\d).*\\n.*\\n110,.*\\n.*\\n110,.*\\n.*\\n128,.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n102.*\\n110,.*\\n.*\\n110,.*\\n.*\\n110,.*\\n.*\\n110,.*\\n.*\\n102.*\\n142.*\\n144.*\\n',txt)\r\n ans=list(ans)\r\n\r\n #输出\r\n for i in ans:\r\n col = 1\r\n for o in i.group(1,2,3):\r\n p = chaifen(o)\r\n for u in p:\r\n sheet[row][col].value = u\r\n col += 1\r\n row += 1\r\n\r\ndef find_line(txt,sheet,row):\r\n ans = re.finditer('126,1,1,1,0,0,0,0D0,0D0,1D0,1D0,1D0,1D0,(-?\\d\\.\\d+D-?\\d).*\\n(-?\\d\\.\\d+D-?\\d,-?\\d\\.\\d+D-?\\d),(-?\\d\\.\\d+D-?\\d).*\\n(-?\\d\\.\\d+D-?\\d,-?\\d\\.\\d+D-?\\d),.*\\n.*\\n126,.*\\n.*\\n.*\\n.*\\n.*\\n',txt)\r\n ans=list(ans)\r\n #输出\r\n## print(ans)\r\n for i in ans:\r\n## print(i.group(1))\r\n col = 1 + 9\r\n p = chaifen(i.group(1)+i.group(2))\r\n for u in p:\r\n sheet[row][col].value = u\r\n col += 1\r\n p = chaifen(i.group(3)+i.group(4))\r\n for u in p:\r\n sheet[row][col].value = u\r\n col += 1\r\n row += 1\r\n \r\ndef find_point(txt,sheet,row):\r\n ans = re.finditer('116,.*\\n',txt)\r\n ans=list(ans)\r\n #输出\r\n for i in ans:\r\n col = 1+9+6\r\n for o in chaifen(i.group()):\r\n sheet[row][col].value = o\r\n col += 1\r\n row += 1\r\n\r\n##拆分 'x,y,z' -> x,y,z\r\ndef chaifen(ans):\r\n ps = re.findall('-?\\d\\.\\d+D-?\\d',ans)\r\n ped = []\r\n for i in ps:\r\n ped.append(huanyuan(i))\r\n return ped\r\n\r\n##还原数字 '1.3333D1' -> 13.333\r\ndef huanyuan(p):\r\n t = re.search('D',p)\r\n loc = t.span()[0]\r\n num = float(p[0:loc-1]) * 10**(int(p[loc+1:]))\r\n return num\r\n\r\n##遍历目录\r\ndef walk(path = '.',keyword = None):\r\n for a, b, c in os.walk(path):\r\n break\r\n d = []\r\n\r\n if keyword == None:\r\n return c\r\n \r\n for i in c:\r\n if re.search(keyword,i) != None:\r\n d.append(i)\r\n return d\r\n\r\nfiles = walk('.','.igs')\r\n\r\nrd = load_workbook('temp.xlsx',data_only = 1)\r\n\r\nfor file in files:\r\n filename = file\r\n print(filename)\r\n f = open(filename)\r\n txt = f.read()\r\n row = 3\r\n\r\n #按文件名写入同名sheet, 不存在则复制模板\r\n try:\r\n sheet = rd[filename]\r\n except:\r\n sheet = rd.copy_worksheet(rd['Sheet1'])\r\n sheet.title = filename\r\n \r\n plane = find_plane(txt,sheet,row)\r\n line = find_line(txt,sheet,row)\r\n point = find_point(txt,sheet,row)\r\n \r\n rd.save('temp2.xlsx')\r\nrd.close\r\n","sub_path":"igs.py","file_name":"igs.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"532158441","text":"member = update.effective_chat.get_member(update.message.from_user.id)\nif (member.can_restrict_members) or (member.status == \"creator\") or (member.user.name in config.telegram_admins) or (member.user.name in config.telegram_moders):\n\tif (len(text) == 2) or (len(text) == 3) or (update.message.reply_to_message is not None):\n\t\tuntil_date = 0\n\t\tif update.message.reply_to_message is not None:\n\t\t\ttarget_id = update.message.reply_to_message.from_user.id\n\t\t\ttarget_display_name = f\"[{get_user_display_name(update.message.reply_to_message.from_user)}](tg://user?id={target_id})\"\n\t\t\tif len(text) == 2:\n\t\t\t\tif text[1].isdigit():\n\t\t\t\t\tuntil_date = int(text[1])\n\t\t\t\telse:\n\t\t\t\t\tupdate.message.reply_text(f\"Для бана по ответу на сообщение, требуется время в секундах, а не `{text[1]}`\", parse_mode=\"Markdown\")\n\t\t\t\t\ttarget_id = \"\"\n\t\t\tif (len(text) == 3):\n\t\t\t\tupdate.message.reply_text(f\"Слишком много аргументов для бана по ответу на сообщение.\", parse_mode=\"Markdown\")\n\t\t\t\ttarget_id = \"\"\n\t\telse:\n\t\t\ttarget_id = text[1]\n\t\t\ttarget_display_name = target_id\n\t\t\tif target_id.isdigit():\n\t\t\t\ttarget_display_name = f\"[Пользователь](tg://user?id={target_id})\"\n\t\t\telif target_id[0] == \"@\":\n\t\t\t\ttarget_id = target_id.split(\"@\")[1]\n\t\t\t\ttarget_id = db.execute(f\"SELECT * FROM users WHERE username='{target_id}';\").fetchone()\n\t\t\t\tif target_id is not None:\n\t\t\t\t\ttarget_display_name = f\"[{target_id[3]}](tg://user?id={target_id[0]})\"\n\t\t\t\t\ttarget_id = target_id[0]\n\t\t\t\telse:\n\t\t\t\t\tupdate.message.reply_text(f\"Я не знаю пользователя {target_display_name}.\", parse_mode=\"Markdown\")\n\t\t\t\t\ttarget_id = \"\"\n\t\t\tif len(text) == 3:\n\t\t\t\tuntil_date = int(text[2])\n\t\tif (until_date > 0) and (until_date < 30):\n\t\t\tuntil_date = 30\n\t\tif (update.message.from_user.id == target_id):\n\t\t\tupdate.message.reply_photo(\"AgACAgIAAx0CRXO-MQACAp5ggFXJZlGYSFtV4Fb1aLALheWclgACKbIxGzc2AUjyhubHdWgXhiY0BaQuAAMBAAMCAANtAAO8MwACHgQ\")\n\t\telif update.effective_chat.kick_member(target_id, until_date=int(time.time())+until_date):\n\t\t\tuntil_date_text = \"\"\n\t\t\tif until_date != 0:\n\t\t\t\tuntil_date_text = f\" на\"\n\t\t\t\tuntil_date_delta = str(datetime.timedelta(seconds=until_date)).split(\" days, \")\n\t\t\t\tif len(until_date_delta) == 2:\n\t\t\t\t\tuntil_date_delta_days = until_date_delta[0]\n\t\t\t\t\tuntil_date_delta = until_date_delta[1].split(\":\")\n\t\t\t\telse:\n\t\t\t\t\tuntil_date_delta_days = 0\n\t\t\t\t\tuntil_date_delta = until_date_delta[0].split(\":\")\n\t\t\t\tif int(until_date_delta_days) != 0:\n\t\t\t\t\tuntil_date_text += \" \"\n\t\t\t\t\tuntil_date_text += str(int(until_date_delta_days))\n\t\t\t\t\tif str(int(until_date_delta_days))[-1] in [\"0\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n\t\t\t\t\t\tuntil_date_text += \" дней\"\n\t\t\t\t\telif str(int(until_date_delta_days))[-1] in [\"2\", \"3\", \"4\"]:\n\t\t\t\t\t\tuntil_date_text += \" дня\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tuntil_date_text += \" день\"\n\t\t\t\tif int(until_date_delta[0]) != 0:\n\t\t\t\t\tuntil_date_text += \" \"\n\t\t\t\t\tuntil_date_text += str(int(until_date_delta[0]))\n\t\t\t\t\tif str(int(until_date_delta[0]))[-1] in [\"0\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n\t\t\t\t\t\tuntil_date_text += \" часов\"\n\t\t\t\t\telif str(int(until_date_delta[0]))[-1] in [\"2\", \"3\", \"4\"]:\n\t\t\t\t\t\tuntil_date_text += \" часа\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tuntil_date_text += \" час\"\n\t\t\t\tif int(until_date_delta[1]) != 0:\n\t\t\t\t\tuntil_date_text += \" \"\n\t\t\t\t\tuntil_date_text += str(int(until_date_delta[1]))\n\t\t\t\t\tif str(int(until_date_delta[1]))[-1] in [\"0\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n\t\t\t\t\t\tuntil_date_text += \" минут\"\n\t\t\t\t\telif str(int(until_date_delta[1]))[-1] in [\"2\", \"3\", \"4\"]:\n\t\t\t\t\t\tuntil_date_text += \" минуты\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tuntil_date_text += \" минуту\"\n\t\t\t\tif int(until_date_delta[2]) != 0:\n\t\t\t\t\tuntil_date_text += \" \"\n\t\t\t\t\tuntil_date_text += str(int(until_date_delta[2]))\n\t\t\t\t\tif str(int(until_date_delta[2]))[-1] in [\"0\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n\t\t\t\t\t\tuntil_date_text += \" секунд\"\n\t\t\t\t\telif str(int(until_date_delta[2]))[-1] in [\"2\", \"3\", \"4\"]:\n\t\t\t\t\t\tuntil_date_text += \" секунды\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tuntil_date_text += \" секунду\"\n\t\t\tupdate.message.reply_text(f\"{target_display_name} забанен{until_date_text}.\", parse_mode=\"Markdown\")\n\t\telse:\n\t\t\tupdate.message.reply_text(f\"Не уда��ось забанить {target_display_name}.\", parse_mode=\"Markdown\")\n\telse:\n\t\tupdate.message.reply_text(f\"Пример использования:\\n/{command} <время в секундах>\\nИли просто отправьте /{command} <время в секундах> в ответ на чье-либо сообщение.\\nЕсли не указать время, то будет считаться, что бан навсегда.\")\nelse:\n\tupdate.message.reply_animation(\"CgACAgIAAx0CQvXPNQABHGrDYIBIvDLiVV6ZMPypWMi_NVDkoFQAAq4LAAIwqQlIQT82LRwIpmoeBA\")","sub_path":"commands/ban.py","file_name":"ban.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465512554","text":"# -*- coding: utf-8 -*-\nimport sys\n\nimport re\nimport imp\n\nimp.reload(sys)\nsys.setdefaultencoding('utf8')\nprint(sys.getdefaultencoding())\n\nimport urllib.request, urllib.error, urllib.parse\nfrom bs4 import BeautifulSoup\nfrom random import randint\nimport time\nimport json\nimport codecs\n\n\ndef pages_anjuke():\n home = 'http://sz.fang.anjuke.com/loupan/all/'\n soup = get_soup(home)\n num = soup.select_one(\"span.result em\").string\n size = 30\n page_nums = list(range(1, int(num) / size + 2))\n for page_num in page_nums:\n if page_num == 1:\n page = 'http://sz.fang.anjuke.com/loupan/all/'\n else:\n page = 'http://sz.fang.anjuke.com/loupan/all/p{page_num}/'.format(page_num=page_num)\n print(page)\n yield page\n\n\ndef houses_by_page(page):\n soup = get_soup(page)\n items = soup.find_all('div', \"item-mod\", rel='nofollow')\n for item in items[0:30]:\n name = item.select_one(\"a.items-name\").string\n address = item.select_one(\"a.list-map\").string\n tag = item.find(\"p\", \"price\")\n data_link = item['data-link']\n\n if tag is None:\n price = 0\n else:\n price = int(tag.span.string)\n json_object = {\"type\": \"NEW\", \"name\": name, \"address\": address, \"price\": price, \"data_link\": data_link}\n print(json_object)\n yield json_object\n\n\ndef get_soup(page):\n response = urllib.request.urlopen(page)\n html = response.read()\n soup = BeautifulSoup(html, \"lxml\")\n return soup\n\n\ndef get_json_object(url):\n response = urllib.request.urlopen(url)\n json_object = json.loads(response.read())\n return json_object\n\n\ndef houses_activiti():\n pages = pages_anjuke()\n houses = [] # flatMap\n for page in pages:\n for house in houses_by_page(page):\n houses.append(house)\n houses = [house for house in houses if house['address'].find(\"深圳周边\") == -1]\n houses = list(map(boom_location, houses))\n houses = list(map(boom_rate, houses))\n return houses\n\n\ndef del_field(item, field_name):\n del item[field_name]\n\n\ndef trans_field(item, field_name, func):\n trans = func(item[field_name])\n item = dict(item, **trans) # 合并\n return item\n\n\ndef filter_item(item, field_name, func):\n if func(item, field_name):\n return None\n return item\n\n\ndef filter_by_address(item, field_name):\n return item[field_name] == -1\n\n\ndef boom_location(house):\n address = house['address']\n try:\n url = 'http://api.map.baidu.com/geocoder/v2/' \\\n '?ak=Q0ERGQ0nNRN9xUQs3kqiIK80PUF950zG&output=json&address=%s&city=深圳市' % address\n json_object = get_json_object(url)\n lat = json_object['result']['location']['lat']\n lon = json_object['result']['location']['lng']\n location = {\"lat\": lat, \"lon\": lon}\n print(location)\n return location\n except Exception:\n print(\"trans error in %s\" % address)\n return {}\n\n\ndef boom_rate(house):\n link = house[\"data_link\"]\n try:\n url = link.replace('http://sz.fang.anjuke.com/loupan/', 'http://sz.fang.anjuke.com/loupan/canshu-') \\\n .replace('.html', '.html?from=loupan_index_more')\n soup = get_soup(url)\n plot_ratio = soup.select_one(\n \"#container > div.can-container.clearfix > div.can-left > div:nth-of-type(3) > div.can-border >\"\n \" ul > li:nth-of-type(4) > div.des\").text.replace(\n \"住宅:\", \"\").replace(\"[查看详情]\", \"\").strip()\n plot_ratio = float(re.findall(r\"\\d+\\.?\\d*\", plot_ratio)[0])\n greening_rate = soup.select_one(\n \"#container > div.can-container.clearfix > div.can-left > div:nth-of-type(3) > div.can-border >\"\n \" ul > li:nth-of-type(5) > div.des\").text.replace(\n \"[查看详情]\", \"\").strip().replace(\"%\", \"\")\n greening_rate = float(re.findall(r\"\\d+\\.?\\d*\", greening_rate)[0])\n greening_rate = 0 if greening_rate >= 100 or greening_rate < 0 else greening_rate\n rate = {\"plotRatio\": plot_ratio, \"greeningRate\": greening_rate}\n print(rate)\n return rate\n except Exception:\n print(\"trans error in %s\" % link)\n return {}\n\nif __name__ == '__main__':\n\n time_time = time.time()\n file_name = \"d:/sz-new-house-%s.txt\" % time_time\n pages = pages_anjuke()\n for page in pages:\n time.sleep(randint(1, 2) / 5)\n houses = houses_by_page(page)\n for house in houses:\n rate = boom_rate(house)\n house = dict(house, **rate) # 合并\n location = boom_location(house)\n house = dict(house, **location) # 合并\n del house['data_link']\n f = open(file_name, \"a\")\n f.write(json.dumps(house, ensure_ascii=False) + \"\\n\")\n f.close()\n","sub_path":"cje/cje_in.py","file_name":"cje_in.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"213574148","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'employer_app'\n\nurlpatterns = [\n # Departement URLS\n path('departement/', DepartementList.as_view(), name='departement_listes'),\n path('creer/departement/', DepartementCreate.as_view(), name='creer_departement'),\n path('departement-detail//', DepartementDetail.as_view(), name='departement_details'),\n path('departement/edit//', EditDepartement.as_view(), name='edit_departement'),\n path('departement/delete//', DeleteDepartement.as_view(), name='delete_departement'),\n # path('departementSearch/', DepartementSearch.as_view(), name='rechercher_departement'),\n path('departementSearch/custom/', DepartementListDetailFilter.as_view(), name='rechercher_departement'),\n\n # Employer URLS\n path('employer/', EmployerList.as_view(), name='employer_listes'),\n path('creer/employer/', EmployerCreate.as_view(), name='creer_employer'),\n path('employer-detail//', EmployerDetail.as_view(), name='employer_details'),\n path('employer/edit//', EditEmployer.as_view(), name='edit_employer'),\n path('employer/delete//', DeleteEmployer.as_view(), name='delete_employer'),\n # path('employerSearch/', EmployerSearch.as_view(), name='rechercher_employer'),\n path('employerSearch/custom/', EmployerListDetailFilter.as_view(), name='rechercher_employer'),\n]\n","sub_path":"employer_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"512170374","text":"import os\ndirname = os.path.dirname(__file__)\nimport sys\nsys.path.append(os.path.join(dirname,'/Users/rridden/Documents/work/code/source_synphot/'))\nimport source_synphot.passband as passband\nimport source_synphot.io as io\nimport source_synphot.source\nimport astropy.table as at\nfrom collections import OrderedDict\nimport pysynphot as S\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import interpolate\nimport astropy.table as at\nfrom extinction import fm07, fitzpatrick99, apply, remove\n\n\nimport pandas as pd\nfrom glob import glob\n\n\ndef mangle(spec,pbs,mags,plot=False):\n \"\"\"\n Mangle a spectrum to scale it to observed photometry.\n\n Inputs\n ------\n spec : pysynphot spectrum array\n\n pbs : ordered dict \n dictionary of passbands. first entry is a pysynphot array passband second is the band zeropoint.\n mags : list/array\n list of magnitudes in the same order as the bands\n Options\n -------\n plot : bool\n if true, plots the scale factor\n\n Returns\n -------\n s : pysynphot spectrum array\n input spectrum scalled by the mangling process\n \"\"\"\n scale = np.array((spec.wave,spec.flux))\n scale[1,:] = 1\n i = 0\n inds = []\n for pb in pbs:\n filt = pbs[pb]\n syn_mag = source_synphot.passband.synphot(spec,filt[0],zp=filt[1])\n factor = 10**(-2/5*(mags[i]-syn_mag))\n med_wav = np.average(filt[0].wave,weights = filt[0].throughput)\n ind = np.argmin(abs(scale[0,:] - med_wav))\n inds += [ind]\n scale[1,ind] = factor\n i += 1 \n inds.sort()\n # Scipy interpolation, more flexibility in fit\n #interp = interp1d(scale[0,inds],scale[1,inds],kind='linear',bounds_error=False,fill_value=0)\n #interped = interp(scale[0,:])\n #interped[:min(inds)] = scale[1,min(inds)]\n #interped[:max(inds)] = scale[1,max(inds)]\n \n factors = np.interp(scale[0,:],scale[0,inds],scale[1,inds])\n scale[1,:] = factors\n s = S.ArraySpectrum(spec.wave,spec.flux*scale[1,:])\n if plot:\n plt.figure()\n plt.plot(scale[0,:],factors,'.',label='Spline')\n plt.plot(scale[0,inds],factors[inds],'x',label='references')\n plt.plot(spec.wave,spec.flux/np.nanmax(spec.flux),label='original')\n plt.plot(s.wave,s.flux/np.nanmax(s.flux),label='mangled')\n plt.xlabel('Wave')\n plt.ylabel('normed flux/scale factor')\n plt.savefig('mangle{}.png'.format(spec))\n print('mangle{}.png'.format(spec))\n return s\n\n\ndef Spec_mags(Models,pbs,av=0,Rv=3.1,Conversion = 1.029):\n \"\"\"\n Generate synthetic magnitudes from the models and passbands added.\n Conversion converts between Ebv and Egr, the Green value is 0.981, but the best fit value\n was found to be 1.029.\n \"\"\"\n #a_v = 3.1*(Conversion * ex ) # ex = extinction from Bayestar19 = Egr\n keys = list(pbs.keys())\n mags = {}\n for key in keys:\n mags[key] = []\n \n pb, zp = pbs[key]\n \n # construct mags\n ind = []\n red = {}\n for model in Models:\n if av > 0:\n model = S.ArraySpectrum(model.wave,apply(fitzpatrick99(model.wave,av,Rv),model.flux),\n waveunits=model.waveunits,fluxunits=model.fluxunits)\n if av < 0:\n model = S.ArraySpectrum(model.wave,remove(fitzpatrick99(model.wave,-av,Rv),model.flux),\n waveunits=model.waveunits,fluxunits=model.fluxunits)\n mags[key] += [source_synphot.passband.synphot(model, pb,zp)]\n\n for key in keys:\n mags[key] = np.array(mags[key])\n \n #good = np.ones(len(mags[key])) > 0\n #for key in keys:\n # good = good *np.isfinite(mags[key])\n #for key in keys:\n # mags[key] = mags[key][good]\n return mags\n\n\ndef Specs(Specs):\n specs = {}\n for spec in Specs:\n print(spec)\n model_sed = source_synphot.source.pre_process_source(spec,np.nan,'ps1g',0,Renorm=False)\n specs[spec] = model_sed\n\n return specs\n\n\ndef Syn_mag(pbs,spec):\n mag = {}\n for pb in pbs:\n if spec is not None:\n syn_mag = source_synphot.passband.synphot(spec,pbs[pb][0],zp=pbs[pb][1])\n else:\n syn_mag = np.nan\n mag[pb] = syn_mag\n \n return mag","sub_path":"make_synmags.py","file_name":"make_synmags.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"445370559","text":"def binarySearch(arr, val):\n start = 0\n end = len(arr) - 1\n while start <= end:\n m = start + int((end - start) / 2)\n if arr[m] == val:\n return True\n elif arr[m] < val:\n start = m + 1\n else:\n end = m - 1\n return False\n\n\ndef find_duplicates(arr1, arr2):\n N = min(len(arr1), len(arr2))\n M = max(len(arr1), len(arr2))\n if N == len(arr1):\n a1, a2 = arr1, arr2\n else:\n a1, a2 = arr2, arr1\n result = []\n if int(M / 2) <= N <= M:\n # near equal size\n i, j = 0, 0\n while i < N and j < M:\n if a1[i] == a2[j]:\n result.append(a1[i])\n i += 1\n j += 1\n elif a1[i] < a2[j]:\n i += 1\n else:\n j += 1\n else:\n\n for i in range(N):\n if binarySearch(a2, a1[i]):\n result.append(a1[i])\n return result\n # M is much larger\n\n\n\n\narr1 = [1, 2, 3, 5, 6, 7]\narr2 = [3, 6, 7, 8, 20]\n\nprint(find_duplicates(arr2, arr1))\noutput= [3, 6, 7]\n\nassert find_duplicates(arr2, arr1) == output\n","sub_path":"Prev/find_duplicates.py","file_name":"find_duplicates.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"186032212","text":"# When clusters are closly grouped together Gaussian Mixture \n# transform seperation\n# Python 2 and 3 support\nfrom __future__ import division, unicode_literals, print_function\n\n# Common Imports\nimport os\nimport numpy\n\n\n# ML Imports\n\n# Graph Imports\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Config\nPROJECT_ROOT_DIR = '.'\n\n# Declare Functions\ndef image_path(fig_id):\n if not os.path.exists('images'):\n os.makedirs('images')\n return os.path.join(PROJECT_ROOT_DIR, 'images', fig_id)\n\ndef save_fig(fig_id, tight_layout=True):\n print(\"Saving\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(image_path(fig_id) + \".png\", format=\"png\", dpi=300)\n","sub_path":"dimensionality_reduction/examples/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"521626204","text":"import argparse\nimport logging\nfrom collections import namedtuple\nimport xml.etree.ElementTree\n\nBook = namedtuple('Book', ['id', 'author', 'title', 'genre', 'price', 'publish_date', 'description'])\n\n\nclass XMLParser:\n def __init__(self, file):\n self.file = file\n self.books = []\n\n def run(self):\n logging.basicConfig(format='%(asctime)s - %(name)s: %(message)s', filename='log.log', level=logging.DEBUG)\n logging.getLogger('Analyzing XML').info(self.file)\n\n root = xml.etree.ElementTree.parse(self.file).getroot()\n\n for item in root:\n attributes = item.attrib\n for attribute in item:\n attributes[attribute.tag] = attribute.text\n\n logging.getLogger('Parsed book').info(attributes)\n self.books.append(Book(**attributes))\n\n print(self.books)\n return [ getattr(obj, 'id') for obj in self.books ]\n\ndef main():\n parser = argparse.ArgumentParser(description='XML Parser')\n parser.add_argument('file', help='input file')\n\n xmlparser = XMLParser(parser.parse_args().file)\n return xmlparser.run()\n\nif __name__ == '__main__':\n main()\n","sub_path":"punkt2/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"56792356","text":"# max, return the largest item in an iterable or the largest of two or more args\n# we can pass in list, iterable\n# min will have the same effect but searched for the minimum value\n\nprint(max(2, 45, 66)) # 66\nprint(max('c', 'd', 'a')) # 'd'\nprint(max([1, 2, 3, 4, 5])) # 5\nprint(max('hello world')) # 'w'\n\n# another example\nnames = ['Arya', 'Samson', 'Dora', 'Tim', 'Ollivander']\n\nmin(names) # Arya\nmax(names) # Tim\nmin(len(name) for name in names) # 3\n\nmax(names, key=lambda x: len(x)) # Ollivander\nmin(names, key=lambda x: len(x)) # Tim\n\n","sub_path":"courses/20_lambdas_and_builtin_functions/20-194_min_and_max.py","file_name":"20-194_min_and_max.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"576010347","text":"# -*- coding: utf-8 -*-\n\nfrom Tkinter import *\nimport menu\n\ndef mod_card():\n\tdef read_txt(fname):\n\t\topenfile = open(fname, 'r')\n\n\t\trstr = openfile.readlines()\n\t\tfor i in range(len(rstr)):\n\t\t\trstr[i] = rstr[i].strip().split(',')\n\t\treturn rstr\n\n\t\topenfile.close()\n\n\tdef write_txt(fname, lst):\n\t\toutfile = open(fname, 'w')\n\n\t\tsep = ','\n\t\tfor i in lst:\n\t\t\toutfile.writelines(i[0] + sep + i[1] + '\\n')\n\n\t\toutfile.close()\n\n\n\twindow_col = Tk()\n\n\tleftF = Frame()\n\tleftF.pack(side=LEFT)\n\n\tF1 = Frame(leftF)\n\tscrollbar = Scrollbar(F1)\n\tlistbox = Listbox(F1)\n\n\tscrollbar.pack(side=RIGHT, fill=Y)\n\tlistbox.pack(side=LEFT, fill=Y)\n\n\tscrollbar['command'] = listbox.yview\n\tlistbox['yscrollcommand'] = scrollbar.set\n\n\t# read data.txt\n\tfilename = 'data.txt'\n\tdata = read_txt(filename)\n\tdata_origin = read_txt('data_origin.txt')\n\tfor i in data_origin:\n\t\tlistbox.insert(END, str(i[0]))\n\t\tF1.pack(side=TOP)\n\n\n\trightF = Frame()\n\trightF.pack(side=RIGHT, ipadx=\"3m\", ipady=\"1m\", padx=\"3m\", pady=\"2m\")\n\n\tdef b1Click():\n\t\t#global signal\n\t\tindex = listbox.curselection()[0]\n\t\tcard_name = data_origin[index][0]\n\t\tcard_in_data = False\n\t\tfor c in range(len(data)):\n\t\t\tif data[c][0] == card_name:\n\t\t\t\tcard_in_data = True\n\t\t\t\tprint(\"이미 저장된 카드\")\n\t\t\t\tprint(data)\n\t\t\t\tbreak\n\t\tif card_in_data == False:\n\t\t\ttext = \"signal of \" + card_name\n\t\t\tdata.append([card_name, text])\n\t\t\twrite_txt(filename, data)\n\t\t\tprint(\"삽입 완료\")\n\t\t\tprint(data)\n\n\tdef b2Click():\n\t\tindex = listbox.curselection()[0]\n\t\tcard_name = data_origin[index][0]\n\t\tcard_in_data = False\n\t\tfor c in range(len(data)):\n\t\t\tif data[c][0] == card_name:\n\t\t\t\tcard_in_data = True\n\t\t\t\tdel data[c]\n\t\t\t\twrite_txt(filename, data)\n\t\t\t\tprint(\"삭제 완료\")\n\t\t\t\tprint(data)\n\t\t\t\tbreak\n\t\tif card_in_data == False:\n\t\t\tprint(\"저장되지 않은 카드\")\n\t\t\tprint(data)\n\n\tdef b3Click():\n\t\twindow_col.destroy()\n\t\tmenu.mod_menu()\n\n\tb1 = Button(rightF, command=b1Click) #카드추가\n\tb1.bind(\"\", b1Click)\n\tb1.configure(text=\"카드복제\", background=\"gray\",\n\t\t\twidth=6, padx=\"2m\", pady=\"1m\")\n\tb1.pack(side=TOP)\n\n\tb2 = Button(rightF, command=b2Click) #카드삭제\n\tb2.bind(\"\", b2Click)\n\tb2.configure(text=\"카드삭제\", background=\"gray\",\n\t\t\twidth=6, padx=\"2m\", pady=\"1m\")\n\tb2.pack(side=TOP)\n\n\tb3 = Button(rightF, command=b3Click)\n\tb3.bind(\"\", b3Click)\n\tb3.configure(text=\"메뉴\", background=\"gray\",\n\t\t\twidth=6, padx=\"2m\", pady=\"1m\")\n\tb3.pack(side=TOP)\n\n\n\twindow_col.mainloop()\n\n","sub_path":"server/tk/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"270764506","text":"from conan.packager import ConanMultiPackager\nfrom conans.tools import os_info\nimport copy\n\n\nclass ArduinoPackager(ConanMultiPackager):\n\n def add(self, options={}):\n super().add(settings={\n \"os\": \"Arduino\",\n \"os.board\": \"uno\",\n \"compiler\": \"gcc\",\n \"compiler.version\": \"5.4\",\n \"compiler.libcxx\": \"libstdc++11\",\n \"arch\": \"avr\"\n }, options=options\n , env_vars={\n \"CC\": \"gcc\"\n })\n\nif __name__ == \"__main__\":\n builder = ArduinoPackager(build_policy = \"outdated\")\n builder.add()\n\n if os_info.is_linux:\n filtered_builds = []\n for settings, options, env_vars, build_requires in builder.builds:\n filtered_builds.append(\n [settings, options, env_vars, build_requires])\n new_options = copy.copy(options)\n new_options[\"arduino-sdk:host_os\"] = \"linux32\"\n filtered_builds.append(\n [settings, new_options, env_vars, build_requires])\n builder.builds = filtered_builds\n\n builder.run()\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118772379","text":"'''\ndraw temp change of one specific turtle data and model data.\n'''\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom datetime import datetime, timedelta\nimport netCDF4\nfrom turtleModule import str2list, str2ndlist, np_datetime, bottom_value, closest_num, dist\nimport watertempModule as wtm # A module of classes that using ROMS, FVCOM.\ndef getModTemp(modTempAll, obsTime, obsLayer, obsNearestIndex, starttime, oceantime):\n '''\n Return the mod temp corresponding to observation based on layers, not depth\n '''\n ind = closest_num((starttime -datetime(2013,5,18)).total_seconds()/3600, oceantime)\n modTemp = []\n l = len(obsLayer.index)\n for i in obsLayer.index:\n print(i, l)\n timeIndex = closest_num((obsTime[i]-datetime(2013,5,18)).total_seconds()/3600, oceantime)-ind\n modTempTime = modTempAll[timeIndex]\n # modTempTime[modTempTime.mask] = 10000\n t = [modTempTime[obsLayer[i][j],obsNearestIndex[i][0], obsNearestIndex[i][1]] \\\n for j in range(len(obsLayer[i]))]\n modTemp.append(t)\n modTemp = np.array(modTemp)\n return modTemp\ndef smooth(v, e):\n '''\n Smooth the data, get rid of data that changes too much.\n '''\n for i in range(2, len(v)-1):\n a, b, c = v[i-1], v[i], v[i+1]\n diff1 = abs(b - c) #diff1 is not used\n diff2 = abs(b - a)\n if diff2>e:\n v[i] = a\n return v\n#########################################################\nobsData = pd.read_csv('ctdWithModTempByDepth.csv', index_col=0)\ntf_index = np.where(obsData['TF'].notnull())[0]\nobsData = obsData.ix[tf_index]\nid = obsData['PTT'].drop_duplicates().values\n#print('turtle id:', id)\ntID = id[3] # 0~4, 6,7,8,9, turtle ID.\nlayers = pd.Series(str2ndlist(obsData['modDepthLayer'], bracket=True), index=obsData.index) # If str has '[' and ']', bracket should be True.\nmodNearestIndex = pd.Series(str2ndlist(obsData['modNearestIndex'].values, bracket=True), index=obsData.index)\nobsTemp = pd.Series(str2ndlist(obsData['TEMP_VALS'].values), index=obsData.index)\nobsTime = pd.Series(np_datetime(obsData['END_DATE'].values), index=obsData.index)\nmodTemp = pd.Series(str2ndlist(obsData['modTempByDepth'].values,bracket=True), index=obsData.index)\nlayers = layers[obsData['PTT']==tID]\nmodNearestIndex = modNearestIndex[obsData['PTT']==tID]\ntime = obsTime[obsData['PTT']==tID]\ntemp = obsTemp[obsData['PTT']==tID]\n#modTemp=pd.Series(str2ndlist(obsData['TEMP_VALS'][temp.index],bracket=True), index=temp.index)\n'''\nstarttime, endtime=np.amin(time), np.amax(time)+timedelta(hours=1)\nmodObj = wtm.waterCTD()\nurl = modObj.get_url(starttime, endtime) #something wrong with ROMS website\noceantime = netCDF4.Dataset(url).variables['ocean_time']\nmodTempAll = netCDF4.Dataset(url).variables['temp']\nmodTemp = getModTemp(modTempAll, obsTime, layers, modNearestIndex, starttime, oceantime)\nmodTemp = pd.Series(modTemp, index=temp.index)\n'''\nobsMaxTemp, obsMinTemp = [], []\nmodMaxTemp, modMinTemp = [], []\nfor i in temp.index: #this loop calculate min & max temperature of each dive\n obsMaxTemp.append(max(temp[i]))\n obsMinTemp.append(min(temp[i]))\n modMaxTemp.append(max(modTemp[i]))\n modMinTemp.append(min(modTemp[i]))\ndata = pd.DataFrame({'time':time.values, 'obsMaxTemp':obsMaxTemp, 'obsMinTemp':obsMinTemp,\n 'modMaxTemp': modMaxTemp, 'modMinTemp': modMinTemp}, index=range(len(time)))\ndata = data.sort_index(by='time')\n\ndata['obsMinTemp'] = smooth(data['obsMinTemp'].values, 5)\ndata['modMinTemp'] = smooth(data['modMinTemp'].values, 5)\n# data['time'] = smooth(data['time'].values, timedelta(days=20))\n'''\nfor i in range(1, len(data['obsMinTemp'])):\n obsMin = data['obsMinTemp'][i]\n obsMax = data['obsMaxTemp'][i]\n modMin = data['modMinTemp'][i]\n modMax = data['modMaxTemp'][i]\n if obsMin==obsMax:\n data['obsMinTemp'][i]=data['obsMaxTemp'][i-1]\n if modMin==modMax:\n data['modMinTemp'][i]=data['modMaxTemp'][i-1]\n'''\nDate=[]\nfor i in data.index:\n Date.append(data['time'][i])\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(Date, data['obsMaxTemp'], color='b', linewidth=2,label='max')\nplt.plot(Date, data['obsMinTemp'],'--', color='b', linewidth=2, label='min')\n#ax.plot(Date, data['modMaxTemp'], color='r', linewidth=2)\n#ax.plot(Date, data['modMinTemp'], color='r', linewidth=2, label='modeled')\nplt.legend()\nplt.xlabel('Time(2013)', fontsize=14)\nplt.ylabel('Temperature(degc)', fontsize=14)\n\ndates = mpl.dates.drange(np.amin(time), np.max(time), timedelta(days=30))\ndateFmt = mpl.dates.DateFormatter('%b')\nax.set_xticks(dates)\nax.xaxis.set_major_formatter(dateFmt)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\nplt.title('Time series of temp for turtle:{0}'.format(tID), fontsize=14)\nplt.savefig('timeSeries.png', dpi=200)\nplt.show()\n'''\nfig = plt.figure()\nax2 = fig.add_subplot(212)\nfor i in temp.index:\n # ax2.plot(([time[i]+timedelta(hours=5)])*len(temp[i]), temp[i],color='b')\n ax2.plot([time[i]]*len(temp[i]), modTemp[i], color='r')\nax2.set_xlabel('Time', fontsize=20)\nax2.set_ylabel('Temperature', fontsize=20)\ndates = mpl.dates.drange(np.amin(time), np.max(time), timedelta(days=30))\ndateFmt = mpl.dates.DateFormatter('%b,%Y')\nax2.set_xticks(dates)\nax2.xaxis.set_major_formatter(dateFmt)\nax2.set_title('Model', fontsize=20)\nplt.xticks(fontsize=20)\nplt.yticks(fontsize=20)\n\n\nax1 = fig.add_subplot(211)\nfor i in temp.index:\n ax1.plot([time[i]]*len(temp[i]), temp[i], color='b')\nax1.set_ylabel('Temperature', fontsize=20)\nax1.set_xticks(dates)\nax1.xaxis.set_major_formatter(dateFmt)\nax1.set_title('Observation', fontsize=20)\nplt.xticks(fontsize=10)\nplt.yticks(fontsize=20)\nfig.suptitle('Time series of temp for turtle:{0}'.format(tID), fontsize=25)\nax2.set_yticks(ax1.get_yticks())\nplt.show()\n'''\n","sub_path":"timeSeries_nomodel.py","file_name":"timeSeries_nomodel.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"516689848","text":"from __future__ import division\nimport os\nimport sys\nimport cv2 \nimport time\nimport re\nimport random \nimport torch \nimport torch.nn as nn\nimport numpy as np\nimport pandas as pd\nimport pickle as pkl\nfrom torch.autograd import Variable\nfrom util import *\nfrom darknet import Darknet\nfrom preprocess import prep_image, inp_to_image, letterbox_image\nfrom datetime import datetime as dt\nfrom scipy.stats import norm\n\n\nsys.path.append('D:/Github/final_project_sdc')\nimport my_params\nfrom build_pointcloud import build_pointcloud\nfrom transform import build_se3_transform\nfrom image import load_image\nfrom camera_model import CameraModel\n\ndef get_test_input(input_dim, CUDA):\n img = cv2.imread('yolo/test_img/car.jpg')\n img = cv2.resize(img, (input_dim, input_dim)) \n img_ = img[:,:,::-1].transpose((2,0,1))\n img_ = img_[np.newaxis,:,:,:]/255.0\n img_ = torch.from_numpy(img_).float()\n img_ = Variable(img_)\n \n if CUDA:\n img_ = img_.cuda()\n \n return img_\n\ndef prep_image(img, inp_dim):\n \"\"\"\n Prepare image for inputting to the neural network. \n \n Returns a Variable \n \"\"\"\n\n orig_im = img\n dim = orig_im.shape[1], orig_im.shape[0]\n img = (letterbox_image(orig_im, (inp_dim, inp_dim)))\n img_ = img[:,:,::-1].transpose((2,0,1)).copy()\n img_ = torch.from_numpy(img_).float().div(255.0).unsqueeze(0)\n return img_, orig_im, dim\n\ndef write(x, img):\n c1 = tuple(x[1:3].int()) \n c2 = tuple(x[3:5].int())\n cls = int(x[-1]) \n label = \"{0}\".format(classes[cls])\n color = random.choice(colors)\n cv2.rectangle(img, c1, c2,color, 1)\n t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1 , 1)[0]\n c2 = c1[0] + t_size[0] + 3, c1[1] + t_size[1] + 4\n cv2.rectangle(img, c1, c2,color, -1)\n cv2.putText(img, label, (c1[0], c1[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225,255,255], 1)\n return img\n\n\nif __name__ == '__main__':\n\n output_lidar_patch = my_params.output_dir+'\\\\lidar\\\\'\n output_yolo_patch = my_params.output_dir+'\\\\yolo\\\\'\n # Yolo intial \n confidence = float(my_params.yolo_confidence)\n nms_thesh = float(my_params.yolo_nms_thresh)\n\n start = 0\n CUDA = torch.cuda.is_available()\n\n num_classes = 80\n CUDA = torch.cuda.is_available()\n \n bbox_attrs = 5 + num_classes\n \n print(\"Loading network.....\")\n model = Darknet(my_params.yolo_cfg)\n model.load_weights(my_params.yolo_weights)\n print(\"Network successfully loaded\")\n\n model.net_info[\"height\"] = my_params.yolo_reso\n inp_dim = int(model.net_info[\"height\"])\n assert inp_dim % 32 == 0 \n assert inp_dim > 32\n\n if CUDA:\n model.cuda()\n \n model(get_test_input(inp_dim, CUDA), CUDA)\n model.eval()\n \n classes = load_classes(my_params.yolo_data + 'fix.names')\n colors = pkl.load(open(my_params.yolo_data + \"pallete\", \"rb\"))\n scale = 1\n width, height = (1280, 960)\n dim = (int(scale*width), int(scale*height))\n\n # Lidar intial and camera pose\n lidar = re.search('(lms_front|lms_rear|ldmrs|velodyne_left|velodyne_right)', my_params.laser_dir).group(0)\n lidar_timestamps_path = os.path.join(my_params.dataset_patch, lidar + '.timestamps')\n\n camera = re.search('(stereo|mono_(left|right|rear))', my_params.image_dir).group(0)\n camera_timestamps_path = os.path.join(os.path.join(my_params.dataset_patch, camera + '.timestamps'))\n\n prj_model = CameraModel(my_params.model_dir, my_params.image_dir)\n poses_file = my_params.poses_file\n extrinsics_dir = my_params.extrinsics_dir\n intrinsics_path = my_params.project_patch + 'models\\\\stereo_narrow_left.txt'\n\n with open(intrinsics_path) as intrinsics_file:\n vals = [float(x) for x in next(intrinsics_file).split()]\n focal_length = (vals[0], vals[1])\n principal_point = (vals[2], vals[3])\n\n G_camera_image = []\n for line in intrinsics_file:\n G_camera_image.append([float(x) for x in line.split()])\n G_camera_image = np.array(G_camera_image)\n\n print('(f1,f2) =', focal_length)\n print('(c1,c2) =', principal_point)\n\n with open(os.path.join(os.path.join(my_params.extrinsics_dir, camera + '.txt'))) as extrinsics_file:\n extrinsics = [float(x) for x in next(extrinsics_file).split(' ')]\n G_camera_vehicle = build_se3_transform(extrinsics)\n G_camera_posesource = None\n\n # VO frame and vehicle frame are the same\n G_camera_posesource = G_camera_vehicle\n\n # Get image form timestamp\n with open(camera_timestamps_path) as timestamps_file:\n for i, line in enumerate(timestamps_file):\n if (i < 2560):\n continue\n image_timestamp = int(line.split(' ')[0])\n image_path = os.path.join(my_params.image_dir, str(image_timestamp) + '.png')\n print('image_path',image_path)\n image = load_image(image_path, prj_model)\n \n print('Image available')\n # Find correct Lidar data\n with open(lidar_timestamps_path) as lidar_timestamps_file:\n for j, row in enumerate(lidar_timestamps_file):\n lidar_timestamps = int(row.split(' ')[0])\n\n if (lidar_timestamps > image_timestamp):\n start_time = image_timestamp\n end_time = image_timestamp + 5e6 # default 5e6\n print('Lidar available')\n break\n break\n\n lidar_timestamps_file.close()\n timestamps_file.close()\n\n pointcloud, reflectance = build_pointcloud(my_params.laser_dir, poses_file, extrinsics_dir, \n start_time, end_time, lidar_timestamps)\n pointcloud = np.dot(G_camera_posesource, pointcloud) \n uv, depth = prj_model.project(pointcloud, image.shape)\n\n print('Now process with image')\n # Set input image\n frame_patch = os.path.join(my_params.reprocess_image_dir + '//' + str(image_timestamp) + '.png')\n frame = cv2.imread(frame_patch) # must processed imagte\n # resize\n frame= cv2.rectangle(frame,(np.float32(50),np.float32(np.shape(frame)[0])),(np.float32(1250),np.float32(800)),(0,0,0),-1)\n frame = cv2.resize(frame,dim)\n # resize\n \n pframe = frame.copy()\n pcloud = np.zeros((height,width),dtype=float)\n\n # Make lidar depth map\n # print('max depth ', np.max(depth))\n for k in range(uv.shape[1]):\n if (depth[k]>50): continue\n x_lidar = (int)(np.ravel(uv[:,k])[0])\n y_lidar = (int)(np.ravel(uv[:,k])[1])\n pcloud[y_lidar,x_lidar] = float(depth[k])\n\n img, orig_im, dim = prep_image(frame, inp_dim)\n im_dim = torch.FloatTensor(dim).repeat(1,2) \n \n if CUDA:\n im_dim = im_dim.cuda()\n img = img.cuda()\n \n with torch.no_grad(): \n output = model(Variable(img), CUDA)\n output = write_results(output, confidence, num_classes, nms = True, nms_conf = nms_thesh)\n im_dim = im_dim.repeat(output.size(0), 1)\n scaling_factor = torch.min(inp_dim/im_dim,1)[0].view(-1,1)\n \n output[:,[1,3]] -= (inp_dim - scaling_factor*im_dim[:,0].view(-1,1))/2\n output[:,[2,4]] -= (inp_dim - scaling_factor*im_dim[:,1].view(-1,1))/2\n \n output[:,1:5] /= scaling_factor\n \n for i in range(output.shape[0]):\n output[i, [1,3]] = torch.clamp(output[i, [1,3]], 0.0, im_dim[i,0])\n output[i, [2,4]] = torch.clamp(output[i, [2,4]], 0.0, im_dim[i,1])\n \n \n # Prediction image \n # list(map(lambda x: write(x, orig_im), output)) \n # cv2.imshow(\"frame\", orig_im)\n\n # Prediction image with pointcloud\n for k in range(uv.shape[1]):\n x_lidar = (int)(np.ravel(uv[:,k])[0])\n y_lidar = (int)(np.ravel(uv[:,k])[1])\n color = (int(255-8*depth[k]),255-3*depth[k],50+3*depth[k])\n pframe= cv2.circle(pframe, (x_lidar, y_lidar), 1, color, 1) \n \n # list(map(lambda x: write(x, pframe), output)) \n # cv2.imshow(\"output\", pframe)\n\n # Output bbox\n print('Number of bbox',output.shape[0])\n bframe = pframe.copy()\n\n object_data = []\n output_objs = []\n plt.figure()\n plt.scatter(0,0,c='r',marker='o', zorder=0) # original\n # list(map(lambda x: print(x), output))\n for i in range(int(output.shape[0])):\n\n x = output[i,:]\n c1 = tuple(x[1:3].int()) \n c2 = tuple(x[3:5].int())\n cls = int(x[-1]) \n label = \"{0}\".format(classes[cls])\n\n if (label == '0' ): continue\n \n color = random.choice(colors)\n cv2.rectangle(bframe, c1, c2,color, 1)\n t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1 , 1)[0]\n c2 = c1[0] + t_size[0] + 3, c1[1] + t_size[1] + 4\n cv2.rectangle(bframe, c1, c2,color, -1)\n cv2.putText(bframe, label, (c1[0], c1[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225,255,255], 1)\n \n rec = pcloud[x[2].int():x[4].int(),x[1].int():x[3].int()]\n # rec = rec.ravel()\n rec = rec.flatten()\n\n in_obj = [i for i in range(0, len(rec)) if rec[i] > 0]\n rec = rec[in_obj]\n dis, std = norm.fit(rec)\n dis = '{:.2f}'.format(dis)\n\n cv2.putText(bframe, str(dis)+' m', (c1[0], c2[1]-30), cv2.FONT_HERSHEY_PLAIN, 1, [0,0,255], 1)\n\n crop_img = frame[x[2].int():x[4].int(),x[1].int():x[3].int()]\n object_data.append(crop_img)\n\n obj_v = int((x[2].int()+x[4].int())/2)\n obj_u = int((x[1].int()+x[3].int())/2)\n \n obj_x = (obj_u - principal_point[0])*float(dis)/focal_length[0] \n obj_y = (obj_v - principal_point[1])*float(dis)/focal_length[1]\n\n print(label, ':', obj_x, obj_y, dis)\n # print(obj_x,obj_y)\n\n plt.scatter(float(obj_x),float(dis),c='b',marker='.', zorder=1)\n plt.text(float(obj_x)-5,float(dis)+2, label)\n\n cv2.imshow(\"bframe\", bframe)\n\n axes = plt.gca()\n axes.set_xlim([-30,30])\n axes.set_ylim([-5,55])\n plt.show()\n\n\n # Save lidar np matrix\n # np.savetxt(output_lidar_patch + str(image_timestamp) +'.csv', pcloud, delimiter=\",\")\n # Save output yolo\n # np.savetxt(output_yolo_patch + str(image_timestamp) +'.csv', output, delimiter=\",\")\n\n\n\n key = cv2.waitKey(0)\n if key & 0xFF == ord('q'):\n print('done!')\n cv2.destroyAllWindows()\n\n\n \n\n","sub_path":"yolo/yolo_lidar_distance_one_image.py","file_name":"yolo_lidar_distance_one_image.py","file_ext":"py","file_size_in_byte":10302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"638158023","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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.win32\\egg\\dragonfly\\engines\\dictation_natlink.py\n# Compiled at: 2009-04-06 11:18:28\n\"\"\"\nDictation container class for Natlink\n============================================================================\n\nThis class is derived from :class:`DictationContainerBase` and implements \ndictation formatting for the Natlink and Dragon NaturallySpeaking engine.\n\n\"\"\"\ntry:\n import natlink\nexcept ImportError:\n natlink = None\n\nfrom ..log import get_log\nfrom .dictation_base import DictationContainerBase\n\nclass NatlinkDictationContainer(DictationContainerBase):\n \"\"\"\n Container class for dictated words as recognized by the\n :class:`Dictation` element for the Natlink and DNS engine.\n\n \"\"\"\n\n def __init__(self, words):\n DictationContainerBase.__init__(self, words=words)\n\n def format(self):\n \"\"\" Format and return this dictation. \"\"\"\n state = FormatState()\n return state.format_words(self._words)\n\n\nclass Word(object):\n _flag_names = ('custom', 'undefined', 'undefined', 'undeletable', 'cap next', 'force cap next',\n 'upper next', 'lower next', 'no space after', 'double space after',\n 'no space between', 'cap mode', 'upper mode', 'lower mode', 'no space mode',\n 'normal space mode', 'None', 'not after period', 'no formatting',\n 'keep space', 'keep cap', 'no space before', 'normal cap mode',\n 'newline after', 'double newline after', 'no cap in title', 'None',\n 'space after', 'None', 'None', 'vocab builder', 'None')\n _flag_bits = dict(zip(_flag_names, [ 1 << index for index in xrange(32) ]))\n _replacements = {'one': ('1', 1024), \n 'two': ('2', 1024), \n 'three': ('3', 1024), \n 'four': ('4', 1024), \n 'five': ('5', 1024), \n 'six': ('6', 1024), \n 'seven': ('7', 1024), \n 'eight': ('8', 1024), \n 'nine': ('9', 1024)}\n\n def __init__(self, word):\n if word in self._replacements:\n (word, self._info) = self._replacements[word]\n else:\n self._info = natlink.getWordInfo(word)\n self._word = word\n index = word.rfind('\\\\')\n if index == -1:\n self.written = word\n self.spoken = word\n else:\n self.written = word[:index]\n self.spoken = word[index + 1:]\n for (name, bit) in Word._flag_bits.items():\n self.__dict__[name.replace(' ', '_')] = self._info & bit != 0\n\n def __str__(self):\n flags = [ flag for flag in self._flag_names if self._info & self._flag_bits[flag]\n ]\n flags.insert(0, '')\n return '%s(%r%s)' % (self.__class__.__name__, self._word,\n (', ').join(flags))\n\n\nclass FormatState(object):\n _log = get_log('dictation.formatter')\n (normal, capitalize, upper, lower, force) = range(5)\n (normal, no, double) = range(3)\n\n def __init__(self, cap=normal, cap_mode=normal, spacing=no, spacing_mode=normal, between=False):\n self.capitalization = cap\n self.capitalization_mode = cap_mode\n self.spacing = spacing\n self.spacing_mode = spacing_mode\n self.between = between\n\n def apply_formatting(self, word):\n c = self.capitalization\n if c == self.normal or word.no_formatting:\n written = word.written\n elif c == self.force:\n written = word.written.capitalize()\n elif c == self.capitalize:\n written = word.written.capitalize()\n elif c == self.upper:\n written = word.written.upper()\n elif c == self.lower:\n written = word.written.lower()\n else:\n raise ValueError('Unexpected internal state')\n if word.no_space_before or word.no_formatting:\n prefix = ''\n elif self.between and word.no_space_between:\n prefix = ''\n elif self.spacing == self.normal:\n prefix = ' '\n elif self.spacing == self.no:\n prefix = ''\n elif self.spacing == self.double:\n prefix = ' '\n else:\n raise ValueError('Unexpected internal state')\n if word.newline_after:\n suffix = '\\n'\n elif word.double_newline_after:\n suffix = '\\n\\n'\n elif word.space_after:\n suffix = ' '\n else:\n suffix = ''\n return ('').join((prefix, written, suffix))\n\n def update_state(self, word):\n if word.normal_cap_mode:\n self.capitalization_mode = self.normal\n elif word.cap_mode:\n self.capitalization_mode = self.capitalize\n elif word.upper_mode:\n self.capitalization_mode = self.upper\n elif word.lower_mode:\n self.capitalization_mode = self.lower\n if word.force_cap_next:\n self.capitalization = self.force\n elif word.cap_next:\n self.capitalization = self.capitalize\n elif word.upper_next:\n self.capitalization = self.upper\n elif word.lower_next:\n self.capitalization = self.lower\n elif not word.keep_cap:\n self.capitalization = self.capitalization_mode\n if word.no_space_mode:\n self.spacing_mode = self.no\n elif word.normal_space_mode:\n self.spacing_mode = self.normal\n if word.no_space_after:\n self.spacing = self.no\n elif word.double_space_after:\n self.spacing = self.double\n elif not word.keep_space:\n self.spacing = self.spacing_mode\n self.between = word.no_space_between\n\n def format_words(self, words):\n output = []\n for word in words:\n if not isinstance(word, Word):\n word = Word(word)\n if self._log:\n self._log.debug(\"Formatting word: '%s'\" % word)\n output.append(self.apply_formatting(word))\n self.update_state(word)\n\n output = ('').join(output)\n if self._log:\n self._log.debug(\"Formatted output: '%s'\" % output)\n return output","sub_path":"pycfiles/dragonfly-0.6.5-py2.5/dictation_natlink.py","file_name":"dictation_natlink.py","file_ext":"py","file_size_in_byte":6263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"92488871","text":"import random\nimport time\nimport sys\n\ndef Hero():\n print(\"Please create a character.\")\n print(\"Would you like your character to be male or female?\")\n print(\"Enter \\\"m\\\" or \\\"f\\\"\")\n genderIn = input(\"> \")\n print(\"What would you like your character's name to be?\")\n name = input(\"> \")\n print(\"Generating random statistics...\")\n time.sleep(3)\n if genderIn == \"m\":\n gender = \"Male\"\n global hp\n hp = random.randint(7,12)\n global ad\n ad = random.randint(3,6)\n global speed\n speed = random.randint(1,3)\n global pot\n pot = random.randint(0,2)\n elif genderIn == \"f\":\n gender = \"Female\"\n hp = random.randint(5,9)\n ad = random.randint(2,4)\n speed = random.randint(2,5)\n pot = random.randint(0,2)\n else:\n print(\"Error in character generation. Please restart.\")\n sys.exit(0)\n \n print(\"Character Generation Complete\")\n print(\"Statistics:\")\n time.sleep(.5)\n print(\"Name =\",name)\n time.sleep(.5)\n print(\"Gender =\",gender)\n time.sleep(.5)\n print(\"Health =\",hp)\n time.sleep(.5)\n print(\"Attack =\",ad)\n time.sleep(.5)\n print(\"Speed =\",speed)\n time.sleep(.5)\n print(\"Health Potions =\",pot)\n time.sleep(2)\n\n\n\n\ndef setup():\n Hero()\n print(\"Welcome to...\")\n print(\"\")\n print(\"\")\n print(\"\")\n print(\"\")\n print(\" ██████╗ ███████╗██╗ ██╗██╗██╗ ███████╗ ██╗ ██╗ ██████╗ ██████╗ ██████╗ ███████╗ \")\n print(\" ██╔══██╗██╔════╝██║ ██║██║██║ ██╔════╝ ██║ ██║██╔═══██╗██╔═══██╗██╔══██╗██╔════╝ \")\n print(\" ██║ ██║█████╗ ██║ ██║██║██║ ███████╗ ██║ █╗ ██║██║ ██║██║ ██║██║ ██║███████╗ \")\n print(\" ██║ ██║██╔══╝ ╚██╗ ██╔╝██║██║ ╚════██║ ██║███╗██║██║ ██║██║ ██║██║ ██║╚════██║ \")\n print(\" ██████╔╝███████╗ ╚████╔╝ ██║███████╗███████║ ╚███╔███╔╝╚██████╔╝╚██████╔╝██████╔╝███████║ \")\n print(\" ╚═════╝ ╚══════╝ ╚═══╝ ╚═╝╚══════╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝ \")\n print(\"\")\n print(\"\")\n print(\"\")\n print(\"You decide to go on a walk through the woods. However, you don't realize that the part of the woods you are going through is infested with many dangerous monsters.\")\n print(\"You grab your sword and shield from the mount on your wall and open your door to a new aventure.\")\n time.sleep(3)\n\n\n\ndef enemy():\n names = [\"octorok\", \"moblin\", \"stalfos\", \"kodono\", \"armos\", \"keese\"]\n global ename\n ename = random.choice(names)\n global ehp\n ehp = random.randint(4,8)\n global ead\n ead = random.randint(1,3)\n global item\n item = random.randint(0,2)\n global espeed\n espeed = random.randint(1,5)\n print(\"An enemy\",ename,\"appears!\")\n print(ename,\"'s stats:\")\n print(\"Health =\",ehp)\n print(\"Attack =\",ead)\n\n\n\ndef die():\n print(\"You lost all of your health. You fall to the ground exauhsted just wanting to rest. You feel your life slipping away as your eyes close.\")\n print (\n\n \"\"\"\n _____ ___ ___ ___ _____ _____ _ _ ___________\n | __ \\ / _ \\ | \\/ || ___| | _ || | | | ___| ___ \\\\\n | | \\// /_\\ \\| . . || |__ | | | || | | | |__ | |_/ /\n | | __ | _ || |\\/| || __| | | | || | | | __|| / \n | |_\\ \\| | | || | | || |___ \\ \\_/ /\\ \\_/ / |___| |\\ \\\\ \n \\\\____/\\_| |_/\\_| |_/\\____/ \\___/ \\___/\\____/\\_| \\_|\n \"\"\"\n )\ndef nonEncounter():\n print(\"You come to a clearing and look around. You spot a colorful mushroom lying in the crevice between a tree root and the ground.\")\n print(\"You go closer to the mushroom. It doesn't look poisonous, but you can't be sure.\")\n print(\"Do you eat it?(\\\"y\\\" or \\\"n\\\")\")\n var = input(\"> \")\n if var == \"y\":\n goodBad = random.randint(0,2)\n if goodBad == 2:\n mushEff = random.randint(0,1)\n if mushEff == 1:\n print(\"You decide to take a chance. You pick the mushroom up and take a bite. The taste is peculiar. You don't feel anything right away, but then suddenly, your sore muscles feel envigorated. Attack + 2.\")\n Hero.ad += 2\n elif mushEff == 0:\n print(\"You decide to take a chance. You pick the mushroom up and take a bite. The taste is peculiar. You don't feel anything right away, but then suddenly, your exhausted body feels healed. Health + 5\")\n Hero.hp += 5\n elif goodBad != 2:\n print(\"You decide to take a chance. You pick the mushroom up and take a bite. The taste is peculiar. You don't feel anything right away, but then suddenly, you fall to the ground, clutching your stomach. Turns out the mushroom was poisonous after all.\")\n die()\n elif var == \"n\":\n print(\"You decide to not take a chance. You leave the mushroom and move on.\")\n\n\ndef attack():\n if speed >= espeed:\n speedcheck = random.randint(0,3)\n if speedcheck == 3:\n print(\"The enemy\",ename,\"manages to outspeed you.\")\n print(\"You take\",ead,\"damage.\")\n hp = hp - ead\n else:\n print(\"You outsped the\",ename,\"and struck first.\")\n print(\"The\",ename,\"takes\",ad,\"damage.\")\n ehp = ehp - ad\n else:\n speedcheck = random.randint(0,1)\n if speedcheck == 1:\n print(\"You outsped the\",ename,\"and struck first.\")\n print(\"The\",ename,\"takes\",ad,\"damage\")\n ehp = ehp - ad\n else:\n print(\"The enemy\",ename,\"manages to outspeed you.\")\n print(\"You take\",ead,\"damage.\")\n hp = hp - ead\n\ndef defend():\n if speed >= espeed:\n speedcheck = random.randint(0,3)\n if speedcheck == 3:\n print(\"You try to block the\",ename,\"'s attack but are too slow.\")\n print(\"You take\",ead,\"damage.\")\n hp = hp - ead\n else:\n print(\"You get your block up in time and you hear the\",ename,\"'s attack clang off of your shield.\")\n shieldBash = random.randint(0,2)\n if shieldBash == 2:\n print(\"Your block stunned the\",ename,\"and you manage to get an attack in before the\",ename,\"recovers.\")\n print(\"The\",ename,\"takes\",ad,\"damage.\")\n ehp = ehp - ad\n \n\n\nsetup()\nwhile hp >> 0:\n encounter = random.randint(0,3)\n if encounter == 3:\n nonEncounter()\n else:\n print(\"As you are walking through the forest...\")\n enemy()\n while ehp >> 0:\n print(\"What would you like to do?\")\n var = input(\"> \")\n if var in [\"attack\", \"strike\", \"hit\", \"swing\", \"cut\", \"punch\", \"kick\", \"slash\"]:\n attack()\n elif var in [\"block\", \"defend\", \"guard\", \"protect\", \"shield\"]:\n defend()\n \n","sub_path":"newGame1.py","file_name":"newGame1.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"436728282","text":"from scipy.io import wavfile as wave\nimport numpy as np\nfrom termcolor import cprint\nimport utility\n\nclass AudioSteganography:\n ASCII_SIZE = 8 #size of an ASCII char in bits\n\n def __init__(self, path):\n self.rate, self.audio = wave.read(path)\n\n def encode(self, msg, output_path):\n msg = utility.msg_to_byte(msg)\n #print(msg)\n\n new_audio = np.copy(self.audio)\n \n if new_audio.shape[1] == 2:\n new_audio = self.encode_stereo(new_audio, msg)\n else:\n new_audio = self.encode_mono(new_audio, msg)\n\n wave.write(output_path, self.rate, new_audio)\n\n def encode_mono(self, audio, msg):\n if (len(msg)+len(msg)//self.ASCII_SIZE) > len(audio):\n print('Audio too small')\n\n i=0\n j=0\n while i < len(msg):\n if msg[i]=='0' and audio[j] % 2 != 0:\n audio[j] -= 1\n elif msg[i]=='1' and audio[j] % 2 == 0:\n audio[j] += 1\n\n i += 1\n j += 1\n \n if i (2*len(audio)): \n print('Audio too small')\n\n i=0\n j=0\n channel=0\n\n while i < len(msg):\n for x in msg[i]:\n if x=='0' and audio[j][channel] % 2 != 0:\n audio[j][channel] -= 1 \n elif x=='1' and audio[j][channel] % 2 == 0:\n audio[j][channel] += 1\n \n channel = (channel + 1) % 2\n \n if channel==0:\n j += 1\n\n i += 1\n\n if i\r\n 14x14size/32channel(image 1) - 5x5/32channel/64amount/1stride/same padding(convolution filter) - 2x2size/2stride(max_pool) ->\r\n 7x7size/64channel(image 2) - fully connected(layer1:7x7x64,layer2:1024) - drop_out - soft_max - arg_max\r\n\r\ntips:\r\n batch_size prefer 8X,benefit to GPU calculation\r\n std_dev will lead to nan weight(>0.1),will reduce proportion of bad weight initial(can't fit)\r\n batch size will strongly affect accuracy(need more try to find this para)[now = 50]\r\n some time got run bug,try to restart it\r\n unknown bug solved: prefer using CPU only when predict\r\n\r\nupdate record:\r\n with GPU(GTX1060),test data accuracy:0.991,time used:58s\r\n add show model for visualization of every layer output. 2018/12/10\r\n'''\r\n\r\nimport time\r\nimport os\r\nimport cv2\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\n\r\n# hyper paras and config\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0' # '-1':only CPU, '0':only GPU\r\nsave_path = './save_data/CNN_handwriting_num/' + 'train_paras.ckpt' # save train paras data\r\nis_train = False # True:train ,False:predict\r\necho = 10\r\nlearn_rate = 0.001\r\nbatch_size = 48\r\nstd_dev = 0.01 # standard deviation of weight initial\r\nrestart_threshold = 0.5\r\ntime_start = time.time()\r\nmnist = input_data.read_data_sets('./MNIST_data_set', one_hot=True)\r\n\r\n\r\ndef weight_init(shape):\r\n #initial = tf.truncated_normal(shape, stddev=std_dev) # truncated random\r\n initial = tf.random_normal(shape, mean=0.0, stddev=std_dev)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef bias_init(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n\r\n\r\ndef conv2d(x, W):\r\n # convolution function\r\n 'The stride of the sliding window for each dimension of `input`'\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\r\n\r\n\r\ndef max_pool_2x2(x):\r\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')\r\n\r\n\r\ndef show_layer_image(input_image):\r\n # for show convolution layer\r\n # need input_image.shape = (size,size,num)\r\n num = input_image.shape[2]\r\n resize_size = 100 # size of every small image\r\n b = []\r\n for vertical in range(int(np.ceil(num/9.))):\r\n a = []\r\n if np.floor(num/9.) <= vertical:\r\n iter_n = num % 9\r\n for i in range(iter_n):\r\n # use Interpolation method to resize image\r\n image_new = cv2.resize(input_image[:, :, i + vertical * 9], (resize_size, resize_size), interpolation=cv2.INTER_NEAREST)\r\n a.append(image_new)\r\n for i in range(9 - iter_n):\r\n a.append(np.zeros([resize_size,resize_size]))\r\n b.append(np.hstack(a))\r\n else:\r\n iter_n = 9\r\n for i in range(iter_n):\r\n image_new = cv2.resize(input_image[:, :, i + vertical * 9], (resize_size, resize_size), interpolation=cv2.INTER_NEAREST)\r\n a.append(image_new)\r\n b.append(np.hstack(a))\r\n\r\n return np.vstack(b)\r\n\r\n\r\n\r\n# cnn model\r\n# placeholder\r\nx = tf.placeholder(\"float\", [None, 784])\r\ny_ = tf.placeholder(\"float\", [None, 10])\r\n\r\n\r\n# first layer\r\nx_image = tf.reshape(x, [-1, 28, 28, 1]) # [batch, in_height, in_width, in_channels]\r\nW_conv1 = weight_init([5, 5, 1, 32]) # filter:[size=5x5,channel=1,filter_amount=32]\r\nb_conv1 = bias_init([32])\r\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\r\nh_pool1 = max_pool_2x2(h_conv1)\r\n\r\n\r\n# second layer\r\nW_conv2 = weight_init([5, 5, 32, 64]) # weight_init => Variables, can SGD\r\nb_conv2 = bias_init([64])\r\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\r\nh_pool2 = max_pool_2x2(h_conv2)\r\n\r\n# neural net layer\r\n'y = x * w + b = [-1,7x7x64] * [7x7x64,1024] + [1024]'\r\nW_fc1 = weight_init([7 * 7 * 64, 1024]) # after x2 pool,image size decrease to 7x7,\r\nb_fc1 = bias_init([1024])\r\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\r\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\r\n\r\n# dropout\r\nkeep_proportion = tf.placeholder(\"float\")\r\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_proportion)\r\n\r\n# output layer and soft_max\r\nW_fc2 = weight_init([1024, 10])\r\nb_fc2 = bias_init([10])\r\ny_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\r\n\r\n# loss and optimizer model\r\ncross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))\r\ntrain_model = tf.train.GradientDescentOptimizer(learn_rate).minimize(cross_entropy)\r\n\r\ncorrect_prediction = tf.equal(tf.argmax(y_conv, axis=1), tf.argmax(y_, axis=1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\nsess = tf.Session()\r\n\r\nsess.run(tf.global_variables_initializer()) # init variables\r\nsaver = tf.train.Saver()\r\n\r\n# predict\r\npredict = tf.argmax(y_conv, axis=1)\r\n\r\n# calc iter\r\ntrain_images_num = mnist.train.images.shape[0]\r\niter_num = np.int32(train_images_num / batch_size * echo)\r\n\r\n# fit\r\nif is_train == True:\r\n for i in range(iter_num):\r\n\r\n batch = mnist.train.next_batch(batch_size) # batch = 8 X ,can improve GPU calculation\r\n\r\n if i % 100 == 0:\r\n train_accuracy = sess.run(accuracy,feed_dict={x: batch[0], y_: batch[1], keep_proportion: 1.0})\r\n print(\"iter: %d, training data accuracy %f\" % (i, train_accuracy))\r\n\r\n sess.run(train_model,feed_dict={x: batch[0], y_: batch[1], keep_proportion: 0.5})\r\n\r\n saver.save(sess,save_path)\r\n print(\"train time used:\", time.time() - time_start)\r\n print(\"test accuracy:\", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_proportion: 1.0}))\r\nelse:\r\n saver.restore(sess,save_path)\r\n print(\"predict time used:\",time.time() - time_start)\r\n\r\n# funny input\r\n#funny_input = plt.imread('./test_data_set/5.png')[:,:,1]\r\n#funny_input_ = funny_input.reshape([1,784])\r\n\r\nprint(\"x\",mnist.test.images.shape)\r\nfunny_input = mnist.test.images[9].reshape([28,28])\r\nfunny_input_ = funny_input.reshape([1,784])\r\n# # predict\r\n# print(\"test accuracy %f\" % sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels,keep_proportion:1.0})) # predict test,not dropout\r\n# predict_list = sess.run(predict,feed_dict={x:funny_input_,keep_proportion:1.0})\r\n# print(\"predict:\",predict_list)\r\n# plt.matshow(funny_input.reshape(28,28))\r\n# plt.title(\"predict:\"+str(predict_list))\r\n# plt.show()\r\n\r\n# show model\r\nprint(\"predict:\",sess.run(predict,feed_dict={x:funny_input_,keep_proportion:1.0}))\r\n'show origin image'\r\ncv2.imshow(\"origin image\",cv2.resize(funny_input,(200,200)))\r\n\r\n'show layer of convolution 1'\r\nconv_layer_1 = h_conv1[0] # h_conv1.shape=[-1,x,x,1]\r\n# conv_layer_1_output = sess.run(conv_layer_1,feed_dict={x:mnist.test.images}) # show test image\r\nconv_layer_1_output = sess.run(conv_layer_1,feed_dict={x:funny_input_}) # show funny_input_\r\ncv2.imshow(\"layer of convolution 1\",show_layer_image(conv_layer_1_output))\r\n\r\n'show layer of convolution 2'\r\nconv_layer_1 = h_conv2[0]\r\nconv_layer_1_output = sess.run(conv_layer_1,feed_dict={x:funny_input_})\r\ncv2.imshow(\"layer of convolution 2\",show_layer_image(conv_layer_1_output))\r\n\r\ncv2.waitKey(0)\r\n","sub_path":"CNN_handwriting_num.py","file_name":"CNN_handwriting_num.py","file_ext":"py","file_size_in_byte":7390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341657372","text":"import cv2\nimport sys\n\ncascade_dir = \"/usr/local/Cellar/opencv/2.4.9/share/OpenCV/haarcascades/\"\nface_cascade = cv2.CascadeClassifier(cascade_dir + \"haarcascade_frontalface_default.xml\")\nportrait_cascade = cv2.CascadeClassifier(cascade_dir + \"haarcascade_profileface.xml\")\n\nfilename = '/Users/ashton/Desktop/training-originals/0008_005.jpg'\n\n# read image and resize it\nimage = cv2.imread(filename)\nreduce_by = 4\nwidth,height = image.shape[1]/reduce_by,image.shape[0]/reduce_by\nimage = cv2.resize(image, (width, height))\n\n# detect face(s)\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nfaces = face_cascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.cv.CV_HAAR_SCALE_IMAGE\n)\nportraits = portrait_cascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.cv.CV_HAAR_SCALE_IMAGE\n)\n# Draw a rectangle around the faces\nfor (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\nfor (x, y, w, h) in portraits:\n cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2)\n\n# show image until pressing Esc\ncv2.imshow('Face detection using Haar', image)\nwhile True:\n if cv2.waitKey(10) == 27:\n break\n\ncv2.destroyAllWindows()","sub_path":"face_detection/file_extra.py","file_name":"file_extra.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"520449748","text":"# Copyright 2017 Yupeng Wang.\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# This application program depends on Tensorflow v1.2 and Python3.\n# Part of its code is derived from the tutoring programs provided\n# by the TensorFlow Authors.\n\n\"\"\"Title: DNN model to process new datasets containing categorical columns\"\"\"\n\n# The input files should be comma delimited (csv) and contain a header line\n# of sample names and 'label'. At least one categorical columns should be\n# provded as a command argument. The last column of the data is 'label', \n# coded by 0,1,...,#classes. All other columns should be feature data.\n# Sample command:\n# Author: Yupeng Wang. ywangbusiness@gmail.com.\n# Sample command: python3 dnn_model_pandas_cat.py train.csv test.csv s7,s8,s9 3 10,20,10\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\n\nif len(sys.argv)<7:\n print(\"Usage:python3 dnn_model_pandas_cat.py training_file testing_file categorical_columns(comma delimited) #classes layer_units(comma delimited) #steps\")\n quit()\n\n#process header\nwith open(sys.argv[1],'r') as fl:\n line=fl.readline().strip('\\n')\nheader=line.split(',')\nn_col=len(header)\nfeatures=[]\nfor i in range(n_col-1):\n features.append(header[i])\nLABEL_COLUMN=header[n_col-1]\n#process arguments\nnsteps=int(sys.argv[6])\nn_cls=int(sys.argv[4])\nh_units=[]\nlt=sys.argv[5].split(',')\nfor w in lt:\n h_units.append(int(w))\nprint(\"DNN units:\")\nprint(h_units)\n#read in training and testing data\ndf_train = pd.read_csv(sys.argv[1], names=header, skiprows=1, skipinitialspace=True)\ndf_test = pd.read_csv(sys.argv[2], names=header, skiprows=1, skipinitialspace=True)\n#assign feature types for the DNN model\nCATEGORICAL_COLUMNS=[]\ncategorical_ind=[]\nCONTINUOUS_COLUMNS=[]\ncontinuous_ind=[]\ntt=sys.argv[3].split(',')\nfor w in tt:\n CATEGORICAL_COLUMNS.append(w)\n categorical_ind.append(tf.contrib.layers.embedding_column(tf.contrib.layers.sparse_column_with_hash_bucket(\n w, hash_bucket_size=1000),dimension=8))\nfor i in range(n_col-1):\n if header[i] not in CATEGORICAL_COLUMNS:\n CONTINUOUS_COLUMNS.append(header[i])\n continuous_ind.append(tf.contrib.layers.real_valued_column(header[i]))\ndeep_columns=[]\nfor s in categorical_ind:\n deep_columns.append(s)\nfor s in continuous_ind:\n deep_columns.append(s)\n#convert input data into tensors\ndef input_fn(df):\n continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS}\n categorical_cols = {\n k: tf.SparseTensor(\n indices=[[i, 0] for i in range(df[k].size)],\n values=df[k].values,\n dense_shape=[df[k].size, 1])\n for k in CATEGORICAL_COLUMNS}\n feature_cols = dict(continuous_cols)\n feature_cols.update(categorical_cols)\n label = tf.constant(df[LABEL_COLUMN].values)\n return feature_cols, label\n#train the DNN model and evaluate its performance\ndef main(unused_argv):\n m = tf.contrib.learn.DNNClassifier(\n feature_columns=deep_columns,\n hidden_units=h_units,\n n_classes=n_cls)\n m.fit(input_fn=lambda: input_fn(df_train), steps=nsteps)\n results = m.evaluate(input_fn=lambda: input_fn(df_test), steps=1)\n print(results)\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"dnn_model_pandas_cat.py","file_name":"dnn_model_pandas_cat.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"110595606","text":"import numpy as np\nimport pandas as pd\nfrom collections import defaultdict\nimport re\n\nimport sys\nimport os\n\n\nfrom keras.layers import Dense, Input\nfrom keras.layers import GRU, Bidirectional, TimeDistributed, Dropout, BatchNormalization\nfrom keras.models import Model\nfrom keras.preprocessing.sequence import TimeseriesGenerator\n\nfrom keras import backend as K\nfrom keras.engine.topology import Layer, InputSpec\nfrom Attention import AttLayer\n# 加载数据\nfrom data_processing import load_data\ntrain, train_label, test, test_label, name = load_data()\n\nMAX_SENTS = 8 # 句子数量,即多少个时间步的\nWORD_LENTTH = 1\nMAX_SENT_LENGTH = 196 # 即多少个特征值\n\n# 利用TimesereisGenerator生成序列数据\ntime_steps = MAX_SENTS\nbatch_size = 1024\n# 先把训练集划分出一部分作为验证集\ntrain = train[:(172032+time_steps), :] # 4096 * 42 = 172032\ntrain = train.reshape(-1, WORD_LENTTH, MAX_SENT_LENGTH)\ntrain_label = train_label[:(172032+time_steps), ]\ntest = test[:(81920+time_steps), :] # 4096 * 20 = 81920\ntest = test.reshape(-1, WORD_LENTTH, MAX_SENT_LENGTH)\ntest_label = test_label[:(81920+time_steps), ]\n# 数据集生成器 需要检查一下是否正确,主要是TimeseriesGenerator的使用情况\ntrain_label_ = np.insert(train_label, 0, 0, axis=0)\ntest_label_ = np.insert(test_label, 0, 0, axis=0)\ntrain_generator = TimeseriesGenerator(train, train_label_[:-1], length=time_steps, sampling_rate=1, batch_size=batch_size)\ntest_generator = TimeseriesGenerator(test, test_label_[:-1], length=time_steps, sampling_rate=1, batch_size=batch_size)\n\n\nsentence_input = Input(shape=(1, MAX_SENT_LENGTH))\nl_lstm_0 = Bidirectional(GRU(128, return_sequences=True))(sentence_input)\nl_lstm_0_drop = Dropout(0.5)(l_lstm_0)\n\nl_lstm = Bidirectional(GRU(32, return_sequences=True))(l_lstm_0_drop)\n\nl_att = AttLayer(32)(l_lstm) # 100是attention_dim\nsentEncoder = Model(sentence_input, l_att)\nprint('Encoder句子summary: ')\nsentEncoder.summary()\n\nreview_input = Input(shape=(MAX_SENTS, 1, MAX_SENT_LENGTH))\nreview_encoder = TimeDistributed(sentEncoder)(review_input)\nl_lstm_sent = Bidirectional(GRU(32, return_sequences=True))(review_encoder)\nl_lstm_sent_drop = Dropout(0.5)(l_lstm_sent)\n\nl_lstm_sent_2 = Bidirectional(GRU(16, return_sequences=True))(l_lstm_sent_drop)\nl_att_sent = AttLayer(16)(l_lstm_sent)\n\ndense_0_batch = BatchNormalization()(l_att_sent)\ndense_0 = Dense(16, activation='relu')(l_att_sent)\n\npreds_batch = BatchNormalization()(dense_0)\npreds = Dense(1, activation='sigmoid')(dense_0)\nmodel = Model(review_input, preds)\nprint('Encoder文档summary: ')\nmodel.summary()\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['acc'])\n\n# 进行训练\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\nprint(\"model fitting - Hierachical attention network\")\nsave_dir = os.path.join(os.getcwd(), 'hierarchical attention')\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nfilepath=\"best_model_1.hdf5\"\ncheckpoint = ModelCheckpoint(os.path.join(save_dir, filepath), monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ntbCallBack = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_grads=True,\n write_images=True, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)\nreduc_lr = ReduceLROnPlateau(monitor='val_acc', patience=20, mode='max', factor=0.2, min_delta=0.0001)\nmodel.fit_generator(train_generator, epochs=200, verbose=2, steps_per_epoch=168,\n callbacks=[checkpoint, tbCallBack, reduc_lr],\n validation_data=test_generator, shuffle=0, validation_steps=80)\nmodel.load_weights('./models/best_model.hdf5')\ntrain_probabilities = model.predict_generator(train_generator, verbose=1)\n\ntrain_pred = train_probabilities > 0.5\ntrain_label_original = train_label_[(time_steps-1):-2, ]\n\ntest_probabilities = model.predict_generator(test_generator, verbose=1)\ntest_pred = test_probabilities > 0.5\ntest_label_original = test_label_[(time_steps-1):-2, ]\n\nfrom sklearn.metrics import confusion_matrix, classification_report\n\nprint('Train_set Confusion Matrix')\nprint(confusion_matrix(train_label_original, train_pred))\n\nprint('Test_set Confusion Matrix')\nprint(confusion_matrix(test_label_original, test_pred))\n\nprint('classification report')\nprint(classification_report(test_label_original, test_pred))","sub_path":"main_double.py","file_name":"main_double.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"82356517","text":"import sys\r\nimport time\r\nimport datetime\r\nimport calendar\r\nfrom myCalendar import MyCalendar\r\n\r\nfrom Item import Item\r\nfrom ProfileManager import ProfileManager\r\nfrom SavingPlan import SavingPlan\r\nfrom MoneyManagement import *\r\n\r\nfrom PySide.QtCore import *\r\nfrom PySide.QtGui import *\r\nfrom PySide.QtUiTools import *\r\n\r\nclass MainPageUI(QMainWindow):\r\n\r\n def __init__(self, parent = None):\r\n QMainWindow.__init__(self, None)\r\n self.setMinimumSize(1280, 900)\r\n self.parent = parent\r\n self.initUI()\r\n\r\n def initUI(self):\r\n loader = QUiLoader()\r\n form = loader.load(\"./UIDesigner/MainWindowUI.ui\", None)\r\n self.setCentralWidget(form)\r\n\r\n ## init all page changing button ##\r\n self.mainMenu_page_button = form.findChild(QPushButton, \"mainMenuBtn\")\r\n self.account_page_button = form.findChild(QPushButton, \"accountBtn\")\r\n self.savingPlan_page_button = form.findChild(QPushButton, \"savingPlanBtn\")\r\n self.priceCatalog_page_button = form.findChild(QPushButton, \"priceCatalogBtn\")\r\n self.setting_page_button = form.findChild(QPushButton, \"settingBtn\")\r\n\r\n\r\n self.connect(self.mainMenu_page_button, SIGNAL(\"clicked()\"), lambda pageNum = 0: self.changePage(pageNum))\r\n self.connect(self.account_page_button, SIGNAL(\"clicked()\"), lambda pageNum = 1: self.changePage(pageNum))\r\n self.connect(self.savingPlan_page_button, SIGNAL(\"clicked()\"), lambda pageNum = 2: self.changePage(pageNum))\r\n self.connect(self.priceCatalog_page_button, SIGNAL(\"clicked()\"), lambda pageNum = 3: self.changePage(pageNum))\r\n self.connect(self.setting_page_button, SIGNAL(\"clicked()\"), lambda pageNum = 4: self.changePage(pageNum))\r\n\r\n ## init all main page attribute ##\r\n self.month_label = form.findChild(QLabel, \"monthLabel\")\r\n self.statusBar_label = form.findChild(QLabel, \"statusLabel\")\r\n self.max_spending_label = form.findChild(QLabel, \"maxLabel\")\r\n self.min_spending_label = form.findChild(QLabel, \"minLabel\")\r\n self.balance_label = form.findChild(QLabel, \"balanceLabel\")\r\n\r\n self.add_income_button = form.findChild(QPushButton, \"plusBtn\")\r\n self.connect(self.add_income_button, SIGNAL(\"clicked()\"), lambda type = \"Income\": self.addItemDialog(type))\r\n\r\n\r\n self.add_spending_button = form.findChild(QPushButton, \"minusBtn\")\r\n self.connect(self.add_spending_button, SIGNAL(\"clicked()\"), lambda type=\"Spending\": self.addItemDialog(type))\r\n\r\n\r\n self.status_bar = form.findChild(QProgressBar,\"progressBar\")\r\n self.status_bar.setMinimum(0)\r\n self.status_bar.setMaximum(10)\r\n\r\n ## init custom calendar ##\r\n self.month = datetime.datetime.now().month\r\n self.year = datetime.datetime.now().year\r\n\r\n self.next_month_button = form.findChild(QPushButton, \"nextMonthBtn\")\r\n self.connect(self.next_month_button, SIGNAL(\"clicked()\"), lambda change_month=\"next\": self.changeMonth(change_month))\r\n self.next_month_button.setStyleSheet(\"background-color: #46a7ae; color: white\")\r\n\r\n self.last_month_button = form.findChild(QPushButton, \"lastMonthBtn\")\r\n self.connect(self.last_month_button, SIGNAL(\"clicked()\"), lambda change_month=\"last\": self.changeMonth(change_month))\r\n self.last_month_button.setStyleSheet(\"background-color: #46a7ae; color: white\")\r\n\r\n self.date_button_list = []\r\n for i in range(40):\r\n self.date_button_list.append(form.findChild(QPushButton, \"d\" + str(i)))\r\n self.date_button_list[i].setStyleSheet(\"background-color: #8cb3d9; color: white\")\r\n self.connect(self.date_button_list[i], SIGNAL(\"clicked()\"), self.getDate)\r\n\r\n self.reset_calendar_button = form.findChild(QPushButton, \"d40\")\r\n self.reset_calendar_button.clicked.connect(self.resetCalendar)\r\n\r\n ## add basic need ##\r\n self.add_daily_basicNeed_button = form.findChild(QPushButton, \"d41\")\r\n self.add_daily_basicNeed_button.clicked.connect(self.addDailyBasicNeed)\r\n\r\n\r\n def getDate(self):\r\n dateValue = self.sender().text()\r\n if(self.month >= 10):\r\n month = \"/\"+str(self.month)+\"/\"\r\n else:\r\n month = \"/0\" + str(self.month) + \"/\"\r\n\r\n if(int(dateValue) < 10):\r\n dateValue = \"0\" + str(dateValue)\r\n dateValue = str(dateValue) + month + str(self.year)\r\n\r\n userAccount = self.parent.currentUser.getUserAccount()\r\n daily_item_list = userAccount.getDailyItemList(dateValue)\r\n\r\n ## daily popup ##\r\n self.dialogBox = QDialog(self)\r\n\r\n mainLayout = QVBoxLayout()\r\n\r\n for i in range(len(daily_item_list)-1):\r\n layout = QHBoxLayout()\r\n layout.addWidget(QLabel(daily_item_list[i].getItemName()))\r\n layout.addWidget(QLabel(\"x \" + str(daily_item_list[i].getItemQuantity())))\r\n layout.addWidget(QLabel(\" = \" + str(daily_item_list[i].getTotalPrice())))\r\n mainLayout.addLayout(layout)\r\n\r\n mainLayout.addWidget(QLabel(\"\\tBalance = \" + str(daily_item_list[len(daily_item_list)-1])))\r\n ok_button = QPushButton(\"OK\")\r\n ok_button.clicked.connect(self.dialogBox.close)\r\n\r\n mainLayout.addWidget(ok_button)\r\n\r\n self.dialogBox.setLayout(mainLayout)\r\n self.dialogBox.show()\r\n\r\n\r\n def addDailyBasicNeed(self):\r\n userAccount = self.parent.currentUser.getUserAccount()\r\n userBasicNeed = self.parent.currentUser.getBasicNeedBox()\r\n basic_need_list = userBasicNeed.getBasicNeedList()\r\n\r\n item_list = []\r\n for i in range(len(basic_need_list)):\r\n category = self.parent.convertingCategoryObj(basic_need_list[i].getItemCategory())\r\n qty = self.parent.convertingQtyObj(basic_need_list[i].getItemQuantity())\r\n\r\n item_list.append(Item(basic_need_list[i].getItemName(), str(basic_need_list[i].getItemPrice()), category,\r\n qty, time.strftime(\"%d/%m/%Y\"), \"Spending\"))\r\n\r\n\r\n #print(item_list.getItemCategory())\r\n userAccount.addManyItem(item_list)\r\n self.updateGUI()\r\n self.parent.showDialog(\"Today's basic need has been added\")\r\n\r\n def addItemDialog(self, type):\r\n # Dialog box\r\n self.addDialog = QDialog(self)\r\n layout = QVBoxLayout()\r\n\r\n loader = QUiLoader()\r\n dialogForm = loader.load(\"./UIDesigner/addItemUI.ui\", None)\r\n\r\n layout.addWidget(dialogForm)\r\n\r\n # init all attribute\r\n self.typeLabel = dialogForm.findChild(QLabel, \"typeLabel\")\r\n self.nameEntry = dialogForm.findChild(QLineEdit, \"itemEntry\")\r\n self.priceEntry = dialogForm.findChild(QLineEdit, \"priceEntry\")\r\n\r\n self.categoryComboBox = dialogForm.findChild(QComboBox, \"categoryComboBox\")\r\n self.income_category_list = ['- None -', 'Salary', 'Interest Money', 'Selling', 'Award', 'Gifts', 'etc.']\r\n if(type == \"Income\"):\r\n self.categoryComboBox.clear()\r\n for i in range(len(self.income_category_list)):\r\n self.categoryComboBox.addItem(self.income_category_list[i])\r\n\r\n\r\n self.quantityEntry = dialogForm.findChild(QSpinBox, \"qtySpinBox\")\r\n\r\n self.dateEntry = dialogForm.findChild(QLineEdit, \"dateEntry\")\r\n self.dateEntry.setText(time.strftime(\"%d/%m/%Y\"))\r\n self.dateEntry.setEnabled(False)\r\n\r\n self.date = time.strftime(\"%d/%m/%Y\")\r\n\r\n self.calendarButton = dialogForm.findChild(QPushButton, \"calendarBtn\")\r\n self.calendarButton.clicked.connect(self.calendarDialog)\r\n\r\n # tell if it's income/spending\r\n self.typeLabel.setText(type)\r\n\r\n # init + connect button\r\n self.save_button = dialogForm.findChild(QPushButton, \"okBtn\")\r\n self.connect(self.save_button, SIGNAL(\"clicked()\"), lambda text=\"ok\": self.close(text))\r\n\r\n self.cancel_button = dialogForm.findChild(QPushButton, \"cancelBtn\")\r\n self.connect(self.cancel_button, SIGNAL(\"clicked()\"), lambda text=\"cancel\": self.close(text))\r\n\r\n # show dialog box\r\n self.addDialog.setLayout(layout)\r\n self.addDialog.show()\r\n\r\n def calendarDialog(self):\r\n self.calendar_dialog_box = QDialog(self)\r\n self.calendar_dialog_box.setMinimumSize(500, 400)\r\n layout = QVBoxLayout()\r\n\r\n loader = QUiLoader()\r\n dialogForm = loader.load(\"./UIDesigner/calendarWidget.ui\", None)\r\n\r\n layout.addWidget(dialogForm)\r\n self.calendar_widget = dialogForm.findChild(QCalendarWidget, \"calendarWidget\")\r\n\r\n\r\n submit_button = dialogForm.findChild(QPushButton, \"submitBtn\")\r\n self.connect(submit_button, SIGNAL(\"clicked()\"), lambda text=\"saveDate\": self.close(text))\r\n\r\n self.calendar_dialog_box.setLayout(layout)\r\n self.calendar_dialog_box.show()\r\n\r\n def close(self, text):\r\n if(text == \"ok\"):\r\n # create object Item\r\n try:\r\n float(self.priceEntry.text())\r\n except:\r\n self.parent.showError(\"Price must be number :(\")\r\n return\r\n\r\n item = Item(self.nameEntry.text(), self.priceEntry.text(), self.categoryComboBox.currentText(), self.quantityEntry.value(), self.date, self.typeLabel.text())\r\n\r\n #add Item into user's account\r\n self.parent.currentUser.userAccount.addItem(item)\r\n\r\n budget_category_list = self.parent.currentUser.getUserBudgeting().getMaximumList()\r\n savings_category_list = self.parent.currentUser.getUserSavings().getMaximumList()\r\n\r\n pm = ProfileManager()\r\n\r\n for n in budget_category_list:\r\n if(n == item.getItemCategory()):\r\n self.parent.currentUser.getUserBudgeting().addValue(n, item.getTotalPrice(), item.getItemDate())\r\n pm.updateUserBudgeting(self.parent.currentUser.getUsername(),self.parent.currentUser.getUserBudgeting())\r\n\r\n for n in savings_category_list:\r\n if(n == item.getItemCategory()):\r\n self.parent.currentUser.getUserSavings().addValue(n, item.getTotalPrice(), item.getItemDate())\r\n pm.updateUserSavings(self.parent.currentUser.getUsername(), self.parent.currentUser.getUserSavings())\r\n\r\n self.addDialog.close()\r\n\r\n elif(text == \"cancel\"):\r\n self.addDialog.close()\r\n\r\n elif(text == \"saveDate\"):\r\n self.date = self.calendar_widget.selectedDate() # get selected date\r\n self.date = self.date.toString('dd,MM,yyyy').split(\",\")\r\n self.date = self.date[0] + \"/\" + self.date[1] + \"/\" + self.date[2]\r\n\r\n self.calendar_dialog_box.close()\r\n\r\n self.dateEntry.setEnabled(True)\r\n self.dateEntry.setText(self.date)\r\n self.dateEntry.setEnabled(False)\r\n\r\n\r\n self.updateGUI()\r\n\r\n def changeMonth(self, option):\r\n c = MyCalendar()\r\n month_year = c.changeMonth(option, self.month, self.year)\r\n self.month = month_year[0]\r\n self.year = month_year[1]\r\n self.updateGUI()\r\n\r\n\r\n def resetCalendar(self):\r\n self.month = datetime.datetime.now().month\r\n self.year = datetime.datetime.now().year\r\n self.updateGUI()\r\n\r\n def updateGUI(self):\r\n userAccount = self.parent.currentUser.getUserAccount()\r\n userBasicNeed = self.parent.currentUser.getBasicNeedBox()\r\n userSavingPlan = self.parent.currentUser.getUserSavingPlan()\r\n\r\n self.max_spending_label.setText(\"Max: 0\")\r\n self.status_bar.setValue(0)\r\n\r\n if(len(userSavingPlan.getSavingPlanDateList()) != 0):\r\n generatedPlan = userSavingPlan.generateSavingPlan(userAccount.getTotalBalance(), userBasicNeed.getTotalBalance())\r\n if(generatedPlan == \"You have finished the plan, CONGRATZ :)\" or generatedPlan == \"It's impossible with your current balance :(\"):\r\n sp = SavingPlan()\r\n pm = ProfileManager()\r\n pm.updateUserSavingPlan(self.parent.currentUser.getUsername(), sp)\r\n self.parent.showDialog(generatedPlan)\r\n else:\r\n maxSpend = userSavingPlan.getMaximumSpending()\r\n self.max_spending_label.setText(\"Max: \" + str(\"%0.2f\" % maxSpend))\r\n\r\n savingStatus = userSavingPlan.getSavingStatus(userBasicNeed.getTotalBalance())\r\n self.status_bar.setValue(int(savingStatus * 10))\r\n\r\n usp_date_list = userSavingPlan.getSavingPlanDateList()\r\n\r\n\r\n self.month_label.setText(calendar.month_name[self.month][0:3]) # set full month name\r\n\r\n c = MyCalendar()\r\n self.date_list = c.getDateList(self.month, self.year)\r\n\r\n savingPlanButton = []\r\n #print(self.date_list)\r\n for i in range(len(self.date_list)): #set date on calendar\r\n for j in range(len(usp_date_list)):\r\n if(self.date_list[i] == usp_date_list[j]): #change color for saving plan\r\n savingPlanButton.append(i) #collect index with savingPlan\r\n if(self.date_list[i][0] != \"0\"):\r\n day = self.date_list[i][0] + self.date_list[i][1]\r\n self.date_button_list[i].setText(day) # date < 10\r\n else:\r\n day = self.date_list[i][1]\r\n self.date_button_list[i].setText(day) # date > 10\r\n self.date_button_list[i].setStyleSheet(\"color: white; background-color: #46a7ae\") #set all to normal color\r\n\r\n for n in savingPlanButton:\r\n self.date_button_list[n].setStyleSheet(\"color: white; background-color: #20566e\") #set red to saving plan\r\n\r\n day = time.strftime(\"%d\")\r\n if(int(day) < 10):\r\n day = day[1]\r\n\r\n for n in self.date_button_list:\r\n if(n.text() == day and self.month == int(time.strftime(\"%m\"))):\r\n n.setStyleSheet(\"color: white; background-color: #81cfd1\")\r\n\r\n userAccount = self.parent.currentUser.getUserAccount()\r\n balance = userAccount.getTotalBalance()\r\n self.balance_label.setText(\"Balance: \" + str(balance))\r\n\r\n\r\n def changePage(self, pageNum):\r\n # 0 = main menu page, 1 = account page, 2 = saving plan page, 3 = price catalog page, 4 = setting page\r\n for i in range(5):\r\n if(i == pageNum):\r\n tempPage = i\r\n break\r\n self.parent.changePage(tempPage)\r\n\r\n'''\r\ndef main():\r\n app = QApplication(sys.argv)\r\n\r\n a = MainPageUI()\r\n a.show()\r\n\r\n return app.exec_()\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n'''\r\n \r\n","sub_path":"zfront_MainPageUI.py","file_name":"zfront_MainPageUI.py","file_ext":"py","file_size_in_byte":15791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"240832652","text":"#!/usr/bin/python\r\nimport logging, web, json, types, traceback, copy\r\nfrom habase import HomeAutomationQueueThread\r\nfrom webservicecommon import WebServiceDefinition, WebServiceDefinitionList, webservice_hawebservice_init, webservice_state_jsonp\r\n\r\nclass WebService_State_JSONP(object):\r\n @webservice_state_jsonp\r\n def GET(self, **kwargs):\r\n jsonvalues = {}\r\n for key, value in kwargs.iteritems():\r\n # jsonvalues.append(value())\r\n jd = json.loads(value())\r\n # logging.info('jd = ' + `jd`)\r\n jsonvalues[jd.items()[0][0]] = jd.items()[0][1] # TODO: a nicer solution for this\r\n # return '[' + ', '.join(jsonvalues) + ']'\r\n return json.dumps(jsonvalues)\r\n\r\nclass WebService_Definition_JSONP(object):\r\n def GET(self):\r\n callback_name = web.input(callback='jsonCallback').callback\r\n web.header('Content-Type', 'application/javascript')\r\n d = {}\r\n d['Definitions'] = []\r\n for wsdi in WebServiceDefinitions:\r\n d['Definitions'].append({'Name': wsdi.jsname,\r\n 'URL': wsdi.jsurl,\r\n 'Args': wsdi.argnames,\r\n 'Enums': wsdi.jsenums,\r\n # 'Module': wsdi.cl,\r\n })\r\n return '%s(%s)' % (callback_name, json.dumps(d) )\r\n\r\nclass HAWebService(HomeAutomationQueueThread):\r\n webservice_definitions = [\r\n WebServiceDefinition(\r\n '/state/', 'WebService_State_JSONP', '/state/', 'wsState'),\r\n ]\r\n\r\n def __init__(self, name, callback_function, queue, threadlist, modules):\r\n HomeAutomationQueueThread.__init__(self, name = name, callback_function = callback_function,\r\n queue = queue, threadlist = threadlist)\r\n\r\n global WebServiceDefinitions\r\n WebServiceDefinitions = WebServiceDefinitionList()\r\n\r\n for mod in modules:\r\n wsdef = modules[mod].cls.webservice_definitions\r\n\r\n if wsdef is not None:\r\n if type(wsdef) == types.FunctionType:\r\n logging.debug('wsdef is function, trying to execute')\r\n wsdef_addition = wsdef() # extend submodules or other dynamic collection\r\n if type(wsdef_addition) == types.ListType:\r\n wsdef = wsdef_addition\r\n elif type(wsdef) != types.ListType:\r\n wsdef = []\r\n\r\n if hasattr(modules[mod].cls, '_webservice_definitions'):\r\n # automatically created through decorator\r\n wsdef_internal = getattr(modules[mod].cls, '_webservice_definitions')\r\n wsdef.extend(wsdef_internal)\r\n logging.info('added decorator definitions')\r\n\r\n WebServiceDefinitions.extend(wsdef)\r\n logging.debug(str(len(wsdef)) + ' definitions loaded from module ' + mod)\r\n\r\n for wsdi in wsdef:\r\n try:\r\n logging.info('wsdi ' + str(wsdi))\r\n _c = getattr(modules[mod].module, wsdi.cl)\r\n if wsdi.methodname is not None and wsdi.argnames is not None:\r\n c = copy.deepcopy(_c) # make a copy so that the following overwrites aren't inherited on the next iter\r\n wsdi.cl = wsdi.cl + '_' + wsdi.methodname # modify the class instance name reference of our copied class\r\n # logging.info(wsdi.cl + ' - attaching methodname and argnames ' + wsdi.methodname)\r\n # c.methodname = wsdi.methodname\r\n # c.argnames = wsdi.argnames\r\n globals()[wsdi.cl] = c # just a little hacky\r\n # logging.info('resolved to: ' + `c`)\r\n else:\r\n globals()[wsdi.cl] = _c # just a little hacky\r\n # logging.info('resolved to: ' + `_c`)\r\n except AttributeError:\r\n logging.info('Unexpected exception caught while loading WSD ' + wsdi.cl + ' from module ' + mod + ' - ' + traceback.format_exc() )\r\n\r\n logging.info(str(len(WebServiceDefinitions)) + ' definitions loaded.')\r\n\r\n global SharedQueue # deprecated?\r\n SharedQueue = queue\r\n\r\n global ThreadList\r\n ThreadList = threadlist\r\n\r\n webservice_hawebservice_init(SharedQueue=SharedQueue, ThreadList=ThreadList)\r\n\r\n def run(self):\r\n urls = (\r\n '/definitions/', 'WebService_Definition_JSONP',\r\n )\r\n for wsdi in WebServiceDefinitions:\r\n urls = urls + (wsdi.url, wsdi.cl)\r\n logging.info('adding url: ' + wsdi.url)\r\n # urls = urls + ('/(.*)', 'WebService_Index')\r\n # logging.info(str(urls))\r\n app = web.application(urls, globals())\r\n logging.info('Starting up WebService app')\r\n app.run()\r\n","sub_path":"hawebservice.py","file_name":"hawebservice.py","file_ext":"py","file_size_in_byte":5121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"107555361","text":"import asyncio\nimport subprocess\nimport cv2\nimport numpy as np\nimport math\nimport traceback\nimport os\n\nfrom cv2 import VideoWriter, VideoWriter_fourcc\nfrom uuid import uuid4\nfrom datetime import datetime\nfrom subprocess import check_output\n\n\nclass Executor:\n\n command = 'video'\n use_call_name = False\n\n def __init__(self, config, debugger, extractor):\n self.config = config\n self.debug = debugger\n self.extractor = extractor\n\n def help(self):\n return \"Video tools:\\n %svideo help\" % self.config.S\n\n def rotate(self, image, angle, switch_direction):\n (h, w) = image.shape[:2]\n center = (w / 2, h / 2)\n\n if not switch_direction:\n angle = -angle\n M = cv2.getRotationMatrix2D(center, angle, 1.0)\n rotated = cv2.warpAffine(image, M, (w, h))\n return rotated\n\n def animate(self, filepath, switch_direction=False, scale=True):\n source = cv2.imread(filepath)\n height, width, channels = source.shape\n\n if scale:\n source = cv2.resize(source, (height//2, width//2))\n height, width, channels = source.shape\n\n FPS = 60\n degree = 360\n\n out = str(uuid4())+'.mp4'\n fourcc = VideoWriter_fourcc(*'mp4v')\n video = VideoWriter(out, fourcc, float(FPS), (width, height))\n\n for angle in range(degree):\n if angle % 2 == 0:\n continue\n if angle % 5 == 0:\n continue\n\n image_rotated = self.rotate(source, angle, switch_direction)\n if scale:\n resized = cv2.resize(image_rotated, (width*2, height*2))\n cent0 = image_rotated.shape[0]//2\n cent1 = image_rotated.shape[1]//2\n image_rotated = resized[cent0:cent0+height, cent1:cent1+width]\n video.write(image_rotated)\n\n video.release()\n return out\n\n def resize_ffmpeg(self, filepath: str, fx: float, fy: float, d='/') -> str:\n \"\"\"\n Resize video to given aspect ratio using ffmpeg.\n \"\"\"\n out_file = 'resized_'+filepath\n fx, fy = int(fx), int(fy)\n if fx > 4:\n fx = 4\n if fy > 4:\n fy = 4\n\n fix_division = \", crop=trunc(iw/2)*2:trunc(ih/2)*2\"\n if d == '/':\n # downscale\n scale = 'scale=iw/%d:ih/%d' % (fx, fy)\n else:\n # upscale\n scale = 'scale=iw*%d:ih*%d' % (fx, fy)\n scale_filter = scale + fix_division\n\n try:\n check_output(['ffmpeg', '-i', filepath, '-vf', scale_filter, out_file], timeout=240)\n except subprocess.TimeoutExpired:\n out_file = -1\n os.remove(filepath)\n return out_file\n\n def parse_args(self, args: list, fname: str) -> list:\n filepath = None\n\n if args[1] == \"animate\":\n switch_direction = False\n scale = True\n for arg in args[1:]:\n if arg == '+':\n switch_direction = True\n if arg == 'noscale':\n scale = False\n try:\n filepath = self.animate(fname, switch_direction, scale)\n except:\n self.debug(traceback.format_exc())\n return [-1, 'An error has occured', fname]\n\n elif args[1] == \"resize\":\n self.debug('Enter resize')\n errmessg = (\"Please, specify correct multipliers \"\n \"fx and fy.\\n\"\n \"%svideo resize 2 2\") % self.config.S\n\n if (len(args) < 4) or (len(args) > 5):\n return [-1, errmessg, fname]\n\n try:\n fx, fy = (float(args[2]), float(args[3]))\n except:\n return [-1, errmessg, fname]\n\n self.debug('Resizing video/gif')\n if len(args) == 5:\n d = args[4]\n else:\n d = '/'\n filepath = self.resize_ffmpeg(fname, fx, fy, d)\n if filepath == -1:\n return [-1, 'Timeout exceeded', fname]\n\n return [1, filepath]\n\n async def call_executor(self, event, client):\n self.debug('Enter executor of %s' % repr(self))\n args = event.raw_text.split()\n\n if len(args) == 1:\n return\n\n S = self.config.S\n if args[1] == 'help':\n self.debug(\"Return message for