diff --git "a/3800.jsonl" "b/3800.jsonl" new file mode 100644--- /dev/null +++ "b/3800.jsonl" @@ -0,0 +1,590 @@ +{"seq_id":"631771400","text":"from pymongo import MongoClient\n\nfrom flask import Flask, render_template, jsonify, request\n\napp = Flask(__name__)\n\nclient = MongoClient('localhost', 27017)\ndb = client.seoul_matjip\n\n\n# HTML 화면 보여주기\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n# API 역할을 하는 부분\n@app.route('/api/restaurant_list', methods=['GET'])\ndef show_matjips():\n # 1. db에서 mystar 목록 전체를 검색합니다. ID는 제외하고 like 가 많은 순으로 정렬합니다.\n matjips = list(db.restaurants.find({}, {'_id':False}).sort('like',-1))\n print(matjips)\n # 참고) find({},{'_id':False}), sort()를 활용하면 굿!\n\n # 2. 성공하면 success 메시지와 함께 stars_list 목록을 클라이언트에 전달합니다.\n return jsonify({'result': 'success', 'msg': 'list 연결되었습니다!', 'list': matjips})\n\n\n@app.route('/api/restaurant_like', methods=['POST'])\ndef like_matjips():\n # 1. 클라이언트가 전달한 name_give를 name_receive 변수에 넣습니다.\n name = request.form[\"name\"]\n\n # 2. mystar 목록에서 find_one으로 name이 name_receive와 일치하는 star를 찾습니다.\n current_like = db.restaurants.find_one({'name':name})[\"like\"]\n # 3. star의 like 에 1을 더해준 new_like 변수를 만듭니다.\n new_like = current_like + 1\n # 4. mystar 목록에서 name이 name_receive인 문서의 like 를 new_like로 변경합니다.\n # 참고: '$set' 활용하기!\n\n db.restaurants.update_one({'name': name}, {'$set':{'like': new_like}})\n # 5. 성공하면 success 메시지를 반환합니다.\n return jsonify({'result': 'success', 'msg': name+'좋아'})\n\n\n@app.route('/api/delete', methods=['POST'])\ndef delete_star():\n # 1. 클라이언트가 전달한 name_give를 name_receive 변수에 넣습니다.\n name = request.form[\"name\"]\n # 2. mystar 목록에서 delete_one으로 name이 name_receive와 일치하는 star를 제거합니다.\n db.restaurants.delete_one({'name':name})\n # 3. 성공하면 success 메시지를 반환합니다.\n return jsonify({'result': 'success', 'msg': name+'삭제~'})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"537385002","text":"import tensorflow as tf\nimport numpy as np\nimport hyperchamber as hc\nimport inspect\n\nfrom hypergan.trainers.base_trainer import BaseTrainer\n\nTINY = 1e-12\n\nclass DepthTrainer(BaseTrainer):\n \"\"\" Runs an optimizer multiple times and combines the output into a mixture. \"\"\"\n def create(self):\n self.hist = [0 for i in range(2)]\n config = self.config\n self.global_step = tf.train.get_global_step()\n self.mix_threshold_reached = False\n decay_function = config.decay_function\n variables = self.gan.d_vars() + self.gan.g_vars()\n self.ema = [ tf.Variable(_v) for _v in variables ]\n self.store_v = [ _v.assign(_v2) for _v,_v2 in zip(self.ema, variables) ]\n self.combine = [ _v.assign(config.decay *_ema + (1.-config.decay)*_new) for _v, _ema, _new in zip(variables, self.ema, variables)]\n self._delegate = self.gan.create_component(config.trainer, d_vars=self.d_vars, g_vars=self.g_vars, loss=self.loss)\n self._delegate.create()\n self.slot_vars_g = self._delegate.slot_vars_g\n self.slot_vars_d = self._delegate.slot_vars_g\n\n def required(self):\n return \"\".split()\n\n def _step(self, feed_dict):\n gan = self.gan\n sess = gan.session\n config = self.config\n loss = self.loss \n\n gan.session.run(self.store_v)\n for i in range(config.depth or 2):\n self._delegate.step(feed_dict)\n gan.session.run(self.combine)\n\n","sub_path":"hypergan/trainers/depth_trainer.py","file_name":"depth_trainer.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"451221872","text":"#!/usr/bin/env python\nfrom __future__ import division, print_function, absolute_import\n\nimport os\n# import sys\n# import subprocess\nimport glob\n\n\ndef configuration(parent_package='', top_path=None):\n from numpy.distutils.misc_util import Configuration\n\n config = Configuration()\n config.add_data_dir('tests')\n\n # check for a config file in ..\n cfg_headers = []\n try:\n with open('crappy.cfg', 'r') as fcfg:\n newsource = fcfg.readline().strip()\n #newsource = os.path.join('..', newsource)\n if os.path.isfile(newsource):\n cfg_headers += [newsource]\n except IOError as e:\n print(\"I/O error({%d}): %s\" % (e.errno, e.strerror))\n\n base_headers = [h for h in glob.glob('base/*.h')]\n template_headers = [h for h in glob.glob('templates/example.h')]\n template_headers += cfg_headers\n depends = base_headers + template_headers\n\n sources = []\n sources += [s.replace('.h', '.cxx') for s in template_headers]\n sources += [os.path.join('base', 'crappy.cxx')]\n sources += [os.path.join('templates', 'initmodule.cxx')]\n\n import generate_functions\n generate_functions.main(template_headers, '')\n\n config.add_extension('crappy',\n define_macros=[('__STDC_FORMAT_MACROS', 1)],\n depends=depends,\n include_dirs=['base', 'templates'],\n sources=sources)\n return config\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(**configuration(top_path='').todict())\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"230885953","text":"# Plotting and reporting Bayes Factor given idata, var name, prior distribution and reference value\nimport logging\n\nfrom scipy.stats import gaussian_kde\n\nfrom ..data.utils import extract\nfrom .plot_utils import get_plotting_function\n\n_log = logging.getLogger(__name__)\n\n\ndef plot_bf(\n idata,\n var_name,\n prior=None,\n ref_val=0,\n xlim=None,\n colors=(\"C0\", \"C1\"),\n figsize=None,\n textsize=None,\n hist_kwargs=None,\n plot_kwargs=None,\n ax=None,\n backend=None,\n backend_kwargs=None,\n show=None,\n):\n \"\"\"\n Bayes Factor approximated as the Savage-Dickey density ratio.\n\n The Bayes factor is estimated by comparing a model (H1) against a model in which the\n parameter of interest has been restricted to be a point-null (H0). This computation\n assumes the models are nested and thus H0 is a special case of H1.\n\n\n\n Parameters\n -----------\n idata : obj\n a :class:`arviz.InferenceData` object\n var_name : str\n Name of variable we want to test.\n prior : numpy.array, optional\n In case we want to use different prior, for example for sensitivity analysis.\n ref_val : int\n Point-null for Bayes factor estimation. Defaults to 0.\n xlim : tuple, optional\n Set the x limits, which might be used for visualization purposes.\n colors : tuple\n Tuple of valid Matplotlib colors. First element for the prior, second for the posterior.\n Defaults to ('C0', 'C1').\n figsize : tuple\n Figure size. If None it will be defined automatically.\n textsize: float\n Text size scaling factor for labels, titles and lines. If None it will be autoscaled based\n on figsize.\n plot_kwargs : dicts, optional\n Additional keywords passed to :func:`matplotlib.pyplot.plot`\n hist_kwargs : dicts, optional\n Additional keywords passed to :func:`arviz.plot_dist`. Only works for discrete variables\n ax : axes, optional\n :class:`matplotlib.axes.Axes` or :class:`bokeh.plotting.Figure`.\n backend : str, optional\n Select plotting backend {\"matplotlib\",\"bokeh\"}. Default \"matplotlib\".\n backend_kwargs : bool, optional\n These are kwargs specific to the backend being used, passed to\n :func:`matplotlib.pyplot.subplots` or :func:`bokeh.plotting.figure`.\n For additional documentation check the plotting method of the backend.\n show : bool, optional\n Call backend show function.\n\n Returns\n -------\n dict : A dictionary with BF10 (Bayes Factor 10 (H1/H0 ratio), and BF01 (H0/H1 ratio).\n axes : matplotlib axes or bokeh figures\n\n\n Examples\n --------\n Moderate evidence indicating that the parameter \"a\" is different from zero\n\n .. plot::\n :context: close-figs\n\n >>> import numpy as np\n >>> import arviz as az\n >>> idata = az.from_dict(posterior={\"a\":np.random.normal(1, 0.5, 5000)},\n ... prior={\"a\":np.random.normal(0, 1, 5000)})\n >>> az.plot_bf(idata, var_name=\"a\", ref_val=0)\n \"\"\"\n posterior = extract(idata, var_names=var_name)\n\n if ref_val > posterior.max() or ref_val < posterior.min():\n _log.warning(\n \"The reference value is outside of the posterior. \"\n \"This translate into infinite support for H1, which is most likely an overstatement.\"\n )\n\n if posterior.ndim > 1:\n _log.warning(\"Posterior distribution has {posterior.ndim} dimensions\")\n\n if prior is None:\n prior = extract(idata, var_names=var_name, group=\"prior\")\n\n if xlim is None:\n xlim = (prior.min(), prior.max())\n\n if posterior.dtype.kind == \"f\":\n posterior_pdf = gaussian_kde(posterior)\n prior_pdf = gaussian_kde(prior)\n\n posterior_at_ref_val = posterior_pdf(ref_val)\n prior_at_ref_val = prior_pdf(ref_val)\n\n elif posterior.dtype.kind == \"i\":\n prior_pdf = None\n posterior_pdf = None\n posterior_at_ref_val = (posterior == ref_val).mean()\n prior_at_ref_val = (prior == ref_val).mean()\n\n bf_10 = prior_at_ref_val / posterior_at_ref_val\n bf_01 = 1 / bf_10\n\n bfplot_kwargs = dict(\n ax=ax,\n bf_10=bf_10.item(),\n bf_01=bf_01.item(),\n xlim=xlim,\n prior=prior,\n posterior=posterior,\n prior_pdf=prior_pdf,\n posterior_pdf=posterior_pdf,\n ref_val=ref_val,\n prior_at_ref_val=prior_at_ref_val,\n posterior_at_ref_val=posterior_at_ref_val,\n var_name=var_name,\n colors=colors,\n figsize=figsize,\n textsize=textsize,\n hist_kwargs=hist_kwargs,\n plot_kwargs=plot_kwargs,\n backend_kwargs=backend_kwargs,\n show=show,\n )\n\n plot = get_plotting_function(\"plot_bf\", \"bfplot\", backend)\n axes = plot(**bfplot_kwargs)\n return {\"BF10\": bf_10, \"BF01\": bf_01}, axes\n","sub_path":"arviz/plots/bfplot.py","file_name":"bfplot.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"116550240","text":"import climate\nimport sys\n\nimport capmetro\n\n\ndef write(st):\n print(','.join((\n st.retrieved.isoformat(),\n str(st.timestamp),\n str(st.vehicle_id),\n str(st.trip_id),\n str(st.route_id),\n str(st.direction_id),\n str(st.start_date),\n str(st.start_time),\n str(st.latitude),\n str(st.longitude),\n str(st.speed),\n )))\n\n\n@climate.annotate(\n root='load protobuf files from this directory',\n before=('only process files before YYYY-MM-DDTHH:MM:SS', 'option'),\n after=('only process files after YYYY-MM-DDTHH:MM:SS', 'option'),\n)\ndef main(root, before=None, after=None):\n print('retrieved,timestamp,vehicle_id,trip_id,route_id,direction_id,'\n 'start_date,start_time,latitude,longitude,speed')\n capmetro.process(write, root, after, before)\n\n\nif __name__ == '__main__':\n climate.call(main, stream=sys.stderr)\n","sub_path":"pb-to-csv.py","file_name":"pb-to-csv.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"557867085","text":"# -*- coding:utf-8 -*-\n\nfrom PyQt4 import QtCore, QtGui, uic\nfrom PyQt4.Qt import QObject, QFileDialog, QMessageBox, QByteArray, QBuffer,\\\n QFont, QHeaderView, QCheckBox\nimport sys\nfrom PyQt4.QtGui import QStandardItemModel, QStandardItem\n\nif __name__ == '__main__':\n app=QtGui.QApplication(sys.argv)\n window=uic.loadUi(\"/home/arama/Repo/TestTable/form.ui\")\n tm=QStandardItemModel(5,3)\n tm.setHeaderData(1, QtCore.Qt.Horizontal, \"bb\")\n \n si=QStandardItem(\"text\")\n #si.setTextAlignment(QtCore.Qt.AlignCenter)\n \n si2=QStandardItem()\n si2.setCheckable(True)\n si2.setEditable(False)\n si2.setTextAlignment(QtCore.Qt.AlignCenter)\n si3=QCheckBox()\n headList=['a','b','c']\n headers=[]\n f=QFont('Lucida',20, QtGui.QFont.Bold)\n si.setFont(f)\n hw=window.tableView.horizontalHeader()\n #hw.setResizeMode( QHeaderView.Fixed)\n tm.setItem(0,0,si)\n tm.setItem(0,1,si2)\n window.tableView.setModel(tm)\n window.tableView.setColumnWidth(1,40)\n window.tableView.horizontalHeader().setFont(f)\n window.tableView.verticalHeader().hide()\n \n \n\n window.show()\n\n sys.exit(app.exec_())\n \n \n ","sub_path":"t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"309014896","text":"__author__ = 'lionel'\nimport xlrd\n#zhab sb\n\nlocation = '/Users/lionel/Desktop/ExcelTest.xlsx'\ndata = xlrd.open_workbook(location)\ntable = data.sheets()[0]\nnrows = table.nrows\nncols = table.ncols\nprint('line number =', nrows)\n\n\ndef getExcelData(type):\n if (type == 'pie'):\n pieChart()\n if (type == 'barH'):\n None\n if (type == 'bar'):\n None\n\n dataList = [[0 for col in range(2)] for row in range(nrows)]\n for i in range(nrows):\n dataList[i] = table.row_values(i)\n\n return dataList\n\n\ndef pieChart():\n return None\n\n\ndef barChart():\n unmodifiedList = getExcelData('bar')\n labelList = ['I have no idea how to creat an empty list']\n valueList = [0]\n del labelList[0]\n del valueList[0]\n for i in range(len(unmodifiedList)-1):\n labelList.append(unmodifiedList[i][0])\n for i in range(len(unmodifiedList)-1):\n valueList.append(unmodifiedList[i][1])\n print(valueList)\n\nbarChart()","sub_path":"ExcelData.py","file_name":"ExcelData.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"378006136","text":"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ------------------------------------------------------------------------------\nimport atexit\nimport json\nimport os\n\nimport msal\nfrom azdata.cli.commands.arc.azure.models.spn import Spn\nfrom azdata.cli.commands.arc.common_util import get_config_file\nfrom azdata.cli.core.configuration import Configuration\nfrom azdata.cli.core.deploy import display\nfrom azdata.cli.core.prompt import prompt_for_input\nfrom azdata.cli.core.logging import get_logger\n\nfrom . import constants as azure_constants\n\nlog = get_logger(__name__)\n\n# #############################################################################\n# -- AAD related functions --\n# #############################################################################\n\ndef acquire_token(scopes):\n \"\"\"\n Obtains AAD bearer token for given scope\n \"\"\"\n spn = _check_for_spn()\n\n token = None\n while not token:\n try:\n token = _get_token_using_msal(spn, scopes)\n except BaseException:\n display('Service principal \"{}\" failed to authenticate with Azure. Please try again\\n'.format(spn.client_id))\n \n # If we did not get a token, prompt for spn\n if not token:\n spn = _prompt_for_spn()\n\n _store_spn_in_env(spn)\n return token\n\n\ndef _check_for_spn():\n \"\"\"\n Checks if service principal is stored in the environment\n or contained in config_file. Returns spn if found, prompts\n user for spn otherwise\n \"\"\"\n spn = Spn()\n\n # Check if spn in environment\n get_spn_from_env = True\n for spn_env in azure_constants.SPN_ENV_KEYS.values():\n if spn_env not in os.environ or not os.environ[spn_env]:\n get_spn_from_env = False\n break\n if get_spn_from_env:\n spn.authority = os.environ[azure_constants.SPN_ENV_KEYS[\"authority\"]]\n spn.tenant_id = os.environ[azure_constants.SPN_ENV_KEYS[\"tenant_id\"]]\n spn.client_id = os.environ[azure_constants.SPN_ENV_KEYS[\"client_id\"]]\n spn.client_secret = os.environ[azure_constants.SPN_ENV_KEYS[\"client_secret\"]]\n return spn\n else:\n # Prompt the user\n return _prompt_for_spn()\n\n\ndef _store_spn_in_env(spn: Spn):\n \"\"\"\n Stores service principal object in environment\n :param spn: Service Principal object\n \"\"\"\n if spn.authority and spn.client_id and spn.tenant_id and spn.client_secret:\n os.environ[azure_constants.SPN_ENV_KEYS[\"authority\"]] = spn.authority\n os.environ[azure_constants.SPN_ENV_KEYS[\"tenant_id\"]] = spn.tenant_id\n os.environ[azure_constants.SPN_ENV_KEYS[\"client_id\"]] = spn.client_id\n os.environ[azure_constants.SPN_ENV_KEYS[\"client_secret\"]] = spn.client_secret\n else:\n missing_keys = []\n for spn_env in azure_constants.SPN_ENV_KEYS.values():\n if spn_env not in os.environ or not os.environ[spn_env]:\n missing_keys.append(spn_env)\n raise ValueError(\"The following service principal values are missing: {}\".format(\", \".join(missing_keys)))\n\n\ndef _prompt_for_spn():\n \"\"\"\n Prompts the user to enter the service principal info\n \"\"\"\n spn = Spn()\n\n display('Please provide the service principal information for upload:')\n # public cloud we can use the default login url\n spn.authority = azure_constants.PUBLIC_CLOUD_LOGIN_URL\n spn.tenant_id = prompt_for_input('Service principal tenant id: ')\n spn.client_id = prompt_for_input('Service principal client id: ')\n spn.client_secret = prompt_for_input('Service principal secret: ')\n\n return spn\n\n\ndef _get_token_using_msal(spn, scopes):\n \"\"\"\n Uses the MSAL library to obtain AAD auth token for \n the given service principal and scope(s)\n\n :param spn: service principal object\n :param scopes: list containing scopes requested to \n access a protected API\n \n :return: auth token string, None if auth fails\n \"\"\"\n cache = msal.SerializableTokenCache()\n cache_file = _get_cache_file()\n if os.path.exists(cache_file):\n cache.deserialize(open(cache_file, \"r\").read())\n atexit.register(\n lambda: open(cache_file, \"w\").write(cache.serialize())\n if cache.has_state_changed\n else None\n )\n\n app = msal.ConfidentialClientApplication(\n spn.client_id,\n spn.client_secret,\n azure_constants.AAD_LOGIN_URL + spn.tenant_id,\n token_cache=cache,\n )\n\n # First look up a token from cache, since we are looking for token for the current app, NOT for an end user.\n # Notice we give account parameter as None.\n result = app.acquire_token_silent(scopes, account=None)\n if result:\n log.info(\"Get AAD token from cache.\")\n else:\n log.info(\"No suitable token exists in cache. Get a new one from AAD.\")\n result = app.acquire_token_for_client(scopes)\n if \"access_token\" in result:\n return result[\"access_token\"]\n else:\n log.error(\"Failed to get access token from AAD with the following error\")\n log.error('Error: \"{}\"'.format(result.get(\"error\")))\n log.error('Error description: \"{}\"'.format(result.get(\"error_description\")))\n log.error('Correlation Id: \"{}\"'.format(result.get(\"correlation_id\")))\n\n\ndef _get_cache_file():\n \"\"\"\n Get token cache file\n \"\"\"\n cli_name = Configuration().CLI_NAME\n config_dir = os.path.expanduser(Configuration().CLI_CONFIG_DIR)\n cache_file = os.path.join(\n config_dir, \"{}-{}\".format(cli_name, azure_constants.AAD_PROFILE_FILENAME)\n )\n if not os.path.exists(cache_file):\n log.info(\"Create AAD token cache file.\")\n f = open(cache_file, \"w+\")\n f.close()\n return cache_file","sub_path":"azdata_cli_arc-20.3.7-py2.py3-none-any/azdata/cli/commands/arc/azure/ad_auth_util.py","file_name":"ad_auth_util.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"408125700","text":"\n# -*- coding:utf-8 -*-\nfrom Tvplay import MovieInfoModel\nimport re\nimport requests\nclass Tvteleplay:\n def __init__(self,data):\n self.__info = MovielnfoModel()\n self.__data_module(data)\n def __data_module(self,data):\n # 获取名称\n pattern = \"(.*)\"\n ret = re.search(pattern, data, re.S)\n self.__info.set_name(ret.group(1).split(\"<\")[0])\n\n # 导演\n pattern = '导演: (.*)编剧'\n ret = re.search(pattern, data, re.S)\n pattern = \"(.*)\")[1][:-3])\n\n # 主演\n pattern = '主演(.*)类型'\n ret = re.search(pattern, data, re.S)\n # ret=ret.group(1)\n str = \"\"\n for i in ret.group(1).split(\"\")[:-1]:\n i = i.split(\"\\\">\")[1]\n str += i + \"/\"\n self.__info.set_author(str)\n\n # 评分\n pattern = \"(.*)人评价\"\n ret = re.search(pattern, data, re.S)\n pattern = \"property=\\\"v:average\\\">(.*)\"\n ret = re.search(pattern, ret.group(), re.S)\n self.__info.set_actor(ret.group(1))\n\n # 简介\n pattern = \"