code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
f=open('p102_triangles.txt') def cross(a,b,c): t1=b[0]-a[0] t2=b[1]-a[1] t3=c[0]-a[0] t4=c[1]-a[1] return t1*t4-t2*t3 x=[0,0] y=[0,0] z=[0,0] origin=(0,0) ans=0 for i in f.xreadlines(): x[0],x[1],y[0],y[1],z[0],z[1]=map(int,i.split(',')) area1=abs(cross(x,y,z)) area2=abs(cross(x,y,orig...
normal
{ "blob_id": "c34ff2bbb0ba743268ace77c110ce0b283a25eba", "index": 8637, "step-1": "f=open('p102_triangles.txt')\n\ndef cross(a,b,c):\n t1=b[0]-a[0]\n t2=b[1]-a[1]\n t3=c[0]-a[0]\n t4=c[1]-a[1]\n return t1*t4-t2*t3\n\nx=[0,0]\ny=[0,0]\nz=[0,0]\norigin=(0,0)\nans=0\nfor i in f.xreadlines():\n x[0]...
[ 0 ]
'''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest Created 27 Aug 20 @author: rik@electronicArtifacts.com ''' from collections import defaultdict import csv import datetime import json import random import re import requests import sys import time import urllib import re PRRDateFm...
normal
{ "blob_id": "b3758e42b52bb50d806832c6a3a76ae0537266de", "index": 8043, "step-1": "<mask token>\n\n\ndef freqHist3(tbl):\n \"\"\"python3 version\n\tASSUME: values are frequencies, returns sorted list of (val,freq) items in descending freq order\n\t\"\"\"\n from functools import cmp_to_key\n\n def cmpd1(a...
[ 10, 11, 13, 14, 16 ]
#!/usr/bin/env python number=int(input("Enter an integer")) if number<=100: print("Your number is smaller than equal to 100") else: print("Your number is greater than 100")
normal
{ "blob_id": "9666c87b4d4dc721683ea33fdbbeadefc65a0cd1", "index": 1860, "step-1": "<mask token>\n", "step-2": "<mask token>\nif number <= 100:\n print('Your number is smaller than equal to 100')\nelse:\n print('Your number is greater than 100')\n", "step-3": "number = int(input('Enter an integer'))\nif ...
[ 0, 1, 2, 3 ]
""" 题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。 今天测试组开完会后,他又发话了:在古老的一维模式识别中, 常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢? 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1) """ # -*- coding:utf-8 -*- class Solution: def FindGreatestSumOfSubArray(self, ar...
normal
{ "blob_id": "fcca845b60b050fa5dd0a3c50b3c36c154022f07", "index": 1467, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def FindGreatestSumOfSubArray(self, array):\n dp = [array[0]]\n res = array[0]\n f...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import codecs import Levenshtein import logging import random from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score import time from sklearn.model_selection import KFold import numpy as np import s...
normal
{ "blob_id": "37804c92b69d366cc1774335b6a2295dfd5b98f3", "index": 6592, "step-1": "<mask token>\n\n\ndef gen_label(uid1, uid2):\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2\n ].__contains__(uid1):\n return '1'\n else:\n return '-1'\n\n\n<mask token>\n\n\ndef gen_...
[ 2, 5, 6, 7, 8 ]
from django.db import models from django.utils import timezone class Test(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) answer = models.CharField(max_length=50) #def __str__(self): # return self.word1, ...
normal
{ "blob_id": "2a1d31b2123c11af3fce571287d3dad00a9b0086", "index": 2820, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Test(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Test(models.Model):\n word1 = models.Char...
[ 0, 1, 2, 3, 4 ]
# # cuneiform_python.py # # Example showing how to create a custom Unicode set for parsing # # Copyright Paul McGuire, 2021 # from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [ (0x10...
normal
{ "blob_id": "bc1aefd0b0a87b80a10cecf00407b4608a6902b5", "index": 3897, "step-1": "<mask token>\n\n\nclass Cuneiform(pp.unicode_set):\n <mask token>\n _ranges: List[Tuple[int, ...]] = [(66432, 66517), (73728, 74751), (\n 74752, 74879)]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Cuneif...
[ 1, 3, 4, 5, 6 ]
class Config(object): DEBUG = False TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False class Production(Config): SQLALCHEMY_DATABASE_URI = '<Production DB URL>' class Development(Config): # psql postgresql://Nghi:nghi1996@localhost/postgres DEBUG = True SQLALCHEMY_DATABASE_URI = 'pos...
normal
{ "blob_id": "e99d557808c7ae32ebfef7e7fb2fddb04f45b13a", "index": 6091, "step-1": "<mask token>\n\n\nclass Production(Config):\n <mask token>\n\n\nclass Development(Config):\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = 'postgresql://Nghi:nghi1996@localhost/postgres'\n SQLALCHEMY_ECHO = False\n JWT_SE...
[ 5, 6, 7, 8, 9 ]
# Generated by Django 2.2.5 on 2019-10-24 05:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('student', '0008_studentbasic_stu_class_num'), ] operations = [ migrations.AlterModelOptions( name='onduty', options=...
normal
{ "blob_id": "289aa48b4433be533c3916dd039136df45e0ac0b", "index": 1073, "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 = [('student', '...
[ 0, 1, 2, 3, 4 ]
import settings #from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns #admin.autodiscover() # Uncomment the next two lines to enable the admin...
normal
{ "blob_id": "acb85a16e45472dac61eed4162dc651f67a0e8ca", "index": 5400, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.autodiscover()\n<mask token>\n", "step-3": "<mask token>\nadmin.autodiscover()\nurlpatterns = patterns('', url('^media/(?P<path>.*)$',\n 'django.views.static.serve', {'document...
[ 0, 1, 2, 3, 4 ]
 class TrieTree(object): def __init__(self): self.size=0 self.childern=[None]*26 def insert(self,word): node=self for w in word: index=ord(w)-97 node.size+=1 if node.childern[index]==None: node.childern[index]=TrieTree() ...
normal
{ "blob_id": "a18fad746a1da3327d79ac0a61edd156c5fb8892", "index": 6127, "step-1": "\n\nclass TrieTree(object):\n def __init__(self):\n self.size=0\n self.childern=[None]*26\n def insert(self,word):\n node=self\n for w in word:\n index=ord(w)-97\n node.size+...
[ 0 ]
""" In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class...
normal
{ "blob_id": "e7b96c0161e65f3f22f2ad0832fc6d1bb529f150", "index": 9772, "step-1": "<mask token>\n\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented terminology: an abstract class).\n\n You do not nee...
[ 8, 10, 12, 13, 15 ]
#!/usr/bin/env python #--coding: utf8-- import time if __name__ == '__main__': date = time.strftime('%m-%d') if date == '03-08': print '女神节' elif date == '02-14': print '情人节' else: print '发红包' print '这是一个测试题'
normal
{ "blob_id": "23375760c0943ca177b7009031d9d17a91165c5c", "index": 230, "step-1": "#!/usr/bin/env python\n#--coding: utf8--\nimport time\n\nif __name__ == '__main__':\n date = time.strftime('%m-%d')\n if date == '03-08':\n print '女神节'\n elif date == '02-14':\n print '情人节'\n else:\n ...
[ 0 ]
from models import Cell,Board import random from pdb import set_trace as bp status={'end':-1} game=None class Game_Service(object): def __init__(self,row_num,col_num): self._row_num=row_num self._col_num=col_num mine_percent=0.3 self._mine_num=int(mine_percent*float(self._row_nu...
normal
{ "blob_id": "4af72cab6444922ca66641a08d45bcfe5a689844", "index": 6763, "step-1": "<mask token>\n\n\nclass Game_Service(object):\n\n def __init__(self, row_num, col_num):\n self._row_num = row_num\n self._col_num = col_num\n mine_percent = 0.3\n self._mine_num = int(mine_percent * f...
[ 5, 6, 7, 9, 10 ]
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import pandas import numpy import json import torch.utils.data as data import os import torch def load_json(file): with open(file) as json_file: data = json.load(json_file) return data class VideoDataSet(data.Dataset): def __init_...
normal
{ "blob_id": "e5b5a0c8c0cbe4862243548b3661057240e9d8fd", "index": 6077, "step-1": "<mask token>\n\n\nclass VideoDataSet(data.Dataset):\n <mask token>\n\n def check_csv(self):\n for video in self.video_list:\n if not os.path.exists(self.feature_path + 'csv_mean_' + str(\n sel...
[ 17, 21, 28, 31, 32 ]
from typing import Dict, Optional from collections import OrderedDict import torch import torch.nn as nn import torch.optim as optim import yaml def get_device() -> torch.device: if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") def load_yaml_config(config_path: s...
normal
{ "blob_id": "e8a36bd7826c5d71cf8012ea82df6c127dd858fc", "index": 549, "step-1": "<mask token>\n\n\ndef load_yaml_config(config_path: str) ->Dict:\n with open(config_path, 'r') as stream:\n return yaml.load(stream)\n\n\ndef get_optimizer(model: nn.Module, optim_config: Dict) ->optim.Optimizer:\n retu...
[ 4, 5, 6, 7, 8 ]
import sys, getopt sys.path.append('.') import RTIMU import os.path import time import math import encoders import motors #right is master, left is slave master_power = .6 slave_power = -.6 right_num_revs = 0 left_num_revs = 0 kp = .5 encoders.init() motors.init() en_left, en_right = encoders.read() SETTINGS_FILE ...
normal
{ "blob_id": "00f8a56b160cab22bf73c0d2397eb2c411e8c966", "index": 7714, "step-1": "<mask token>\n\n\ndef adjustMotorPowers():\n global slave_power\n global en_left\n global en_right\n global kp\n error = en_right + en_left\n slave_power -= error / kp\n encoders.clear()\n time.sleep(0.1)\n\...
[ 2, 3, 4, 5, 6 ]
from configparser import ConfigParser from ef.config.components import * from ef.config.efconf import EfConf from ef.config.section import ConfigSection comp_list = [BoundaryConditions, InnerRegion, OutputFile, ParticleInteractionModel, ParticleSource, SpatialMesh, TimeGrid, ExternalFieldUniform] def t...
normal
{ "blob_id": "edcccc673994a8de281a683b747de52d2115f89e", "index": 347, "step-1": "<mask token>\n\n\ndef test_components_to_conf_and_back():\n for Component in comp_list:\n x = Component()\n y = x.to_conf().make()\n assert x == y\n\n\n<mask token>\n\n\nclass TestEfConf:\n\n def test_conf...
[ 4, 5, 6, 8, 9 ]
import os import requests def download(url: str, dest_folder: str): #https://stackoverflow.com/a/56951135/8761164 if not os.path.exists(dest_folder): os.makedirs(dest_folder) # create folder if it does not exist filename = url.split('/')[-1].replace(" ", "_") # be careful with file names fil...
normal
{ "blob_id": "0726a4fa3af196e2ba1592019f09afb0e7bb47d7", "index": 9731, "step-1": "<mask token>\n\n\ndef parse_lat(lat: int):\n lat_str = 'N' if lat >= 0 else 'S'\n if 10 > lat > -10:\n lat_str += '0'\n lat_str += str(abs(lat))\n return lat_str\n\n\n<mask token>\n", "step-2": "<mask token>\n\...
[ 1, 3, 4, 5, 6 ]
import cv2 import pytesseract import os from PIL import Image import numpy as np from helper_functions import Helper class ImageData: # multipliers to get portion of image with interval value __bottom_thresh = 0.9 __left_thresh = 0.35 __right_thresh = 0.65 # (words, offset) to contour interval value __words_of...
normal
{ "blob_id": "d3be26d56b3597a5d9e3a870b735a30d90d1e501", "index": 8165, "step-1": "<mask token>\n\n\nclass ImageData:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, image):\n self.image = image\n self._contour_interval_dist = None\...
[ 6, 10, 11, 12, 17 ]
# coding=utf8 def InsertSort(array_a, n): for i in range(1, n): temp = array_a[i] j = i - 1 while temp < array_a[j] and j >= 0: array_a[j + 1] = array_a[j] # 如果小于其前驱,则从后往前寻找插入位置并后移。 j -= 1 array_a[j + 1] = temp return array_a def ShellSort(array_a, n):...
normal
{ "blob_id": "a01783e3687278d1ec529c5123b9151721ba3364", "index": 3033, "step-1": "# coding=utf8\n\ndef InsertSort(array_a, n):\n for i in range(1, n):\n temp = array_a[i]\n j = i - 1\n while temp < array_a[j] and j >= 0:\n array_a[j + 1] = array_a[j] # 如果小于其前驱,则从后往前寻找插入位置并后移。\...
[ 0 ]
#!/usr/bin/python # -*- coding: utf-8 -*- import json import urllib2 #this is executed by a cron job on the pi inside the pooltable secret ='secret' baseurl='https://pooltable.mysite.com/' url = baseurl + 'gettrans.php?secret=' + secret req = urllib2.Request(url) f = urllib2.urlopen(req) response = f.read()...
normal
{ "blob_id": "9baf55eb2fb70e9fa0d92df22d307962b8d6c6d4", "index": 5883, "step-1": "#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport json\r\nimport urllib2\r\n#this is executed by a cron job on the pi inside the pooltable\r\nsecret ='secret'\r\nbaseurl='https://pooltable.mysite.com/'\r\nurl = baseurl + '...
[ 0 ]
import os import numpy as np from argparse import ArgumentParser from collections import Counter from typing import Iterable, Dict, Any, Tuple from utils.constants import TRAIN, VALID, TEST, SAMPLE_ID, INPUTS, OUTPUT from utils.file_utils import make_dir from utils.data_writer import DataWriter WINDOW = 50 STRIDE = ...
normal
{ "blob_id": "e82dd2792ecbb8ed5a33012239102d2c6a02202b", "index": 1749, "step-1": "<mask token>\n\n\ndef get_partition(subject_id: int) ->str:\n if subject_id <= 10:\n return TEST\n elif subject_id <= 15:\n return VALID\n else:\n return TRAIN\n\n\ndef data_generator(input_folder: str...
[ 3, 4, 5, 6, 7 ]
# !/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2021 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
normal
{ "blob_id": "129df937d7d295bae2009cfb65b2f85228206698", "index": 8657, "step-1": "<mask token>\n\n\nclass SGD(BasicOptimizer):\n <mask token>\n\n def __init__(self, iterations: int, circuit: BasicCircuit,\n learning_rate: float):\n \"\"\"The constructor of the SGD class\n\n Args:\n ...
[ 2, 3, 4, 5, 6 ]
#cerner_2^5_2019 #Mason Seeger submission 1 from random import randint as r import operator as o #Only works with valid integers. A function for quick math brain training. def randomMath(): correct = 0 while(correct<10): str_ops = ['+', '-', '*', '/', '%'] ops = {'+': o.add, '-': o.sub, '*': o...
normal
{ "blob_id": "12f035962925c5380c782e8fad23f16fe9fb9435", "index": 5311, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef randomMath():\n correct = 0\n while correct < 10:\n str_ops = ['+', '-', '*', '/', '%']\n ops = {'+': o.add, '-': o.sub, '*': o.mul, '/': o.floordiv, '%': o.mo...
[ 0, 1, 2, 3, 4 ]
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras.initializers import RandomUniform class Critic: def __init__(self, obs_dim, action_dim, learning_rate=0.001): self.obs_dim = obs_dim self.action_dim = action_dim self.model = self.make_network() ...
normal
{ "blob_id": "535fdee8f74b1984c5d1a5ec929310473b01239d", "index": 1617, "step-1": "<mask token>\n\n\nclass Critic:\n\n def __init__(self, obs_dim, action_dim, learning_rate=0.001):\n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.model = self.make_network()\n self.opti...
[ 7, 8, 9, 10, 11 ]
import socket import threading import os import time import psutil import shutil class server: def __init__(self): self.commandSock = socket.socket() self.commandPort = 8080 self.transferSock = socket.socket() self.transferPort = 8088 self.chatSock=socket.socket() ...
normal
{ "blob_id": "4736f4e06f166b3c3fd8379a2021eb84a34fcbd3", "index": 6099, "step-1": "<mask token>\n\n\nclass server:\n\n def __init__(self):\n self.commandSock = socket.socket()\n self.commandPort = 8080\n self.transferSock = socket.socket()\n self.transferPort = 8088\n self.ch...
[ 7, 9, 11, 15, 16 ]
import argparse from flower_classifier import FlowerClassifier from util import * parser = argparse.ArgumentParser() parser.add_argument("data_dir", help="path to training images") parser.add_argument("--save_dir", default=".", help="path where checkpoint is saved") parser.add_argument("--arch", default="vgg11", help=...
normal
{ "blob_id": "0c3947a1699c78080661a55bbaa9215774b4a18e", "index": 4751, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('data_dir', help='path to training images')\nparser.add_argument('--save_dir', default='.', help=\n 'path where checkpoint is saved')\nparser.add_argument('--arch',...
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/env python3 import warnings import config import numpy as np from latplan.model import ActionAE, default_networks from latplan.util import curry from latplan.util.tuning import grid_search, nn_task import keras.backend as K import tensorflow as tf float_formatter = lambda x: "%.3f" % x np.set_printo...
normal
{ "blob_id": "f1c6340880b52ba86856913f74c7d589d9b49f49", "index": 5179, "step-1": "<mask token>\n", "step-2": "<mask token>\nnp.set_printoptions(formatter={'float_kind': float_formatter})\n<mask token>\nif __name__ == '__main__':\n import numpy.random as random\n import sys\n if len(sys.argv) == 1:\n ...
[ 0, 1, 2, 3, 4 ]
from redis_db import RedisClient from setting import TEST_URL import requests class Test_Proxy(): def __init__(self): self.db=RedisClient() def proxy_test(self, proxy): url = TEST_URL proxies={ "http":proxy, "https":proxy } # print("{}(测试中)".form...
normal
{ "blob_id": "2cbdb828ab6e0ad44154f0c5b2a1d807fd0d2520", "index": 8783, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Test_Proxy:\n\n def __init__(self):\n self.db = RedisClient()\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Test_Proxy:\n\n def __init__(self):\n ...
[ 0, 2, 3, 4, 5 ]
from django.apps import AppConfig class BuyerSellerAppConfig(AppConfig): name = 'buyer_seller_app'
normal
{ "blob_id": "0b730314fef31e7304a8f5d8bb998581b021a610", "index": 1798, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass BuyerSellerAppConfig(AppConfig):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass BuyerSellerAppConfig(AppConfig):\n name = 'buyer_seller_app'\n", "step-4": "from...
[ 0, 1, 2, 3 ]
from .models import CNNClassifier, load_weights, LastLayer_Alexnet, classes, MyResNet from .transforms import image_transforms, tensor_transform from .utils import newest_model, Dataset, load_data
normal
{ "blob_id": "17781ae5e9c72232fbc11c7eda7daeaeb0fa3670", "index": 9277, "step-1": "<mask token>\n", "step-2": "from .models import CNNClassifier, load_weights, LastLayer_Alexnet, classes, MyResNet\nfrom .transforms import image_transforms, tensor_transform\nfrom .utils import newest_model, Dataset, load_data\n"...
[ 0, 1 ]
import math import numpy import theano from theano import tensor as T from utils import shared_dataset from layer import HiddenLayer, LogisticRegressionLayer import pickle as pkl from mlp import MLP, Costs, NeuralActivations DEBUGGING = False class PostMLP(MLP): """Post training:- Second phase MLP. A mul...
normal
{ "blob_id": "f9ea29f882c6491a2ac0007e4d9435c732d0967a", "index": 8582, "step-1": "import math\n\nimport numpy\nimport theano\n\nfrom theano import tensor as T\n\nfrom utils import shared_dataset\n\nfrom layer import HiddenLayer, LogisticRegressionLayer\nimport pickle as pkl\n\nfrom mlp import MLP, Costs, NeuralA...
[ 0 ]
from urllib.parse import urlencode from urllib.request import urlopen, Request from datetime import datetime #пользовательские переменные period=7 # задаём период. Выбор из: 'tick': 1, 'min': 2, '5min': 3, '10min': 4, '15min': 5, '30min': 6, 'hour': 7, 'daily': 8, 'week': 9, 'month': 10 start = "01.01.2021" #с какой д...
normal
{ "blob_id": "9d22a90835f5cf293808ab359244fe1bde81f3e1", "index": 2171, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor ticker in tickers:\n params = urlencode([('market', market), ('em', tickers[ticker]), (\n 'code', ticker), ('apply', 0), ('df', start_date.day), ('mf', \n start_date....
[ 0, 1, 2, 3, 4 ]
import base64 import json from werkzeug.exceptions import Unauthorized from ab import app from ab.utils import logger from ab.plugins.spring import eureka def _login(username, password): """ only for test :return the access token """ try: logger.info('login as user {username}'.format(us...
normal
{ "blob_id": "342063b37038c804c2afa78091b1f1c2facbc560", "index": 3102, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_current_user(s: str=None, required=True):\n \"\"\"\n get current user by request auth header\n :param s:\n :return:\n {'code': 'SUCCESS', 'nickName': 'gs1',...
[ 0, 1, 2, 3, 4 ]
import time from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtSql import * from PyQt5.QtWidgets import * from qgis.core import QgsFeature, QgsGeometry, QgsProject from shapely import wkb print(__name__) # Function definition def TicTocGenerator(): # Generator that returns time differences ti...
normal
{ "blob_id": "73ff1444b5ab1469b616fe449ee6ab93acbbf85a", "index": 918, "step-1": "import time\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtWidgets import *\nfrom qgis.core import QgsFeature, QgsGeometry, QgsProject\nfrom shapely import wkb\n\nprint(__name__)\n\n\...
[ 0 ]
from tw.core import *
normal
{ "blob_id": "ea25aedc4728c18ac3d5da22c76cb7f1ef65e827", "index": 4958, "step-1": "<mask token>\n", "step-2": "from tw.core import *\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
from django.conf.urls import url from django.contrib import admin from comments.api.views import CommentListAPIView, CommentDetailAPIView urlpatterns = [ url(r'^$', CommentListAPIView.as_view(), name='list'), url(r'^(?P<pk>\d+)/$', CommentDetailAPIView, name='detail'), ]
normal
{ "blob_id": "e08820ff4fb35a3770fcb110ef7181aad1abbae5", "index": 8778, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [url('^$', CommentListAPIView.as_view(), name='list'), url(\n '^(?P<pk>\\\\d+)/$', CommentDetailAPIView, name='detail')]\n", "step-3": "from django.conf.urls import url...
[ 0, 1, 2, 3 ]
from django.contrib import admin from django.urls import path, include from .views import hindex,galeria,mision_vision,direccion,registro,login,logout_vista,registro_insumo,admin_insumos urlpatterns = [ path('',hindex,name='HINDEX'), path('galeria/',galeria,name='GALE'), path('mision/',mision_vision,name=...
normal
{ "blob_id": "dff5a46c6f1eb715fe5e1eec87e42ceb295b0eae", "index": 4650, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('', hindex, name='HINDEX'), path('galeria/', galeria,\n name='GALE'), path('mision/', mision_vision, name='MISION'), path(\n 'direccion/', direccion, name='UBICA...
[ 0, 1, 2, 3 ]
import sys import queue as q from utils import * LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' lines = sys.stdin.readlines() i_max = len(lines) j_max = len(lines[0]) deltas = [ ((0, 0), (0, 1), (0, 2)), ((0, 1), (0, 2), (0, 0)), ((0, 0), (1, 0), (2, 0)), ((1, 0), (2, 0), (0, 0)), ] p...
normal
{ "blob_id": "973fc3a973d952cb0f192221dfda63e255e4a8a0", "index": 2543, "step-1": "<mask token>\n\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\n<m...
[ 3, 4, 5, 6, 7 ]
#!/usr/bin/env python3 import math from PIL import Image as Image # NO ADDITIONAL IMPORTS ALLOWED! def in_bound(dim , s): """Get inbound pixel coordinate for out-of-bound Args: dim (int): Image height or width s (int): Coordinate Returns: int: Inbound """ if s <= -1: ...
normal
{ "blob_id": "591b1a2e245ae0f3c9b2a81769bbf5988574ed07", "index": 8253, "step-1": "<mask token>\n\n\ndef in_bound(dim, s):\n \"\"\"Get inbound pixel coordinate for out-of-bound\n\n Args:\n dim (int): Image height or width\n s (int): Coordinate \n\n Returns:\n int: Inbound\n \"\"\"...
[ 8, 10, 13, 15, 16 ]
x = int(input("Enter number:")) y = x/2 print(y) for i in
normal
{ "blob_id": "79c6b7c3d23248f249b55af1d097a66a78a2c22f", "index": 9164, "step-1": "x = int(input(\"Enter number:\"))\ny = x/2\nprint(y)\n\nfor i in \n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import pytest from time import sleep from timeflux.helpers.background import Task class DummyWorker(): def echo(self, message='hello', delay=0, fail=False): sleep(delay) if fail: raise Exception('failed') self.message = message return(self.message) def test_default(working_path): ...
normal
{ "blob_id": "d2e46944ab05c5e8c1979101728b7b25900be342", "index": 415, "step-1": "<mask token>\n\n\nclass DummyWorker:\n\n def echo(self, message='hello', delay=0, fail=False):\n sleep(delay)\n if fail:\n raise Exception('failed')\n self.message = message\n return self.me...
[ 4, 5, 7, 9, 10 ]
#!/bin/python3 import sys from collections import deque def connectedCell(matrix,n,m): # Complete this function visit = [] for j in range(n): a = [] for i in range(m): a.append(True) visit.append(a) #print(visit) path = 0 for i in range(n): for j in ...
normal
{ "blob_id": "25a159ca2abf0176135086324ab355d6f5d9fe9e", "index": 5054, "step-1": "<mask token>\n\n\ndef connectedCell(matrix, n, m):\n visit = []\n for j in range(n):\n a = []\n for i in range(m):\n a.append(True)\n visit.append(a)\n path = 0\n for i in range(n):\n ...
[ 1, 2, 3, 4, 5 ]
import random ''' 通用文件头,浏览器访问时随机选择 ''' user_agent = [ "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50", "Mozilla/5....
normal
{ "blob_id": "5ed91b98ece3ac9525e9d2c42db9c9d9912d5ed2", "index": 9029, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_user_agent():\n return {'User-Agent': random.choice(user_agent)}\n", "step-3": "<mask token>\nuser_agent = [\n 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us...
[ 0, 1, 2, 3, 4 ]
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math # initialize global variables used in your code range = 100 guesses_made = 0 guesses_remaining = 0 highest_guess = 0 lowes...
normal
{ "blob_id": "783326ccec31dc7a0ff46c5e4b69806e99aeda57", "index": 9136, "step-1": "# template for \"Guess the number\" mini-project\n# input will come from buttons and an input field\n# all output for the game will be printed in the console\nimport simplegui\nimport random\nimport math\n\n# initialize global vari...
[ 0 ]
''' This module is used for handling the button. ''' import RPi.GPIO as GPIO from aiy.voicehat import * class Button: status = bool() #status indicates whether it is supposed to be on or off. LED_pin = 25 #Pin for the LED in the button in the Google AIY kit. button_pin = 23#...
normal
{ "blob_id": "878937e19d6a48a0d44309efbac1d41c208ce849", "index": 6195, "step-1": "<mask token>\n\n\nclass Button:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def read_button(self):\n self.status = GPIO.input(self.button_pin)\n\n def light(self, stat):\n if stat...
[ 4, 5, 6, 7, 8 ]
# -*- coding:utf-8 -*- ''' Created on 2013. 4. 30. @author: Hwang-JinHwan parsing the txt file which are generated by coping the pdf nova praxis rpg rule book to create bootstrap document ''' import re import codecs template = """ <head> <style type="text/css"> body {{ padding-...
normal
{ "blob_id": "c036621c5f03d94987b4da004d063d11a7cc8424", "index": 4418, "step-1": "# -*- coding:utf-8 -*-\r\n'''\r\nCreated on 2013. 4. 30.\r\n\r\n@author: Hwang-JinHwan\r\n\r\nparsing the txt file which are generated by coping the pdf nova praxis rpg rule book \r\nto create bootstrap document\r\n'''\r\nimport re...
[ 0 ]
import user # or from user import User from post import Post app_user_one = user.User("rr@gg.com", "Riks R", "ppp1", "student") app_user_one.get_user_info() app_user_one.change_status("in job market") app_user_one.get_user_info() app_user_two = user.User("z43@gg.com", "Bobby L", "zz1", "student") app_user_two.get_us...
normal
{ "blob_id": "f59db28b669a41051cc6d0d4b8e14d1c7b0edd11", "index": 2555, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_user_one.get_user_info()\napp_user_one.change_status('in job market')\napp_user_one.get_user_info()\n<mask token>\napp_user_two.get_user_info()\n<mask token>\nnew_post.get_post_info()...
[ 0, 1, 2, 3, 4 ]
import copy from typing import List, Optional, Tuple, NamedTuple, Union, Callable import torch from torch import Tensor from torch_sparse import SparseTensor import time import torch_quiver as qv from torch.distributed import rpc def subgraph_nodes_n(nodes, i): row, col, edge_index = None, None, None return r...
normal
{ "blob_id": "3f4f396d1d18611e0248a08b42328422ca4b8146", "index": 4766, "step-1": "<mask token>\n\n\nclass Adj(NamedTuple):\n adj_t: SparseTensor\n e_id: Optional[Tensor]\n size: Tuple[int, int]\n <mask token>\n\n\nclass RandomIndexSampler(torch.utils.data.Sampler):\n\n def __init__(self, num_nodes...
[ 12, 15, 18, 20, 21 ]
from .tc_gcc import * class AndroidGccToolChain(GccToolChain): def __init__(self, name, ndkDir, gccVersionStr, platformVer, archStr, prefix = "", suffix = ""): # TODO: non-windows host platform hostPlatform = 'windows' installDir = os.path.join(ndkDir, 'toolchains', prefix + gccVersionStr,...
normal
{ "blob_id": "d6574cacea693517f3eaa92b4b929c2ee73da2e4", "index": 4421, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass AndroidGccToolChain(GccToolChain):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass AndroidGccToolChain(GccToolChain):\n\n def __init__(self, name, ndkDir, gccVersi...
[ 0, 1, 2, 3, 4 ]
"""Distribution script for unitreport.""" import setuptools with open("README.md", "r") as f: long_description = f.read() setuptools.setup( name="unitreport", version="0.1.1", author="annahadji", author_email="annahadji@users.noreply.github.com", description="A small unittest-based tool for ge...
normal
{ "blob_id": "7a243f5e24d81d3395cc790dface5e795b9c04e6", "index": 4495, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('README.md', 'r') as f:\n long_description = f.read()\nsetuptools.setup(name='unitreport', version='0.1.1', author='annahadji',\n author_email='annahadji@users.noreply.git...
[ 0, 1, 2, 3 ]
import pickle import numpy as np in_dir = "C:\\Users\\ganga\\Github\\Generative-Models\\Project\\Data\\Dynamics\\" out_dir = f"C:\\Users\\ganga\\Github\\Generative-Models\\Project\\Data\\Dynamics\\" # Read frames train_frames = pickle.load( open(in_dir +'\\train_frames.pkl' , 'rb' )) test_frames = pickle.load( open(...
normal
{ "blob_id": "e048170775c589cf0a9fb3d54c72dab4df3f1bcb", "index": 7558, "step-1": "<mask token>\n\n\ndef sigmoid(x):\n return 0.5 * (1 + np.tanh(0.5 * x))\n\n\ndef bernoulli_array(prob_array, dim):\n sample = np.zeros(dim)\n uni_sample = np.random.uniform(0, 1, dim)\n diff = uni_sample - prob_array\n ...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python3 import datetime, random class State(object): def __init__(self, name): self.name = name def __str__(self): return self.name class State_New(State): def __init__(self): super(State_New, self).__init__("New") class State_Underway(State): def __init__(sel...
normal
{ "blob_id": "e40b34f0ee51cc14615c6225a7676929e6d2876a", "index": 2975, "step-1": "<mask token>\n\n\nclass State_Underway(State):\n\n def __init__(self):\n super(State_Underway, self).__init__('Underway')\n\n\nclass State_Paused(State):\n\n def __init__(self):\n super(State_Paused, self).__ini...
[ 25, 26, 30, 31, 34 ]
class Solution(object): def checkSubarraySum(self, nums, k): if not nums or len(nums) == 1: return False sum_array = [0] * (len(nums) + 1) for i, num in enumerate(nums): sum_array[i + 1] = sum_array[i] + num if k == 0: if sum_array[-1] == 0: ...
normal
{ "blob_id": "033973ddc81a5fdf0e40009c4f321215fe3f4217", "index": 6779, "step-1": "<mask token>\n", "step-2": "class Solution(object):\n <mask token>\n", "step-3": "class Solution(object):\n\n def checkSubarraySum(self, nums, k):\n if not nums or len(nums) == 1:\n return False\n ...
[ 0, 1, 2 ]
__author__ = 'Freek' __build__ = 'versie 1.0' from iNStagram.file_io.fileio import lees_stationgegevens from iNStagram.api_requests.app_requests import request_instagram from tkinter import * startscherm = Tk() startscherm.title('Foto of video in de buurt!') startscherm.minsize(width=790, height=600, ) startscherm.c...
normal
{ "blob_id": "2804d49fc9f0e40859de1e8eb4f04a849639b1d4", "index": 8277, "step-1": "<mask token>\n\n\ndef weergeef_instagram_links():\n \"\"\"\n Geeft de bijbehorende station dict uit de lijst van alle stations (in de NS API)\n :param stationnaam: geef ofwel kort, middel als lange stationnaam om de bijbeh...
[ 1, 2, 3, 4, 5 ]
#! python3 import os import shutil import re import argparse def create_test_file(filename): with open(filename, "w") as f: f.write("foobar") def create_test_files(test_dir, file_prefix): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(test_dir) for i in range(1, 10): ...
normal
{ "blob_id": "db684185c2b0a26cb101dc40090c84b64c554eeb", "index": 2595, "step-1": "<mask token>\n\n\ndef create_test_file(filename):\n with open(filename, 'w') as f:\n f.write('foobar')\n\n\n<mask token>\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Filling In The Gaps program')\n ...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python import sys from static_pipeline import render from static_pipeline.lib import argparse if __name__ == "__main__": """ Use argparse to decide what to do """ # set up arg parsing parser = argparse.ArgumentParser( description='render and rearrange files ' \ ...
normal
{ "blob_id": "348676e43e4dfbbe7cd0c0527acb8c613d3d1ebc", "index": 6301, "step-1": "#!/usr/bin/env python\nimport sys\nfrom static_pipeline import render\nfrom static_pipeline.lib import argparse\n\nif __name__ == \"__main__\":\n \"\"\" Use argparse to decide what to do\n \"\"\"\n # set up arg parsing\n ...
[ 0 ]
def largestVar(s: str): freq = {i:0 for i in range(26)} for i in range(len(s)): freq[(int) (chr(i) - 'a')] += 1 max_var = 0 for a in range(26): for b in range(26): left_a = freq[a] left_b = freq[b]
normal
{ "blob_id": "4bd2923381cd3ead9a5605363a86f41b3743bf27", "index": 7223, "step-1": "<mask token>\n", "step-2": "def largestVar(s: str):\n freq = {i: (0) for i in range(26)}\n for i in range(len(s)):\n freq[int(chr(i) - 'a')] += 1\n max_var = 0\n for a in range(26):\n for b in range(26):...
[ 0, 1, 2 ]
#Displaying multiple images using matplotlib import pandas as pd import numpy as np import cv2 import matplotlib.pyplot as plt def main(): imgpath1="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png" imgpath2="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png" img1=cv2.imread(imgpath1,1) img2=cv2.imread(imgpath2,...
normal
{ "blob_id": "2867a7b24b4911b2936cb34653fa57431c14d6a3", "index": 7319, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n imgpath1 = 'C:\\\\Shreyas\\\\OpenCv\\\\DIP_OpenCV\\\\lena.png'\n imgpath2 = 'C:\\\\Shreyas\\\\OpenCv\\\\DIP_OpenCV\\\\lena.png'\n img1 = cv2.imread(imgpath1, 1)...
[ 0, 1, 2, 3, 4 ]
""" This is a big integer challenge. You are given an integer which is a **perfect square**. It is composed of 40 or more digits. Compose a function which will find the exact square root of this integer. ### Examples square_root(152415787532388367501905199875019052100) ➞ 12345678901234567890 square_ro...
normal
{ "blob_id": "f9b53df799b3e6b71282c84a625ea5915ccb8014", "index": 1966, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef square_root(n):\n start = 1\n end = n\n if n == 0 or n == 1:\n return n\n while start <= end:\n mid = (start + end) // 2\n if mid * mid == n:\n ...
[ 0, 1, 2 ]
lista = [] z = 0 j = 9 for i in range(0, 10): lista.append(int(input())) while z < j: c = lista[z] lista[z] = lista[j] lista[j] = c z += 1 j -= 1 print(lista)
normal
{ "blob_id": "01ede703e36268dc9b3331b21726c24674a43817", "index": 1338, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(0, 10):\n lista.append(int(input()))\nwhile z < j:\n c = lista[z]\n lista[z] = lista[j]\n lista[j] = c\n z += 1\n j -= 1\nprint(lista)\n", "step-3": "li...
[ 0, 1, 2 ]
from base_page import Base_Page import locators class Product_Object: "Page Object for the table" #locators def get_all_text(self): "Get the text within the table" table_text = [] row_doms = self.get_elements(self.rows_xpath) for index,row_dom in enumerate(row_doms): ...
normal
{ "blob_id": "aebc8665a97ab0a71b1d8a920b5cbf2643254883", "index": 479, "step-1": "<mask token>\n\n\nclass Product_Object:\n <mask token>\n\n def get_all_text(self):\n \"\"\"Get the text within the table\"\"\"\n table_text = []\n row_doms = self.get_elements(self.rows_xpath)\n for...
[ 4, 6, 8, 11, 12 ]
from setuptools import setup import imp def get_version(): ver_file = None try: ver_file, pathname, description = imp.find_module('__version__', ['cmakelint']) vermod = imp.load_module('__version__', ver_file, pathname, description) version = vermod.VERSION return version ...
normal
{ "blob_id": "b3d9013ab6facb8dd9361e2a0715a8ed0cdfeaba", "index": 342, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_version():\n ver_file = None\n try:\n ver_file, pathname, description = imp.find_module('__version__', [\n 'cmakelint'])\n vermod = imp.load_modu...
[ 0, 1, 2, 3, 4 ]
import urllib.request import json import dml, prov.model import datetime, uuid import geojson # import csv """ Skelton file provided by lapets@bu.edu Heavily modified by bmroach@bu.edu City of Boston Open Spaces (Like parks, etc) Development notes: """ class retrieve_open_space(dml.Algorithm): contributor = '...
normal
{ "blob_id": "2c82dd33180a7442607e5cbedf8846bd72b37150", "index": 9914, "step-1": "<mask token>\n\n\nclass retrieve_open_space(dml.Algorithm):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non...
[ 2, 3, 4, 5, 6 ]
from sklearn.base import BaseEstimator class movingAverage(BaseEstimator): '''Implements a moving average.''' def __init__(self, lag): self.lag = lag def movingAverage(self, periods=5): '''Implements a naiveLV forecast.''' try: # sets data x = self.data['Values'] d = ...
normal
{ "blob_id": "f4e45c19105d4ee1520acc0cd61dadfe27904d0f", "index": 8134, "step-1": "from sklearn.base import BaseEstimator\n\n\nclass movingAverage(BaseEstimator):\n '''Implements a moving average.'''\n\n def __init__(self, lag):\n self.lag = lag\n\ndef movingAverage(self, periods=5):\n '''Implemen...
[ 0 ]
#!/usr/local/bin/python3 from sys import stdin import argparse # Default values alignment = 'l' border = 'none' stretch_factor = '1.0' toprule = '' # Default options custom_header = False standalone = False stretch = False booktabs = False # Parsing command-line options parser = argparse.ArgumentParser('<stdin> | cs...
normal
{ "blob_id": "591ac07e735e08bcafa8274eb1a1547a01261f55", "index": 8430, "step-1": "<mask token>\n\n\ndef rule(type):\n if booktabs:\n if type == 'top':\n return '\\\\toprule'\n if type == 'mid':\n return '\\\\midrule'\n if type == 'bottom':\n return '\\\\bo...
[ 2, 3, 4, 5, 6 ]
# Copyright 2013 Rackspace Hosting Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
normal
{ "blob_id": "cf931da4c06e16fe6f6da5eb1826d8b7a59c1f7b", "index": 9057, "step-1": "<mask token>\n\n\nclass TestQuarkUpdateIpPolicies(test_quark_plugin.TestQuarkPlugin):\n\n @contextlib.contextmanager\n def _stubs(self, ip_policy, subnets=None, networks=None):\n if not subnets:\n subnets = ...
[ 37, 43, 48, 57, 67 ]
# encoding: utf-8 """ File: demo.py Author: Rock Johnson Description: 此文件为案例文件 """ import sys sys.path.append('../') try: from panicbuying.panic import Panic except: from panicbuying.panicbuying.panic import Panic def main(): ''' 公共参数: store: 商城或书店名称(小米|文泉), browser: 浏览器(目前只支持Chrome), versio...
normal
{ "blob_id": "2f8dff78f5bc5ed18df97e2574b47f0a7711d372", "index": 547, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n \"\"\"\n 公共参数:\n store: 商城或书店名称(小米|文泉), browser: 浏览器(目前只支持Chrome),\n version: 浏览器版本号, quit: 运行完后是否退出浏览器(默认不退出),\n hidden: 是否启用界面(默认启用),\n\n 商城抢购:\n u...
[ 0, 1, 2, 3, 4 ]
# 使用celery from django.conf import settings from django.core.mail import send_mail from django.template import loader,RequestContext from celery import Celery import time # 在任务处理者一 # # 端加的代码 import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh.settings") django.setup() from goods.models ...
normal
{ "blob_id": "7f7d087b7001cd7df01d4f22e056809be5a35568", "index": 9584, "step-1": "<mask token>\n\n\n@app.task\ndef generate_static_index_html():\n \"\"\"产生首页静态页面\"\"\"\n types = GoodsType.objects.all()\n goods_banners = IndexGoodsBanner.objects.all().order_by('index')\n promotion_banners = IndexPromo...
[ 1, 2, 4, 5, 6 ]
''' Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] ''' #卡了很久,还是列表的基本操作不太熟 #参考:https://zhidao.baidu.com/question/1244520812319200859.html def r...
normal
{ "blob_id": "b7ebee3c96fd9cd3d8ddc69838363925085a944d", "index": 1347, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef rotate_left3(nums):\n if len(nums) < 3:\n return 0\n nums.append(nums[0])\n del nums[0]\n return nums\n", "step-3": "'''\nGiven an array of ints length 3, ret...
[ 0, 1, 2 ]
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'AND BREAK CHAR COLON COMA CTE_F CTE_I CTE_STRING DETERMINANT DIFFERENT DIVIDE DO DOUBLEEQUAL ELSE EQUAL FLOAT FROM FUNCTION ID IF INPUT INT INVERSA LBRACE LCORCH LOWERE...
normal
{ "blob_id": "160f272edd8283ea561552f22c71967db4a1660a", "index": 7983, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _k, _v in _lr_action_items.items():\n for _x, _y in zip(_v[0], _v[1]):\n if not _x in _lr_action:\n _lr_action[_x] = {}\n _lr_action[_x][_k] = _y\ndel _lr_...
[ 0, 1, 2, 3 ]
class Odwroc(): def __init__(self,dane): self.dane = dane self.indeks = len(dane) def __iter__(self): return self def __next__(self): if self.indeks == 0: raise StopIteration self.indeks -= 1 return self.dane[self.indeks] for i in Odwroc('Martu...
normal
{ "blob_id": "763c0baf919b48ff135f7aa18974da5b85ee40f5", "index": 1133, "step-1": "class Odwroc:\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "class Odwroc:\n\n def __init__(self, dane):\n self.dane = dane\n self.indeks = len(dane)\n <mask token>\n\n ...
[ 1, 3, 4, 5, 6 ]
""" This is the main script """ import datetime import sqlite3 from sqlite3 import Error import nltk.sentiment from chatterbot import ChatBot from pythonosc import udp_client def _create_connection(db_file): """ Create a database connection to the SQLite database """ try: conn = sqlite3.connect(db_fi...
normal
{ "blob_id": "2b8b5b893d61d11d2795f5be96fde759256a15e8", "index": 9741, "step-1": "<mask token>\n\n\ndef _create_connection(db_file):\n \"\"\" Create a database connection to the SQLite database \"\"\"\n try:\n conn = sqlite3.connect(db_file)\n cur = conn.cursor()\n cur.execute('CREATE ...
[ 2, 3, 4, 5, 6 ]
"""Unit tests for the `esmvalcore.preprocessor._rolling_window` function.""" import unittest import iris.coords import iris.exceptions import numpy as np from cf_units import Unit from iris.cube import Cube from numpy.testing import assert_equal from esmvalcore.preprocessor._rolling_window import rolling_window_stati...
normal
{ "blob_id": "9539d2a4da87af1ff90b83bbcf72dfc8ab7b6db0", "index": 5501, "step-1": "<mask token>\n\n\nclass TestRollingWindow(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Te...
[ 1, 7, 8, 9, 11 ]
# DO NOT EDIT THIS FILE! # # Python module managedElementManager generated by omniidl import omniORB omniORB.updateModule("managedElementManager") # ** 1. Stub files contributing to this module import managedElementManager_idl # ** 2. Sub-modules # ** 3. End
normal
{ "blob_id": "7727896d4e1b2b415c398b206f9fb7e228e6f26d", "index": 8602, "step-1": "<mask token>\n", "step-2": "<mask token>\nomniORB.updateModule('managedElementManager')\n<mask token>\n", "step-3": "import omniORB\nomniORB.updateModule('managedElementManager')\nimport managedElementManager_idl\n", "step-4"...
[ 0, 1, 2, 3 ]
# coding=utf-8 """ author = jamon """
normal
{ "blob_id": "00790b9d2648d19a37d1d1864e7fdeab0f59f764", "index": 4266, "step-1": "<mask token>\n", "step-2": "# coding=utf-8\n\"\"\"\nauthor = jamon\n\"\"\"", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
from enum import Enum from roll.input import Input from roll.network import Server, Client from assets.game_projects.fighter.src.game_properties import GameProperties from assets.game_projects.fighter.src.network_message import NetworkMessage class InputBuffer: """ Responsible for collecting game input from...
normal
{ "blob_id": "4789546128263bd298f8f5827734f8402747b9ac", "index": 67, "step-1": "<mask token>\n\n\nclass OutgoingNetworkInputBuffer(InputBuffer):\n <mask token>\n <mask token>\n\n\nclass IncomingNetworkInputBuffer(InputBuffer):\n\n def __init__(self, frame_limit=12):\n super().__init__(left_action...
[ 5, 12, 13, 15, 21 ]
from django.shortcuts import * from shop.models import * from django.db import transaction from django.core.exceptions import * @transaction.atomic def computers(request): ctx = {} computer = Computer.objects.all() ctx['brand'] = Brand.objects.all() if request.method == 'POST': if request.POST['computer_i...
normal
{ "blob_id": "18689741a33e6d17e694ee0619a1f36d8d178cbb", "index": 3223, "step-1": "<mask token>\n\n\n@transaction.atomic\ndef computers(request):\n ctx = {}\n computer = Computer.objects.all()\n ctx['brand'] = Brand.objects.all()\n if request.method == 'POST':\n if request.POST['computer_id'] !...
[ 1, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- """ Created on Sat Oct 20 07:48:47 2018 @author: hfuji """ import os from PIL import Image import glob import shutil src_jpg_dir = 'D:/Develop/data/VOCdevkit/VOC2007/JPEGImages/' dst_bmp_dir = 'D:/Temp/' jpg_files = glob.glob(src_jpg_dir + '*.jpg') cnt = 0 for jpg_file in ...
normal
{ "blob_id": "a57059927a7bd3311c1d104bfc80877912c7d995", "index": 125, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor jpg_file in jpg_files:\n basename = os.path.basename(jpg_file)\n if int(basename[:-4]) % 10 == 0:\n cnt += 1\n dirname = os.path.dirname(jpg_file)\n dirs = d...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python3 """1. Divide a matrix """ def matrix_divided(matrix, div): """Divides a Matrix Args: matrix: A list of lists of ints or floats div: a non zero int or float Exceptions: TypeError: if the matrix and/or div is not as stated or the matrix elements are not of the...
normal
{ "blob_id": "95c5971a102fb2ed84ab0de0471278d0167d8359", "index": 22, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef matrix_divided(matrix, div):\n \"\"\"Divides a Matrix\n\n Args:\n matrix: A list of lists of ints or floats\n div: a non zero int or float\n\n Exceptions:\n TypeEr...
[ 0, 1, 2 ]
# Generated by Django 3.2.3 on 2021-06-19 11:27 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BillDetail', ...
normal
{ "blob_id": "b7a8e4105f1c1c532eaae27afae14e9a4f2ddfba", "index": 2915, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
import os import shutil def flatCopyWithExt(srcDir, dstDir, ext): if not os.path.exists(dstDir): os.makedirs(dstDir) for basename in os.listdir(srcDir): if basename.endswith(ext): pathname = os.path.join(srcDir, basename) if os.path.isfile(pathname): shutil.copy2(pathname, dstDir) def move...
normal
{ "blob_id": "649c0c0f170b50fe51f5eaf11908e968f66625c9", "index": 5925, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef moveSDLIncludes():\n flatCopyWithExt('./ext/SDL2/core/code/include/',\n './ext/SDL2/core/include/', '.h')\n flatCopyWithExt('./ext/SDL2/SDL2-image/code/',\n '....
[ 0, 1, 2, 3, 4 ]
import torch import torch.nn as nn import torch.optim as optim import torchtext import absl.flags import absl.app import pickle import yaml import numpy as np from tqdm import tqdm from core import model import core.dnc.explanation from core import functions from core.config import ControllerConfig, MemoryConfig, Train...
normal
{ "blob_id": "00dbcae2d3941c9ef4c8b6753b8f6f7a46417400", "index": 5110, "step-1": "<mask token>\n\n\ndef run_explanations(network, explanation_module, data_iterator):\n network.eval()\n best_accuracy = 0\n worst_accuracy = 0\n best_correct = 0\n worst_correct = 0\n covered = 0\n total = 0\n ...
[ 3, 5, 6, 7, 9 ]
# -*- coding: utf-8 -*- # Project = https://github.com/super-l/search-url.git # Author = superl # Blog = www.superl.org QQ:86717375 # Team = Code Security Team(C.S.T) | 铭剑创鼎 import urllib2 import re import ConfigParser from lib.filter import * from lib.getdata import * from lib.count import * from lib.status...
normal
{ "blob_id": "b724b04c6303cc9021539ad7df5a198000491029", "index": 5436, "step-1": "<mask token>\n\n\nclass Baidu:\n <mask token>\n <mask token>\n\n def __init__(self, count):\n cfg = ConfigParser.ConfigParser()\n cfg.read('config/setting.conf')\n self.baidu_page_size = int(cfg.get('s...
[ 2, 3, 4, 5, 6 ]
# B. A New Technique # TLE (Time limit exceeded) from sys import stdin, stdout t = int(input()) for _ in range(t): n, m = map(int, input().split()) rows = [0] * n a_column = list() for r in range(n): tmp = list(input().split()) rows[r] = tmp a_column.append(tmp[0]) sorte...
normal
{ "blob_id": "9004314951f77b14bab1aba9ae93eb49c8197a8d", "index": 4409, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _ in range(t):\n n, m = map(int, input().split())\n rows = [0] * n\n a_column = list()\n for r in range(n):\n tmp = list(input().split())\n rows[r] = tmp\n ...
[ 0, 1, 2, 3, 4 ]
from cache_replacement.double_linked_list import DoubleLinkedList from cache_replacement.node import Node class LRUCache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.cache_map = {} self.cache_list = DoubleLinkedList(capacity=capacity) def get(sel...
normal
{ "blob_id": "898ff6e38e80419d61ec4bbde827e8ca729eb19a", "index": 5202, "step-1": "<mask token>\n\n\nclass LRUCache:\n <mask token>\n <mask token>\n\n def put(self, key, value):\n if key in self.cache_map:\n old_node = self.cache_map.get(key)\n self.cache_list.remove(old_node...
[ 2, 3, 4, 5 ]
# Generated by Django 3.2.4 on 2021-06-16 13:41 import ckeditor.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('FAQ', '0004_auto_20210616_1253'), ] operations = [ migrations.RemoveField( model_name='question', nam...
normal
{ "blob_id": "a4c4a5cc63c345d1fa8cbf426f7857a0f3d4357f", "index": 8360, "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 = [('FAQ', '0004...
[ 0, 1, 2, 3, 4 ]
from pyrogram import Client, filters from pyrogram.errors import MessageNotModified from db.models import * @Client.on_callback_query(filters.regex('^change_lg_')) async def on_change_language(_, callback): settings_id = int(callback.data.split('_')[2]) with db_session: settings = SettingsInstance.g...
normal
{ "blob_id": "dd053da45d2577772414b1373ba324b0bfdc0d94", "index": 6605, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@Client.on_callback_query(filters.regex('^change_lg_'))\nasync def on_change_language(_, callback):\n settings_id = int(callback.data.split('_')[2])\n with db_session:\n ...
[ 0, 1, 2, 3 ]
from function import * from .propogation import optimize from .initialize import initialize_with_zeros def predict(weight, intercept, x_vector): """ Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px ...
normal
{ "blob_id": "63360ec9693a916375b49d0881008b1d7d4ec953", "index": 4546, "step-1": "<mask token>\n\n\nclass Logistic(object):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initializing the model parameter\n :param args:\n :param kwargs:\n X_train,\n...
[ 3, 4, 5, 6, 7 ]
#Script to retrieve relevant files and paths, supply to cx_Freeze to compile into executeable import os # import cx_Freeze files_list = [] dir_path = os.path.dirname(os.path.realpath(__file__))+str('/') print(dir_path) for root, directories, filenames in os.walk(str(dir_path)): for file in filenames: pat...
normal
{ "blob_id": "430dccf1001af43c2a713b08dc05d8f04818aa1f", "index": 5597, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(dir_path)\nfor root, directories, filenames in os.walk(str(dir_path)):\n for file in filenames:\n path = os.path.join(root, file)\n if path.find('/.') == -1 and pat...
[ 0, 1, 2, 3, 4 ]
import pickle from generation_code import serial_filename import serial_output_code import numpy as np from shutil import copyfile from os import remove # This file is only temporary, mostly to be used when updating the # reference output from a regression test, to ensure that, in all # aspects that are in common with...
normal
{ "blob_id": "6acb253189798c22d47feb3d61ac68a1851d22ba", "index": 1619, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n copyfile(serial_filename(), temp_filename)\n serial_output_code.serial_output_code()\n with open(serial_filename(), 'rb') as f:\n qmc_out = pickle.load(f)\n with...
[ 0, 1, 2, 3, 4 ]
# importing libraries import cv2 import numpy as np import argparse aq = argparse.ArgumentParser() aq.add_argument('-i', '--input', required=True, help="input image path") aq.add_argument('-o', '--output', help="path where you want to download the image") args = vars(aq.parse_args()) # reading image img = cv2....
normal
{ "blob_id": "10cefb1cf2392fdcd368f11d0d69774a9ffa73ec", "index": 2816, "step-1": "<mask token>\n", "step-2": "<mask token>\naq.add_argument('-i', '--input', required=True, help='input image path')\naq.add_argument('-o', '--output', help=\n 'path where you want to download the image')\n<mask token>\nif args[...
[ 0, 1, 2, 3, 4 ]
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit from django import forms from django.forms import RadioSelect from django.urls import reverse from core.models import Person, Datapackage from core.utils import cancel_button ...
normal
{ "blob_id": "5a59108084d943f6faa07ffea1467dc19c3dd790", "index": 1101, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass DatapackageModelForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n se...
[ 0, 2, 3, 5, 6 ]
import requests import logging import json class Handler(object): def __init__(self): """ This class is used to handle interaction towards coffee interface. """ super(Handler, self).__init__() logging.warning('Initializing coffeeHandler....') # get an active token ...
normal
{ "blob_id": "00228facd19c72bebd9afbbe52597e390233d41e", "index": 5822, "step-1": "<mask token>\n\n\nclass Handler(object):\n <mask token>\n\n def get_rsp_from_url(self, url, params=None, method='get', data=None):\n logging.warning(\n 'when using method {}, header is:\\n {} \\n data is: \\...
[ 4, 6, 8, 9, 10 ]
import tensorflow as tf import numpy as np import tensorflow_datasets as tfds print(tf.__version__) imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True) train_data = imdb['train'] test_data = imdb['test'] # 25000 in each set training_sentences = [] training_labels = [] testing_sentences = [] ...
normal
{ "blob_id": "921c45af3ba34a1b12657bf4189fc8dd66fa44a6", "index": 3860, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(tf.__version__)\n<mask token>\nfor s, l in train_data:\n training_sentences.append(str(s.numpy()))\n training_labels.append(l.numpy())\nfor s, l in test_data:\n testing_sen...
[ 0, 1, 2, 3, 4 ]
from .dataset_readers import * from .models import *
normal
{ "blob_id": "bc8bf06f1adedeb7b364308591bff09ac42d6c29", "index": 3702, "step-1": "<mask token>\n", "step-2": "from .dataset_readers import *\nfrom .models import *\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import math def solve(): a = int(input()) b = int(input()) return math.sqrt(a * a + b * b) print(solve())
normal
{ "blob_id": "a22d38f7e8122d6339d1beab3bf08fa41c36d61d", "index": 9648, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef solve():\n a = int(input())\n b = int(input())\n return math.sqrt(a * a + b * b)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef solve():\n a = int(input())\n...
[ 0, 1, 2, 3 ]
import numpy as np import cv2 print("read imafe from file" ) img = cv2.imread("panda.jpg") print("create a window holder for the image") cv2.namedWindow("Image",cv2.WINDOW_NORMAL) print ('display the image ') cv2.imshow("Image",img) print ('press a key inside the image to make a copy') cv2.waitKey(0)
normal
{ "blob_id": "7cf6a4b8057280b38572dd92693013724751c47f", "index": 9502, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('read imafe from file')\n<mask token>\nprint('create a window holder for the image')\ncv2.namedWindow('Image', cv2.WINDOW_NORMAL)\nprint('display the image ')\ncv2.imshow('Image', i...
[ 0, 1, 2, 3, 4 ]
# Author: Cristian Steib # # # -*- encoding: utf-8 -*- import pilasengine class consoleColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class BotonComando(): ''' ...
normal
{ "blob_id": "266b8958b761ee7266a8098aeaecb8b6c2a24a2a", "index": 1757, "step-1": "<mask token>\n\n\nclass BotonComando:\n <mask token>\n\n def __init__(self, *args, **kwargs):\n self.pilas = args[0] if len(args) and type(args[0]\n ) is pilasengine.Pilas else kwargs['pilas'] if kwargs.get(...
[ 10, 12, 13, 14, 19 ]