code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
from psycopg2 import extras as ex import psycopg2 as pg import json import datetime import os from functools import reduce data_list = [{'projectName': '伊犁哈萨克自治州友谊医院开发区分院保洁服务项目', 'pingmu': '服务', 'purUnit': '新疆伊犁哈萨克自治州友谊医院', 'adminiArea': '新疆维吾尔自治区', 'bulletTime': '2020年09月02日 19:20', 'obtBidTime': '2020年09月02日至2020年...
normal
{ "blob_id": "e9af8f7830be7db3ca57b0a24de48ef7fcb08d6c", "index": 8453, "step-1": "<mask token>\n\n\ndef processJson(dic):\n dicobj = json.loads(dic)\n print(dicobj)\n for k, v in dicobj.items():\n dict_tmp = {}\n dict_tmp['file_name'] = k\n dict_tmp['urls'] = v\n print(k)\n ...
[ 2, 4, 5, 6, 7 ]
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt # Create your views here. from projects.models import Project from django.db import connection from .utils import namedtuplefetchall from django.http import JsonResponse fro...
normal
{ "blob_id": "c2839046592469dfae7526f72be947126960ba19", "index": 621, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@login_required\n@csrf_exempt\ndef social(request):\n if request.method == 'POST':\n data = request.POST\n project_id = int(json.loads(data.get('projid')))\n he...
[ 0, 1, 2, 3 ]
from typing import List, Tuple import pytest def fit_transform(*args: str) -> List[Tuple[str, List[int]]]: if len(args) == 0: raise TypeError('expected at least 1 arguments, got 0') categories = args if isinstance(args[0], str) else list(args[0]) uniq_categories = set(categories) bi...
normal
{ "blob_id": "b236abaa5e206a8244083ee7f9dcdb16741cb99d", "index": 3072, "step-1": "<mask token>\n\n\ndef test_str_fit_transformr():\n assert fit_transform(['Moscow', 'New York', 'Moscow', 'London']) == [(\n 'Moscow', [0, 0, 1]), ('New York', [0, 1, 0]), ('Moscow', [0, 0, 1]\n ), ('London', [1, 0,...
[ 3, 4, 6, 7, 8 ]
# We don't need no stinking models but django likes this file to be there if you are an app
normal
{ "blob_id": "a1304f290e0346e7aa2e22d9c2d3e7f735b1e8e7", "index": 96, "step-1": "\n# We don't need no stinking models but django likes this file to be there if you are an app\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 1 ] }
[ 1 ]
from .mail_utils import send_mail from .request_utils import get_host_url
normal
{ "blob_id": "74b0ccb5193380ce596313d1ac3f898ff1fdd2f3", "index": 930, "step-1": "<mask token>\n", "step-2": "from .mail_utils import send_mail\nfrom .request_utils import get_host_url\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import numpy as np import initialization as init import evaluation as eval import selection as sel import recombination as rec import mutation as mut initialize = init.permutation evaluate = eval.custom select = sel.rank_based mutate = mut.swap reproduce = rec.pairwise crossover = rec.order replace = sel.rank_based par...
normal
{ "blob_id": "5eab41a2ef536365bab6f6b5ad97efb8d26d7687", "index": 4456, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor gen in range(params['gens']):\n parents = select(population, params['n_pars'])\n offspring = reproduce(params, parents, crossover)\n offspring = mutate(params, offspring)\n ...
[ 0, 1, 2, 3 ]
import logging from django.contrib.auth.models import User import json from django.http import HttpResponse from enumfields.fields import EnumFieldMixin from Api.models import Status logger = logging.getLogger() logger.setLevel(logging.INFO) def check_cookie(request): # Post.objects.all().delete() result = ...
normal
{ "blob_id": "2bc3b0df720788e43da3d9c28adb22b3b1be8c58", "index": 5002, "step-1": "<mask token>\n\n\ndef check_cookie(request):\n result = {'status': True}\n try:\n user_id = request.GET.get('user_id')\n user = User.objects.get(pk=user_id)\n cookie_status = user.profile.cookie_status\n ...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python import cgitb import cgi import pymysql form = cgi.FieldStorage() c.execute("SELECT * FROM example") recs = c.fetchall() records1 = """ <body> <table> <tbody> <tr> <th>Full Name</th> <th>Average Score</th> </tr>""" records_dyn = [ f"<tr><td>{name}</td><td>{avg...
normal
{ "blob_id": "b5fee01582a28085983c56b9c266ef7fd5c3c927", "index": 5132, "step-1": "<mask token>\n", "step-2": "<mask token>\nc.execute('SELECT * FROM example')\n<mask token>\nprint('Content-Type:text/html; charset=utf-8')\nprint()\nfor i in records1.split('\\n'):\n print(i)\nfor i in records_dyn:\n print(...
[ 0, 1, 2, 3, 4 ]
'''import pyttsx3 #engine = pyttsx3.init() #Conficuração das vozes #voices = engine.getProperty('voices') #engine.setProperty('voice', voices[2].id) engine=pyttsx3.init() voices=engine.getProperty('voices') engine.setProperty('voice',voices[3].id) #Falar texto engine.say('Olá meu nome é Jarvis. Sou uma inteligênci...
normal
{ "blob_id": "d9bf58dc76d4e8d7146fac3bb2bdfb538ebf78a5", "index": 7102, "step-1": "<mask token>\n", "step-2": "'''import pyttsx3\n\n#engine = pyttsx3.init()\n\n#Conficuração das vozes\n#voices = engine.getProperty('voices')\n#engine.setProperty('voice', voices[2].id)\n\nengine=pyttsx3.init()\n\nvoices=engine.ge...
[ 0, 1 ]
# -*- coding:Utf-8 -*- from .game_action_manager import GameActionManager from .menu_action_manager import OptionsActionManager, CharacterSelectionActionManager, MainMenuActionManager
normal
{ "blob_id": "48294209d51fbe4dfb2a5130311a10c8a1dd027c", "index": 9237, "step-1": "<mask token>\n", "step-2": "from .game_action_manager import GameActionManager\nfrom .menu_action_manager import OptionsActionManager, CharacterSelectionActionManager, MainMenuActionManager\n", "step-3": "# -*- coding:Utf-8 -*-...
[ 0, 1, 2 ]
# C8-06 p.146 Write city_country() function that takes name city and country # Print city name then the country the city is in. call 3 times with differet pairs. def city_country(city, country): """Name a city and the country it resides in seperated by a comma.""" print(f'"{city.title()}, {country.title()}"\n'...
normal
{ "blob_id": "2866ecf69969b445fb15740a507ddecb1dd1762d", "index": 3395, "step-1": "<mask token>\n", "step-2": "def city_country(city, country):\n \"\"\"Name a city and the country it resides in seperated by a comma.\"\"\"\n print(f'\"{city.title()}, {country.title()}\"\\n')\n\n\n<mask token>\n", "step-3...
[ 0, 1, 2, 3 ]
#!/oasis/scratch/csd181/mdburns/python/bin/python import sys import pickle import base64 from process import process import multiprocessing as mp EPOCH_LENGTH=.875 EPOCH_OFFSET=.125 NUM_FOLDS=5 if __name__ == "__main__": mp.freeze_support() p= mp.Pool(2) for instr in sys.stdin: this_key='' sys.stderr.wr...
normal
{ "blob_id": "e477a59e86cfeb3f26db1442a05d0052a45c42ff", "index": 6397, "step-1": "#!/oasis/scratch/csd181/mdburns/python/bin/python\nimport sys\nimport pickle\nimport base64\nfrom process import process\nimport multiprocessing as mp\n\nEPOCH_LENGTH=.875\nEPOCH_OFFSET=.125\nNUM_FOLDS=5\n\nif __name__ == \"__main_...
[ 0 ]
import numpy as np import skimage def preprocess_img(img, size): img = np.rollaxis(img, 0, 3) # It becomes (640, 480, 3) img = skimage.transform.resize(img, size) img = skimage.color.rgb2gray(img) return img # data = minerl.data.make("MineRLNavigateDense-v0", data_dir="../dataset/navigate") # # # I...
normal
{ "blob_id": "9706b9ba81f41b131c364a16bb17a0c1e31e3a04", "index": 6608, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef preprocess_img(img, size):\n img = np.rollaxis(img, 0, 3)\n img = skimage.transform.resize(img, size)\n img = skimage.color.rgb2gray(img)\n return img\n", "step-3": ...
[ 0, 1, 2, 3 ]
# !/usr/bin/env python # -*- coding: utf-8 -*- # tail -2 hightemp.txt import sys with open(sys.argv[1]) as f: lines = f.readlines(); n = sys.argv[2]; print "".join(lines[len(lines)-int(n):])
normal
{ "blob_id": "a1710ee228a432db92c9586ddff0bfcad1f434a8", "index": 2088, "step-1": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# tail -2 hightemp.txt\n\n\nimport sys\n\nwith open(sys.argv[1]) as f:\n lines = f.readlines();\n\nn = sys.argv[2];\n\nprint \"\".join(lines[len(lines)-int(n):])", "step-2": nul...
[ 0 ]
from datetime import datetime import time from os import system import RPi.GPIO as GPIO import firebase_admin from firebase_admin import credentials from firebase_admin import db GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) # este pin es de salida carro GPIO.setup(26, GPIO.OUT) # este pin es...
normal
{ "blob_id": "0972bd1241ad91f54f8dfde6327ee226c27bf2ca", "index": 9747, "step-1": "<mask token>\n", "step-2": "<mask token>\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.OUT)\nGPIO.setup(26, GPIO.OUT)\nGPIO.setup(19, GPIO.OUT)\nGPIO.setup(13, GPIO.OUT)\nGPIO.setup(6, GPIO.OUT)\nGPIO.setu...
[ 0, 1, 2, 3, 4 ]
from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import PowerTransformer from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import Normalizer from sklearn.preprocessing import MinMaxScaler import pandas as pd import numpy as np def preprocess_transformers(y_train, tra...
normal
{ "blob_id": "890d50c741ffd576312c63dc450e274b4517bf12", "index": 9856, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef preprocess_transformers(y_train, transf):\n if transf != 'ln':\n if transf == 'minmax':\n scaler = MinMaxScaler()\n scaler2 = MinMaxScaler()\n ...
[ 0, 2, 3, 4, 5 ]
DATABASE_NAME = "user_db"
normal
{ "blob_id": "8c8bbbc682889c8d79c893f27def76ad70e8bf8d", "index": 233, "step-1": "<mask token>\n", "step-2": "DATABASE_NAME = 'user_db'\n", "step-3": "DATABASE_NAME = \"user_db\"", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!/usr/bin/env python from __future__ import print_function import weechat import sys import pickle import json import math import os.path from datetime import datetime from datetime import date from datetime import timedelta from dateutil.parser import parse as datetime_parse from os.path import expanduser from goog...
normal
{ "blob_id": "0ed0fb6f9bcc768bb005222c9ae9b454f6d962ec", "index": 9148, "step-1": "<mask token>\n\n\ndef _load_credentials(creds_file=None):\n \"\"\"Loads the credentials from a credentials.json file or by prompting for authentication.\n Returns a credentials object to be used by the Google Sheets API.\n ...
[ 7, 10, 11, 12, 13 ]
#!/usr/bin/python -tt # snmp3_test # Claudia # PyCharm __author__ = "Claudia de Luna (claudia@indigowire.net)" __version__ = ": 1.0 $" __date__ = "10/23/16 11:25 AM" __copyright__ = "Copyright (c) 2015 Claudia de Luna" __license__ = "Python" #from __future__ import print_function import sys import snmp_helper # P...
normal
{ "blob_id": "ccdae522983ddc7c02e221ab5c1bc32683358a7b", "index": 2883, "step-1": "#!/usr/bin/python -tt\n# snmp3_test\n# Claudia\n# PyCharm\n__author__ = \"Claudia de Luna (claudia@indigowire.net)\"\n__version__ = \": 1.0 $\"\n__date__ = \"10/23/16 11:25 AM\"\n__copyright__ = \"Copyright (c) 2015 Claudia de Lun...
[ 0 ]
# Any object containing execute(self) method is considered to be IDE App # this is Duck typing concept class PyCharm: def execute(self): print("pycharm ide runnig") class MyIde: def execute(self): print("MyIde running") class Laptop: def code(self,ide): ide.execut...
normal
{ "blob_id": "9ab3dd87f17ac75a3831e9ec1f0746ad81fad70d", "index": 501, "step-1": "<mask token>\n\n\nclass MyIde:\n <mask token>\n\n\nclass Laptop:\n\n def code(self, ide):\n ide.execute()\n\n\n<mask token>\n", "step-2": "class PyCharm:\n <mask token>\n\n\nclass MyIde:\n\n def execute(self):\n...
[ 3, 5, 7, 8, 9 ]
__version__ = '1.1.3rc0'
normal
{ "blob_id": "2e5bbc8c6a5eac2ed71c5d8619bedde2e04ee9a6", "index": 4932, "step-1": "<mask token>\n", "step-2": "__version__ = '1.1.3rc0'\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import numpy #calculate field of simple def dipole(x, y, z, dx, dy, dz, mx, my, mz): R = (x - dx)**2 + (y - dy)**2 + (z - dz)**2 return (3.0*(x - dx) * ((x - dx)*mx + (y - dy)*my + (z - dz)*mz) / R**2.5 - mx/R**1.5, 3.0*(y - dy) * ((x - dx)*mx + (y - dy)*my + (z - dz)*mz) / R**2.5 - my/R**1.5, ...
normal
{ "blob_id": "9d37d1618fb9d00d63b7ed58290c5ba1b8f106cd", "index": 4599, "step-1": "import numpy \n\n#calculate field of simple \ndef dipole(x, y, z, dx, dy, dz, mx, my, mz):\n R = (x - dx)**2 + (y - dy)**2 + (z - dz)**2\n return (3.0*(x - dx) * ((x - dx)*mx + (y - dy)*my + (z - dz)*mz) / R**2.5 - mx/R**1.5...
[ 0 ]
import pymysql db= pymysql.connect(host = 'localhost', port = 3306, user = 'root', password = 'Wubaba950823', database = 'mydb', charset = 'utf8mb4' ) # 使用cursor()方法获取操作游标 curso...
normal
{ "blob_id": "8566e30a6450a72a0e441155321bd03363944b5a", "index": 8236, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(sql)\ntry:\n cursor.execute(sql)\n db.commit()\nexcept:\n db.rollback()\ndb.close()\n", "step-3": "<mask token>\ndb = pymysql.connect(host='localhost', port=3306, user='r...
[ 0, 1, 2, 3, 4 ]
from day19.rules import Rule, CharacterMatch, OrRule, ListRule def parse_rule(rules: dict, rule_str: str=None) ->Rule: if rule_str is None: rule_str: str = rules[0] if '"' in rule_str: return CharacterMatch(rule_str.strip('"')) elif '|' in rule_str: or_rules = [parse_rule(rules, pa...
normal
{ "blob_id": "4d4f7db6d5b4ed7eac3ced73aca76d3c952c84f4", "index": 1456, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef parse_rule(rules: dict, rule_str: str=None) ->Rule:\n if rule_str is None:\n rule_str: str = rules[0]\n if '\"' in rule_str:\n return CharacterMatch(rule_str.s...
[ 0, 1, 2, 3 ]
import matplotlib.pyplot as plt import matplotlib import matplotlib.colors as colors import matplotlib.cm as cm def plot_hist(data_list): plt.hist(data_list, bins=500) plt.show() return def compare_hits_plot(np_array, compare=False): if compare: clist = list(np_array[:,2]) minima, maxima = ...
normal
{ "blob_id": "b6adb956aed934451fc21e51663be36d08c5b645", "index": 2535, "step-1": "import matplotlib.pyplot as plt\nimport matplotlib\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\n\ndef plot_hist(data_list):\n plt.hist(data_list, bins=500)\n plt.show()\n return\n\ndef compare_hits_plot(np...
[ 0 ]
import MySQLdb import MySQLdb.cursors from flask import _app_ctx_stack, current_app class MySQL(object): def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): """Initialize the `app` for use with this :class:`...
normal
{ "blob_id": "db8c2f6f5da0b52c268634043e1132984f610eed", "index": 8405, "step-1": "<mask token>\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n <mask token>\n\n @property\n def connect(self):\n kw...
[ 4, 5, 6, 7, 8 ]
for i in range(-10,0): print(i,end=" ")
normal
{ "blob_id": "8d0fcf0bf5effec9aa04e7cd56b4b7098c6713cb", "index": 70, "step-1": "<mask token>\n", "step-2": "for i in range(-10, 0):\n print(i, end=' ')\n", "step-3": "for i in range(-10,0):\n print(i,end=\" \")", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# Stubs for binascii # Based on http://docs.python.org/3.2/library/binascii.html import sys from typing import Union, Text if sys.version_info < (3,): # Python 2 accepts unicode ascii pretty much everywhere. _Bytes = Text _Ascii = Text else: # But since Python 3.3 ASCII-only unicode strings are accep...
normal
{ "blob_id": "9ba74c7ecbd20c59883aff4efdc7e0369ff65daf", "index": 5267, "step-1": "<mask token>\n\n\ndef a2b_base64(string: _Ascii) ->bytes:\n ...\n\n\n<mask token>\n\n\ndef a2b_qp(string: _Ascii, header: bool=...) ->bytes:\n ...\n\n\ndef b2a_qp(data: _Bytes, quotetabs: bool=..., istext: bool=..., header:\n...
[ 13, 15, 16, 17, 19 ]
a=int(raw_input()) if (a%2)==0: print("Even") else: print("Odd")
normal
{ "blob_id": "00b06b5e6465bae3eab336441b283a9831bb93c0", "index": 4531, "step-1": "<mask token>\n", "step-2": "<mask token>\nif a % 2 == 0:\n print('Even')\nelse:\n print('Odd')\n", "step-3": "a = int(raw_input())\nif a % 2 == 0:\n print('Even')\nelse:\n print('Odd')\n", "step-4": "a=int(raw_inp...
[ 0, 1, 2, 3 ]
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from datetime import datetime import statsmodels.api as sm from quant.stock.stock import Stock from quant.stock.date import Date from quant.utility_fun.factor_preprocess import FactorPreProcess from quant.utility_fun.write_excel import Wri...
normal
{ "blob_id": "1d0730e8fd120e1c4bc5b89cbd766234e1fa3bca", "index": 2197, "step-1": "<mask token>\n\n\ndef cal_factor_alpha_return(factor_name, beg_date, end_date, cal_period):\n group_number = 8\n year_trade_days = 242\n min_stock_number = 100\n out_path = 'E:\\\\3_Data\\\\5_stock_data\\\\3_alpha_model...
[ 1, 2, 3, 4, 5 ]
# Fix a method's vtable calls + reference making #@author simo #@category iOS.kernel #@keybinding R #@toolbar logos/refs.png #@description Resolve references for better CFG # -*- coding: utf-8 -*- """ script which does the following: - adds references to virtual method calls - Identifies methods belong to a specific ...
normal
{ "blob_id": "30a57197e3156023ac9a7c4a5218bfe825e143d9", "index": 5978, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n fix_extra_refs(currentAddress)\n", "step-3": "<mask token>\nfrom utils.references import *\nif __name__ == '__main__':\n fix_extra_refs(currentAddress...
[ 0, 1, 2, 3 ]
import warnings warnings.filterwarnings('ignore', category=FutureWarning) from cv2 import cv2 from tqdm import tqdm import os import pickle import numpy as np import csv import sys from collections import defaultdict from dataset_utils import * sys.path.append("../training") from dataset_tools import enclosing_square...
normal
{ "blob_id": "0b7d1564ecbd78086d59629a2058716f41b4b8c8", "index": 9686, "step-1": "<mask token>\n\n\ndef get_emotion_label(emotion):\n return LABELS['emotion'][emotion]\n\n\ndef _load_meta_from_csv(csv_meta, output_dict):\n data = readcsv(csv_meta)\n for row in data:\n output_dict[row[0]]['gender'...
[ 9, 12, 13, 18, 19 ]
import pymel.core as PM import socket def getShadingGroupMembership(): ''' Get a dictionary of shading group set information {'shadingGroup': [assignmnet1, assignment2...]} ''' result = {} #sgs = PM.ls(sl= 1, et='shadingEngine') sgs = PM.listConnections(s= 1, t='shadingEngine') for sg i...
normal
{ "blob_id": "4e38ad17ad66ac71b0df3cbcaa33cb546e96ce9d", "index": 2257, "step-1": "import pymel.core as PM\nimport socket\n\ndef getShadingGroupMembership():\n '''\n Get a dictionary of shading group set information\n {'shadingGroup': [assignmnet1, assignment2...]}\n '''\n result = {}\n #sgs = P...
[ 0 ]
#!/home/nick/.virtualenvs/twitterbots/bin/python3.5 # -*- coding: utf-8 -*- import tweepy import sqlite3 from configparser import ConfigParser ''' A little OOP would be good later for authenticated user data, c, conn, api ''' def main(): Collector.collect() class Collector: # Main function def coll...
normal
{ "blob_id": "372d8c8cb9ec8f579db8588aff7799c73c5af255", "index": 519, "step-1": "<mask token>\n\n\nclass Collector:\n <mask token>\n\n def get_api():\n parser = ConfigParser()\n parser.read('twitter_auth.ini')\n consumer_key = parser.get('Keys', 'consumer_key').strip(\"'\")\n co...
[ 5, 9, 11, 12, 14 ]
""" """ import os from alert_triage.util import filelock MODIFIED_ALERTS_FILE = "/tmp/alert_triage_modified_alerts" def read_modified_alert_ids(): """ Read modified alert IDs from file, then remove them from the file.""" # Return an empty list if the file doesn't exist. if not os.path.exists(MODIFIED_AL...
normal
{ "blob_id": "90ae14d8af163343520365a5565a7c44de57059d", "index": 5662, "step-1": "<mask token>\n\n\ndef read_modified_alert_ids():\n \"\"\" Read modified alert IDs from file, then remove them from the file.\"\"\"\n if not os.path.exists(MODIFIED_ALERTS_FILE):\n return []\n lock = filelock.FileLoc...
[ 1, 2, 3, 4, 5 ]
import os from typing import Union, Tuple, List import pandas as pd from flags import FLAGS from helpers import load_from_pickle, decode_class, sort_results_by_metric ROOT = FLAGS.ROOT RESULTS_FOLDER = FLAGS.RESULTS_FOLDER FULL_PATH_TO_CHECKPOINTS = os.path.join(ROOT, RESULTS_FOLDER, "checkpoints") def eval_resul...
normal
{ "blob_id": "5447bd3b08c22913ae50ee66ee81554d2357ef3e", "index": 3991, "step-1": "<mask token>\n\n\ndef eval_results(time_stamps: Union[Tuple, List], excel_file_path=os.path.\n join(FULL_PATH_TO_CHECKPOINTS, f'xVal_results.xlsx')):\n with pd.ExcelWriter(excel_file_path, mode='w') as writer:\n for ts...
[ 1, 2, 3, 4, 5 ]
import numpy as np import matplotlib.pyplot as plt from PIL import Image import cv2 import openslide class QualityPatch(): def __init__(self, original_img_path,label_img_path,patch_level,patch_size): """ parameter: original_img_path(str): the source of image label_img_path(s...
normal
{ "blob_id": "0ad71f02e37f2744036b134c33e037a724fd38a6", "index": 8049, "step-1": "<mask token>\n\n\nclass QualityPatch:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def getReleventPatches(self):\n relevent_patches = []\n for i, coor in enumerate(s...
[ 3, 6, 7, 9, 10 ]
#API End Points by Mitul import urllib.error, urllib.request, urllib.parse import json target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key' : 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrive...
normal
{ "blob_id": "d34159536e860719094a36cfc30ffb5fcae72a9a", "index": 296, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Retriving', url)\n<mask token>\nprint('Retrived', len(data), 'characters')\n<mask token>\nprint(json.dumps(js, indent=4))\nprint('Place id', js['results'][0]['place_id'])\n<mask tok...
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.2.14 on 2020-08-25 17:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20200825_1318'), ] operations = [ migrations.RenameField( model_name='cv', old_name='additionalskills_tex...
normal
{ "blob_id": "e296a5bea5465c2b84e37c7d83922adb01feab70", "index": 9828, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('blog', '000...
[ 0, 1, 2, 3, 4 ]
import csv #ratings.csv must be in the same directory skipped_header = False with open("ratings.csv") as in_file: csvreader = csv.reader(in_file) #read each row of ratings.csv (userId,movieId,rating,timestamp) with open("ratings_train.csv", 'w') as train_out: with open("ratings_test.csv", 'w...
normal
{ "blob_id": "e48a6a84268a0fe64e90714bd32712665934fc39", "index": 2223, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('ratings.csv') as in_file:\n csvreader = csv.reader(in_file)\n with open('ratings_train.csv', 'w') as train_out:\n with open('ratings_test.csv', 'w') as test_out:\n...
[ 0, 1, 2, 3, 4 ]
# test_LeapYear.py # By Alex Graalum import unittest import LeapYear class test_leapyear(unittest.TestCase): def test_four(self): self.assertEqual(LeapYear.leapyear(2012), True) def test_hundred(self): self.assertEqual(LeapYear.leapyear(2100), False) def test_fourhundred(self): self...
normal
{ "blob_id": "29cae66fdca65020a82212e5eabbc61eb900e543", "index": 7720, "step-1": "<mask token>\n\n\nclass test_leapyear(unittest.TestCase):\n <mask token>\n\n def test_hundred(self):\n self.assertEqual(LeapYear.leapyear(2100), False)\n\n def test_fourhundred(self):\n self.assertEqual(LeapY...
[ 4, 5, 6, 7, 8 ]
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_pa...
normal
{ "blob_id": "c66f4ee5719f764c8c713c23815302c00b6fb9af", "index": 310, "step-1": "<mask token>\n\n\n@app.route('/buy', methods=['GET', 'POST'])\n@login_required\ndef buy():\n \"\"\"Buy shares of stock\"\"\"\n if request.method == 'POST':\n if not request.form.get('symbol'):\n return apolog...
[ 3, 9, 13, 14, 15 ]
import os import urllib.request import zipfile import tarfile import matplotlib.pyplot as plt %matplotlib inline from PIL import Image import numpy as np # フォルダ「data」が存在しない場合は作成する data_dir = "./data/" if not os.path.exists(data_dir): os.mkdir(data_dir) # MNIStをダウンロードして読み込む from sklearn.datasets import fetch_open...
normal
{ "blob_id": "6f53a989ddf179b699186a78b5d8cf6d3d08cbb2", "index": 4756, "step-1": "import os\nimport urllib.request\nimport zipfile\nimport tarfile\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom PIL import Image\nimport numpy as np\n\n# フォルダ「data」が存在しない場合は作成する\ndata_dir = \"./data/\"\nif not os.path...
[ 0 ]
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import unittest import logging from collections import Counter from utility import token_util class TestFileReadingFunctions(unittest.TestCase)...
normal
{ "blob_id": "7c3798aa9cc5424656572dfaa87f7acb961613eb", "index": 8715, "step-1": "<mask token>\n\n\nclass TestFileReadingFunctions(unittest.TestCase):\n\n def setUp(self):\n self.data_dir = os.path.join(os.path.dirname(os.path.realpath(\n __file__)), 'data')\n self.one_word_per_line_p...
[ 4, 5, 6, 7, 8 ]
from collections import OrderedDict as odict from vent.gui import styles MONITOR = odict({ 'oxygen': { 'name': 'O2 Concentration', 'units': '%', 'abs_range': (0, 100), 'safe_range': (60, 100), 'decimals' : 1 }, 'temperature': { ...
normal
{ "blob_id": "941dac77fe60081ffa113c437a356d59837f5883", "index": 5304, "step-1": "<mask token>\n", "step-2": "<mask token>\nMONITOR = odict({'oxygen': {'name': 'O2 Concentration', 'units': '%',\n 'abs_range': (0, 100), 'safe_range': (60, 100), 'decimals': 1},\n 'temperature': {'name': 'Temperature', 'uni...
[ 0, 1, 2, 3 ]
### Script to convert matlab structure file (/motiongan/data/style-dataset/style_motion_database.mat') import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import argparse import math import numpy as np from collections import OrderedDict import scipy.io import pickle from core.utils.eul...
normal
{ "blob_id": "f2dac8b454805829cf5dbe2efe3c0de805ae4cb5", "index": 1727, "step-1": "<mask token>\n\n\ndef load_skeleton(mat_path):\n mat_data = scipy.io.loadmat(mat_path)['skel'][0, 0]\n skeleton = OrderedDict()\n bone_names = mat_data[1].tolist()\n for i, bone in enumerate(bone_names):\n bone =...
[ 3, 5, 6, 7, 8 ]
# -*- coding: utf-8 -*- """Very basic codec tests. :copyright: the translitcodec authors and developers, see AUTHORS. :license: MIT, see LICENSE for more details. """ import codecs import translitcodec data = u'£ ☹ wøóf méåw' def test_default(): assert codecs.encode(data, 'transliterate') == u'GBP :-( woof mea...
normal
{ "blob_id": "426002bf900e23fd9b1d32c484350ac854228459", "index": 2565, "step-1": "<mask token>\n\n\ndef test_translit_long():\n assert codecs.encode(data, 'translit/long') == u'GBP :-( woof meaaw'\n\n\ndef test_translit_short():\n assert codecs.encode(data, 'translit/short') == u'GBP :-( woof meaw'\n\n\n<m...
[ 6, 8, 9, 10, 12 ]
import re from xml.etree import ElementTree def get_namespace(xml_path): with open(xml_path) as f: namespaces = re.findall(r"xmlns:(.*?)=\"(.*?)\"", f.read()) return dict(namespaces) def get_comic_data(item, ns): return { "title": item.find("title").text, "post_date": item.find("...
normal
{ "blob_id": "86a15bb2e4d59fb5c8763fa2de31164beb327685", "index": 7928, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_namespace(xml_path):\n with open(xml_path) as f:\n namespaces = re.findall('xmlns:(.*?)=\\\\\"(.*?)\\\\\"', f.read())\n return dict(namespaces)\n\n\ndef get_comic...
[ 0, 2, 3, 4, 5 ]
"""Vista de Autorizaciones (Clientes/Especialistas/Vendedores).""" from django.shortcuts import render from dashboard.json2table import convert from django.utils.translation import ugettext_lazy as _ from api.connection import api from login.utils.tools import role_admin_check from django.utils.decorators import method...
normal
{ "blob_id": "b78ad3a55eb27fd91f89c22db07fadca297640ab", "index": 2892, "step-1": "<mask token>\n\n\nclass Autorization:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en...
[ 4, 5, 6, 7, 8 ]
#!/usr/bin/env python3 # -*- coding=utf-8 -*- # description: # author:jack # create_time: 2017/12/30 """ 卡片基类 """ import logging class BaseCard(object): def __init__(self, field=[]): self.data = {} self.support_set_field = field def add_cue_words(self, arr): """ 为卡片添加cue wor...
normal
{ "blob_id": "93e5852df00733c024a59d37699bae58bd893030", "index": 112, "step-1": "<mask token>\n\n\nclass BaseCard(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __getattr__(self, item):\n \"\"\"\n 添加魔术方法\n :param item:\n :return:\n \...
[ 2, 3, 4, 7, 9 ]
import scrapy from scrapy.loader import ItemLoader class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://blog.scrapinghub.com'] def content_title_parser(self, mystr): return mystr[0].split(' ')[3] def parse(self, response): for url in response.css('ul li a::attr...
normal
{ "blob_id": "4c79dcf394acbcc9a636bcc9b0aac13a2bafc7e3", "index": 9249, "step-1": "<mask token>\n\n\nclass BlogSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def parse(self, response):\n for url in response.css('ul li a::attr(\"href\")').re('.*/category/.*'):\n ...
[ 4, 5, 7, 8 ]
from HurdleRace import hurdleRace from ddt import ddt, data, unpack import unittest class test_AppendAndDelete3(unittest.TestCase): def test_hurdleRace(self): height = [1, 6, 3, 5, 2] k = 4 sum_too_high = hurdleRace(k, height) self.assertEqual(2, sum_too_high)
normal
{ "blob_id": "ea86a2a9068c316d3efcbcb165a8ef3d3516ba1b", "index": 4763, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass test_AppendAndDelete3(unittest.TestCase):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass test_AppendAndDelete3(unittest.TestCase):\n\n def test_hurdleRace(self):\...
[ 0, 1, 2, 3 ]
import inaccel.coral as inaccel import numpy as np import time class StereoBM: def __init__(self, cameraMA_l=None, cameraMA_r=None, distC_l=None, distC_r=None, irA_l=None, irA_r=None, bm_state=None ): # allocate mem for camera parameters for rectification and bm_state class with inaccel.allocator: if cameraMA_...
normal
{ "blob_id": "66f3590381fe96c49a8926a806b4a845f0d7e25d", "index": 4681, "step-1": "<mask token>\n\n\nclass StereoBM:\n <mask token>\n\n def runAsync(self, left_img, right_img):\n self.m_runStartTime = int(round(time.time() * 1000000))\n if left_img is None:\n raise RuntimeError('Inv...
[ 4, 5, 6, 7, 8 ]
import os import attr import click import guitarpro import psutil ALL = object() @attr.s class GPTools: input_file = attr.ib() output_file = attr.ib() selected_track_numbers = attr.ib(default=None) selected_measure_numbers = attr.ib(default=None) selected_beat_numbers = attr.ib(default=None) ...
normal
{ "blob_id": "c6821cb8dd6f8d74ca20c03f87dae321eb869c32", "index": 2454, "step-1": "<mask token>\n\n\n@attr.s\nclass GPTools:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def parse(self):\n if self.input_file is None:\n self.in...
[ 7, 8, 9, 11, 12 ]
# 213. 打家劫舍 II # 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。 # 同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。 # 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。 class Solution: # 86.24%, 15.46% def rob(self, nums) -> int: n = len(nums) if n == 0: ...
normal
{ "blob_id": "59b2c9d279168a806e59fb7529ab12d7b86107bc", "index": 5340, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n\n def helper(self, nums, n):\n if n == 1:\n return nums[0]\n dp = [0] * n\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])...
[ 0, 2, 3, 4, 5 ]
from random import random, randint, choice from copy import deepcopy from math import log """ Обертка для функций, которые будут находиться в узлах, представляющих функции. Его члены – имя функции, сама функция и количество принимаемых параметров. """ class fwrapper: def __init__(self, function, childcou...
normal
{ "blob_id": "89881f3cc6703b3f43f5d2dae87fa943d8a21513", "index": 5485, "step-1": "<mask token>\n\n\nclass fwrapper:\n\n def __init__(self, function, childcount, name):\n self.function = function\n self.childcount = childcount\n self.name = name\n\n\n<mask token>\n\n\nclass node:\n\n de...
[ 23, 25, 28, 31, 34 ]
def towers_of_hanoi(n, src, dest, temp,res): if n==1: s = 'disk 1 from ',src,'->',dest res.append(s) return towers_of_hanoi(n-1, src, temp, dest, res) s = 'disk ',n, ' from ',src,'->',dest res.append(s) towers_of_hanoi(n-1, temp, dest, src, res) return res def steps...
normal
{ "blob_id": "f23bfef2daf8fda4249435821dbc2e0b1846e3d6", "index": 9842, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef steps_in_tower_of_hanoi(no_of_disks):\n res = towers_of_hanoi(no_of_disks, 'A', 'C', 'B', [])\n return res\n\n\n<mask token>\n", "step-3": "def towers_of_hanoi(n, src, des...
[ 0, 1, 2, 3, 4 ]
_base_ = "../model.py" model = dict( type="ImageClassifier", task="classification", pretrained=None, backbone=dict(), head=dict(in_channels=-1, loss=dict(type="CrossEntropyLoss", loss_weight=1.0), topk=(1, 5)), ) checkpoint_config = dict(type="CheckpointHookWithValResults")
normal
{ "blob_id": "8bd5eff12e68f7145676f5e089b51376a82ab489", "index": 3231, "step-1": "<mask token>\n", "step-2": "_base_ = '../model.py'\nmodel = dict(type='ImageClassifier', task='classification', pretrained=None,\n backbone=dict(), head=dict(in_channels=-1, loss=dict(type=\n 'CrossEntropyLoss', loss_weight...
[ 0, 1, 2 ]
num=5 a=5 for row in range(num,0,-1): for col in range(row,0,-1): print(a,end="") a-=1 print()
normal
{ "blob_id": "a567a2dc1dbb59979d849a5a772e4592910a9f27", "index": 2783, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor row in range(num, 0, -1):\n for col in range(row, 0, -1):\n print(a, end='')\n a -= 1\n print()\n", "step-3": "num = 5\na = 5\nfor row in range(num, 0, -1):\n for...
[ 0, 1, 2, 3 ]
from airflow.plugins_manager import AirflowPlugin from flask import Blueprint, Flask from rest_api.log.views import views from rest_api.route.log_route import log from rest_api.route.mylog_route import my_log_pb from rest_api.route.native_log_route import native_log_bp class AirflowPlugin(AirflowPlugin): name = "...
normal
{ "blob_id": "39f1fc04911f8d22d07532add24cd1671a569e72", "index": 9414, "step-1": "<mask token>\n\n\nclass AirflowPlugin(AirflowPlugin):\n name = 'airflow-plugin'\n operators = []\n hooks = []\n executors = []\n macros = []\n admin_views = []\n flask_blueprints = []\n menu_links = []\n\n\n...
[ 2, 3, 4, 5, 6 ]
from django.http import HttpResponse from django.views.decorators.http import require_http_methods from django.shortcuts import render, redirect from app.models import PaidTimeOff, Schedule from django.utils import timezone from django.contrib import messages from app.decorators import user_is_authenticated from app....
normal
{ "blob_id": "7245d4db6440d38b9302907a6203c1507c373112", "index": 6970, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef index_get(request, user_id, user, pto):\n schedules = Schedule.to_calendar(Schedule.objects.filter(pto=pto))\n context = pto.__dict__\n context.update({'schedules': sched...
[ 0, 2, 3, 4, 5 ]
""" 给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ """ 解题思路: 先计算两个节点的值和与进位的和 然后将值对10取余存放到新的链表中 循环下去 直到l1 l2 进位都不存在 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): ...
normal
{ "blob_id": "80f681eb99d1e3f64cacd23ce0a4b10a74a79fe8", "index": 4223, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype:...
[ 1, 2, 3, 4, 5 ]
from collections import OrderedDict class LRU_Cache(object): def __init__(self, capacity): # Initialize class variables self.size = capacity self.jar = OrderedDict() pass def get(self, key): # Retrieve item from provided key. Return -1 if nonexistent. if key not ...
normal
{ "blob_id": "3c88e13e8796c5f39180a9a514f0528a074460a6", "index": 2198, "step-1": "<mask token>\n\n\nclass LRU_Cache(object):\n\n def __init__(self, capacity):\n self.size = capacity\n self.jar = OrderedDict()\n pass\n\n def get(self, key):\n if key not in self.jar:\n ...
[ 6, 8, 10, 11, 12 ]
from queuingservices.managers.queue_lifecycle_manager import QueueLifecycleManager from queuingservices.managers.queue_publisher_manager import QueuePublisherManager from queuingservices.managers.queue_subscriber_manager import QueueSubscriberManager class QueueMaster(QueueSubscriberManager, QueuePublisherManager, ...
normal
{ "blob_id": "b2b961c6ff1d975d80a84be361321ab44dc026a0", "index": 2134, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass QueueMaster(QueueSubscriberManager, QueuePublisherManager,\n QueueLifecycleManager):\n <mask token>\n pass\n", "step-3": "<mask token>\n\n\nclass QueueMaster(QueueSub...
[ 0, 1, 2, 3 ]
from django.shortcuts import render from .forms import TeacherForm,Teacher from django.http import HttpResponse def add_teacher(request): if request.method=="POST": form=TeacherForm(request.POST) if form.is_valid(): form.save() return redirect("list_teachers") else: return HttpResponse("in...
normal
{ "blob_id": "cf97c87400649dd15e5d006707f9adfbd0c91b2c", "index": 4118, "step-1": "<mask token>\n\n\ndef teacher_detail(request, pk):\n teacher = Teacher.objects.get(pk=pk)\n return render(request, 'teacher_detail.html', {'teacher': teacher})\n\n\ndef edit_teacher(request, pk):\n teacher = Teacher.object...
[ 2, 3, 4, 5, 6 ]
import rambench rambench.perform_benchmark()
normal
{ "blob_id": "3d1f2130043613dc8d5bbd773edd96c87c355de9", "index": 3455, "step-1": "<mask token>\n", "step-2": "<mask token>\nrambench.perform_benchmark()\n", "step-3": "import rambench\nrambench.perform_benchmark()\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!/usr/bin/python import pyglet from pyglet.gl import * win = pyglet.window.Window() @win.event def on_draw(): # Clear buffers glClear(GL_COLOR_BUFFER_BIT) # Draw outlines only glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # Draw some stuff glBegin(GL_TRIANGLES) glVertex3i(0, 0, 0) glVertex3i(300, 0, 0) glVe...
normal
{ "blob_id": "86c4193ec0fee8a0c06858913ec8153fcf0df6d9", "index": 4114, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@win.event\ndef on_draw():\n glClear(GL_COLOR_BUFFER_BIT)\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n glBegin(GL_TRIANGLES)\n glVertex3i(0, 0, 0)\n glVertex3i(300, 0,...
[ 0, 2, 3, 4, 5 ]
import re text = 'Macademia nuts, Honey tuile, Cocoa powder, Pistachio nuts' search_pattern = re.compile('nuts') search_match_object = search_pattern.search(text) if search_match_object: print(search_match_object.span()) print(search_match_object.start()) print(search_match_object.end()) print(search_...
normal
{ "blob_id": "ef5d235f09eea827b240290218c397f880f1046d", "index": 4433, "step-1": "<mask token>\n", "step-2": "<mask token>\nif search_match_object:\n print(search_match_object.span())\n print(search_match_object.start())\n print(search_match_object.end())\n print(search_match_object.group())\nprint...
[ 0, 1, 2, 3, 4 ]
import inputoutput def xor_encryption(source, destination, key): """ Returns text encrypted or decrypted with xor Keyword arguments: source - path to file with text to be encrypted destination - path to the file where you want to save the result key - encryption key """ text = inputou...
normal
{ "blob_id": "81774d3b4d9fbf22ed19e1cba7ec5e8e3707f51a", "index": 2076, "step-1": "<mask token>\n\n\ndef xor_encryption(source, destination, key):\n \"\"\"\n Returns text encrypted or decrypted with xor\n\n Keyword arguments:\n source - path to file with text to be encrypted\n destination - path to...
[ 1, 2, 3, 4, 5 ]
aes_key = 'eR5ceExL4IpUUY2lqALN7gLXzo11jlXPOwTwFGwOO3h='
normal
{ "blob_id": "7112348631bc60767bfb79c7f6966fc9189c522b", "index": 7901, "step-1": "<mask token>\n", "step-2": "aes_key = 'eR5ceExL4IpUUY2lqALN7gLXzo11jlXPOwTwFGwOO3h='\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import datetime def days_count(year, month, hour): point = datetime.datetime(year, month, hour, 0, 0, 0, 000000) now = datetime.datetime.now() interval_day = point - now return interval_day.days messages = { '猫钰钰 五月有砖搬': '距离 猫钰钰 上岗还有 {} 天'.format(days_count(2019, 6, 1)), # 6.1 上岗 'AD Zh': '...
normal
{ "blob_id": "82ce6304977d468945526824ade1500e10d25d09", "index": 2872, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef days_count(year, month, hour):\n point = datetime.datetime(year, month, hour, 0, 0, 0, 0)\n now = datetime.datetime.now()\n interval_day = point - now\n return interva...
[ 0, 1, 2, 3, 4 ]
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # from sklearn import tree # import joblib music_data = pd.read_csv(r"C:\Users\junha\PythonProjects\predict_music_preferences\music.csv") # print(music_dat...
normal
{ "blob_id": "8dbcd7bba09f8acff860890d8201e016b587796d", "index": 6149, "step-1": "<mask token>\n", "step-2": "<mask token>\nmodel.fit(X_train, y_train)\n<mask token>\nprint(predictions)\n<mask token>\nprint(score)\n", "step-3": "<mask token>\nmusic_data = pd.read_csv(\n 'C:\\\\Users\\\\junha\\\\PythonProj...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from customer_support.views import update_existing_subscriber, \ add_new_subscriber from .views import (EditSubscriberView, DeActivateSubscriberView, ReActivateSubscriberView, SupportSub...
normal
{ "blob_id": "fb4818e742ed3c7d131c426811f839dbe70f03de", "index": 2650, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = patterns('', url(regex='new_subscriber/$', view=\n add_new_subscriber, name='support.new_subscriber'), url(regex=\n 'update_subscriber/(?P<pk>\\\\d+)/$', view=update_e...
[ 0, 1, 2, 3 ]
#!/usr/bin/python import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) ledPin = 4 pinOn = False GPIO.setup(ledPin, GPIO.OUT) GPIO.output(ledPin, GPIO.LOW) def print_pin_status(pin_number): GPIO.setup(pin_number, GPIO.IN) value = GPIO.input(pin_number) print(f'Current Value of {pin_number} is {value}') G...
normal
{ "blob_id": "492c416becc44deaafef519eae8c9a82ac00cc0e", "index": 8632, "step-1": "<mask token>\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\n<mask t...
[ 1, 2, 3, 4, 5 ]
from nmigen import * class Top(Elaboratable): def __init__(self): self.counter = Signal(3) self.led = Signal() def elaborate(self, platform): m = Module() m.d.comb += self.led.eq(self.counter[2]) m.d.sync += self.counter.eq(self.counter + 1) return m
normal
{ "blob_id": "22b6ea64cdb109e1c6b2536b50935d09d37a7e1a", "index": 3057, "step-1": "<mask token>\n\n\nclass Top(Elaboratable):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Top(Elaboratable):\n <mask token>\n\n def elaborate(self, platform):\n m = Module()\n m.d.c...
[ 1, 2, 3, 4 ]
import os import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance with open('input.txt', 'r') as f: data = f.read() res = [i for i in data.splitlines()] print(res) newHold = [] for line in res: newHold.append((tuple(int(i) for i in line.split(', ')))) print(newHold) mapper = np....
normal
{ "blob_id": "47476fbb78ca8ce14d30bf226795bbd85b5bae45", "index": 6939, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('input.txt', 'r') as f:\n data = f.read()\n<mask token>\nprint(res)\n<mask token>\nfor line in res:\n newHold.append(tuple(int(i) for i in line.split(', ')))\nprint(newHol...
[ 0, 1, 2, 3, 4 ]
import tensorflow as tf def data_rescale(x): return tf.subtract(tf.divide(x, 127.5), 1) def inverse_rescale(y): return tf.round(tf.multiply(tf.add(y, 1), 127.5))
normal
{ "blob_id": "1a09b38838f40c4c6049da8e6a72ba3d56806c07", "index": 3703, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef inverse_rescale(y):\n return tf.round(tf.multiply(tf.add(y, 1), 127.5))\n", "step-3": "<mask token>\n\n\ndef data_rescale(x):\n return tf.subtract(tf.divide(x, 127.5), 1)\...
[ 0, 1, 2, 3 ]
''' Created on 2018-9-8 @author: weij ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os.path import sys import time import numpy as np from numpy import shape from scipy import linalg from sklearn import datas...
normal
{ "blob_id": "49995e60b817e2c5a2ea7e85e4fe96ca95363cb2", "index": 2148, "step-1": "<mask token>\n\n\ndef test_linearSVC(*data):\n X_train, X_test, y_train, y_test = data\n cls = svm.LinearSVC()\n cls.fit(X_train, y_train)\n print('Coefficients:%s,Intercept:%s' % (cls.coef_, cls.intercept_))\n print...
[ 5, 6, 7, 8, 10 ]
# Generated by Django 3.2.7 on 2021-10-01 08:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0005_alter_users_is_active'), ] operations = [ migrations.AlterModelManagers( name='users', managers=[ ],...
normal
{ "blob_id": "6670295241516664e30c7db5cd3b5e2fb6c4fb05", "index": 1985, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('app', '0005...
[ 0, 1, 2, 3, 4 ]
old_file = open("new.csv", "r") new_file = open("new1,csv", "w") for line in old_file.readlines(): cleaned_line =line.replace(',','.') new_file.write(cleaned_line) old_file.close new_file.close
normal
{ "blob_id": "b3d26d01d45c073192d06c8e94c06f7eae267b14", "index": 968, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor line in old_file.readlines():\n cleaned_line = line.replace(',', '.')\n new_file.write(cleaned_line)\nold_file.close\nnew_file.close\n", "step-3": "old_file = open('new.csv', '...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python import sys def solve(): numEngines = int(sys.stdin.readline()) engines = [] for _ in range(numEngines): engine = sys.stdin.readline() engines.append(engine) numQueries = int(sys.stdin.readline()) queries = [] for _ in range(numQueries): query = sys.stdin.readline() queries.append(...
normal
{ "blob_id": "174f5b04f02ec0c9651d5e34c8b04df8bfd4dff4", "index": 1943, "step-1": "#!/usr/bin/env python\n\nimport sys\n\ndef solve():\n\tnumEngines = int(sys.stdin.readline())\n\tengines = []\n\tfor _ in range(numEngines):\n\t\tengine = sys.stdin.readline()\n\t\tengines.append(engine)\n\n\tnumQueries = int(sys.s...
[ 0 ]
from oscar.app import Shop from apps.catalogue.app import application as catalogue_app class BaseApplication(Shop): catalogue_app = catalogue_app application = BaseApplication()
normal
{ "blob_id": "c8bb6ead7e305f466e24b47811d6ed38c8cfec0a", "index": 2691, "step-1": "<mask token>\n\n\nclass BaseApplication(Shop):\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseApplication(Shop):\n catalogue_app = catalogue_app\n\n\n<mask token>\n", "step-3": "<mask token>\n...
[ 1, 2, 3, 4 ]
import dash_html_components as html import dash_core_components as dcc import dash_daq as daq import dash_bootstrap_components as dbc import src.common.common_layout as layout_common def build_navbar(): return html.Div( id="banner", children=[ html.Div( id="banner-text...
normal
{ "blob_id": "f9dd20a3b72c0c8e72029459244486f31eaff536", "index": 9411, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef generate_modal():\n return html.Div(id='markdown', className='modal', children=html.Div(id=\n 'markdown-container', className='markdown-container', children=[\n h...
[ 0, 1, 2, 3, 4 ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Sponge_sy" # Date: 2021/9/11 import numpy from tqdm import tqdm from bert4keras.tokenizers import Tokenizer from bert4keras.models import build_transformer_model from bert4keras.snippets import sequence_padding, DataGenerator from utils import * class d...
normal
{ "blob_id": "5cb390b06026bc0899c0b10dc93f3ec1f2ffefa6", "index": 9727, "step-1": "<mask token>\n\n\nclass data_generator(DataGenerator):\n <mask token>\n\n def __init__(self, pattern='', is_pre=True, *args, **kwargs):\n super(data_generator, self).__init__(*args, **kwargs)\n self.pattern = pa...
[ 3, 4, 6, 7, 8 ]
import _thread import os from queue import Queue from threading import Thread import random import io import vk_api from vk_api.longpoll import VkLongPoll, VkEventType from datetime import datetime, timedelta import time from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from wordcloud import W...
normal
{ "blob_id": "03ce69924c885e59e40689dc63e50d54b89649f7", "index": 2924, "step-1": "<mask token>\n\n\ndef cloud(user_id):\n wall = tools.get_all('wall.get', 100, {'owner_id': user_id})['items']\n wall = list(filter(lambda x: datetime.fromtimestamp(x['date']).year ==\n current_year, wall))\n tokeniz...
[ 2, 4, 5, 6, 7 ]
# Generated by Django 2.0.7 on 2018-09-27 13:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('education', '0005_auto_20180927_1041'), ] operations = [ migrations.RemoveField( model_name='educationgroup', name='...
normal
{ "blob_id": "8ff7ace102b781b35fff0671e2c606bf662e2767", "index": 9851, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('education',...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import rospy import rosnode import csv import datetime import rosbag import sys import os import matplotlib.pyplot as plt import argparse import math from math import hypot import numpy as np from sensor_msgs.msg import LaserScan from std_msgs.msg import String import yaml as yaml start_time = Non...
normal
{ "blob_id": "c00a8bfec46ed829e413257bf97c44add564080d", "index": 8349, "step-1": "#!/usr/bin/env python\nimport rospy\nimport rosnode\nimport csv\nimport datetime\nimport rosbag\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nimport argparse\nimport math\nfrom math import hypot\nimport numpy as np\nfrom...
[ 0 ]
import numpy as np count = 0 # счетчик попыток number = np.random.randint(1, 101) # загадали число print("Загадано число от 1 до 100") def game_core_v3(number): '''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного. Функция...
normal
{ "blob_id": "66474b8cdca9a4aa48b8dc710d161a3a16495aed", "index": 6438, "step-1": "<mask token>\n\n\ndef game_core_v3(number):\n \"\"\"Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного.\n Функция принимает загаданное число...
[ 2, 3, 4, 5, 6 ]
import threading import serial import time bno = serial.Serial('/dev/ttyUSB0', 115200, timeout=.5) compass_heading = -1.0 def readBNO(): global compass_heading try: bno.write(b'g') response = bno.readline().decode() if response != '': compass_heading = float(response.split(...
normal
{ "blob_id": "63a7225abc511b239a69f625b12c1458c75b4090", "index": 8904, "step-1": "<mask token>\n\n\ndef readContinuous():\n while True:\n readBNO()\n time.sleep(0.1)\n\n\n<mask token>\n\n\ndef get_heading():\n return compass_heading\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef rea...
[ 2, 3, 4, 5, 7 ]
import numpy as np import copy ''' 本脚本主要用来实现决策树的相关内容。 constrcut_tree:该函数是构建决策树的主要函数 其输入:数据集X:n*p n:样本数,p-1维特征,p为样本类别, 以及属性信息label:属性名称,p-1一维数组,label表示的是此时X每一列对应的属性名称 决策结构用字典来表示,例如{attribution1:{0:{attribution2:{}},1:{attribution3:{}}} ''' def construct_tree(X,label): classList = [sample[-1] for sample in X] ...
normal
{ "blob_id": "ff66b33a133b627ba2329434d6c1649c94b6ec78", "index": 8188, "step-1": "<mask token>\n\n\ndef return_major(Y):\n label_count = {}\n for i in Y:\n label_count[i] = label_count.get(i, 0) + 1\n sorted_class = sorted(label_count.items(), key=operator.itemgetter(1),\n reverse=True)\n ...
[ 3, 4, 5, 6, 7 ]
from django.db import models # Create your models here. class Tutorial(models.Model): web_title = models.CharField(max_length=200) web_content = models.TextField() web_published = models.DateTimeField("date published") def __str__(self): return self.web_title
normal
{ "blob_id": "32499688db51f701173ec0ea212c483bf902c109", "index": 3048, "step-1": "<mask token>\n\n\nclass Tutorial(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Tutorial(models.Model):\n <mask token>\n <mask token>\n <mask...
[ 1, 2, 3, 4, 5 ]
class Node: def __init__(self,data): self.data = data self.next = None self.prev = None class dequeue: def __init__(self): self.front = None self.last = None self.count = 0 def add_front(self, data): new_nodef = Node(data) if(self.front ==...
normal
{ "blob_id": "2f6e0b6a7e14ac9c5a38db6fd2b1cf23cff7144e", "index": 172, "step-1": "<mask token>\n\n\nclass dequeue:\n\n def __init__(self):\n self.front = None\n self.last = None\n self.count = 0\n\n def add_front(self, data):\n new_nodef = Node(data)\n if self.front == Non...
[ 8, 10, 12, 13, 15 ]
# coding=utf-8 class HtmlDownload(object): """docstring for HtmlDownload""" def html_download(city, keyWords, pages): # root URL paras = { 'jl': city, 'kw': keyWords, 'pages': pages, 'isadv': 0 } url = "http://sou.zhaopin.com/jobs/searchresult.ashx?" + urlencode...
normal
{ "blob_id": "e33aca56e4c9f82779278e836308c2e22d3356e2", "index": 3770, "step-1": "<mask token>\n", "step-2": "class HtmlDownload(object):\n <mask token>\n <mask token>\n", "step-3": "class HtmlDownload(object):\n <mask token>\n\n def html_download(city, keyWords, pages):\n paras = {'jl': c...
[ 0, 1, 2, 3, 4 ]
from __future__ import unicode_literals from django.db import models # Create your models here. class Group(models.Model): name = models.CharField(max_length=200, db_index=True) loan_eligibility = models.CharField(max_length=200, db_index=True) account_number = models.CharField(max_length=200, db_index=Tr...
normal
{ "blob_id": "0c8b58acf33bdfa95984d29a75ae01e49d0da149", "index": 9202, "step-1": "<mask token>\n\n\nclass Member(models.Model):\n name = models.CharField(max_length=200, db_index=True)\n age = models.CharField(max_length=200)\n phone = models.CharField(max_length=200)\n address1 = models.CharField(ma...
[ 2, 3, 4, 5, 6 ]
from django.contrib import admin from .models import Game, Scrap admin.site.register(Game) admin.site.register(Scrap)
normal
{ "blob_id": "7e328992392a4ff2b0e23920a8907e38f63fcff0", "index": 7168, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.site.register(Game)\nadmin.site.register(Scrap)\n", "step-3": "from django.contrib import admin\nfrom .models import Game, Scrap\nadmin.site.register(Game)\nadmin.site.register(Sc...
[ 0, 1, 2 ]
from django import forms from .models import Profile class ImageForm(forms.ModelForm): userimage = forms.ImageField(required=False, error_messages={'invalid':("Image file only")}, widget=forms.FileInput) class Meta: model = Profile fields = ['userimage',]
normal
{ "blob_id": "9081d0f75ac53ab8d0bafb39cd46a2fec8a5135f", "index": 3813, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ImageForm(forms.ModelForm):\n <mask token>\n\n\n class Meta:\n model = Profile\n fields = ['userimage']\n", "step-3": "<mask token>\n\n\nclass ImageForm(fo...
[ 0, 1, 2, 3, 4 ]
from OTXv2 import OTXv2 from pandas.io.json import json_normalize from datetime import datetime, timedelta import getopt import sys from sendemail import sendemail from main import otx import csv import pandas as pd from pandas import read_csv import os.path def tools(): search = str(input('Please enter search: '...
normal
{ "blob_id": "659f45d2c6c7138f26b4a8d15d1710ae60450b08", "index": 6278, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef tools():\n search = str(input('Please enter search: '))\n search.strip()\n pulsesJSON = otx.search_pulses(search, 40)\n for aPulse in pulsesJSON['results']:\n n...
[ 0, 1, 2, 3 ]
# Generated by Django 2.2.2 on 2019-07-30 01:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('usuarios', '0001_initial'), ] operations = [ migrations.AlterField( model_name='usuario', name='inicio', ...
normal
{ "blob_id": "5e4a334b373d912ba37b18f95e4866450bda5570", "index": 3938, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('usuarios', ...
[ 0, 1, 2, 3, 4 ]
# import libraries import sys import pandas as pd import numpy as n from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): """ This function loads the message and categories files and merge them and return the new dataframe for the project """ # Read messages an...
normal
{ "blob_id": "4642537f8af1f060f5ee43cc9e98bd07be6a558c", "index": 124, "step-1": "# import libraries\nimport sys\nimport pandas as pd\nimport numpy as n\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n \"\"\"\n This function loads the message and categories f...
[ 0 ]
from selenium import webdriver import time import xlwt from JD_PhoneNo import get_phone_no book = xlwt.Workbook(encoding="utf-8") sheet1=book.add_sheet("Sheet 1") browser = webdriver.Firefox() browser.get("https://www.zomato.com/bhopal/dinner") z_hotel_list = [] z_address_list = [] z_phone_list = [] z_rating...
normal
{ "blob_id": "96425986305171a9d23231f60b35dcbcbbd12d2d", "index": 7995, "step-1": "<mask token>\n\n\ndef traverse(a, b):\n temp = []\n for i in range(a, b, 1):\n a = str(i)\n button = browser.find_element_by_link_text(a)\n button.click()\n name_list = browser.find_elements_by_cla...
[ 1, 2, 3, 4, 5 ]