code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import torch.nn as nn class RNN_instruction_encoder(nn.Module): def __init__(self, vocab_size, word_vec_dim, hidden_size, n_layers, input_dropout_p=0, dropout_p=0, bidirectional=True, variable_lengths=True, word2vec=None, fix_embeddings=False, rnn_cell='lstm'): super(RNN_instructi...
normal
{ "blob_id": "16106250548ef60b475b009116cfeb7a25101637", "index": 7727, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass RNN_instruction_encoder(nn.Module):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass RNN_instruction_encoder(nn.Module):\n\n def __init__(self, vo...
[ 0, 1, 3, 4 ]
from tkinter import * from get_train_set import * from datetime import * counter = 0 week = int(datetime.today().isocalendar()[1]) def update(a, b): global counter if b == 'x': b = 0 a = week counter = 0 else: counter += b a += counter train_set = get_train_set(...
normal
{ "blob_id": "62fe29b0ac4dee8fec4908cf803dba9bd7e92fa5", "index": 4602, "step-1": "<mask token>\n\n\ndef update(a, b):\n global counter\n if b == 'x':\n b = 0\n a = week\n counter = 0\n else:\n counter += b\n a += counter\n train_set = get_train_set(a)\n txtLbl1.c...
[ 1, 2, 3, 4 ]
def printPar(): for i in range(len(par)): print "par[{0:d}] = {1:d}".format(i,par[i]) def printImpar(): for i in range(len(impar)): print "impar[{0:d}] = {1:d}".format(i,impar[i]) par = [] impar = [] for i in range(15): n= int(raw_input()) if n%2 == 0: if len(par)<4: ...
normal
{ "blob_id": "7e33475a6ab7ad0d1e9d7d00b8443329e265fe69", "index": 6793, "step-1": "def printPar():\n for i in range(len(par)):\n print \"par[{0:d}] = {1:d}\".format(i,par[i])\ndef printImpar():\n for i in range(len(impar)):\n print \"impar[{0:d}] = {1:d}\".format(i,impar[i])\npar = []\nimpar =...
[ 0 ]
'''4. Write a Python program to filter the positive numbers from a list.''' lst = [1, -3, 4, -56, 7, 3, -8, -5, 2, 4, 9] New_list = list(filter(lambda x: x > 0, lst)) print(New_list)
normal
{ "blob_id": "d61151859390ab1c907ac3753143312da434981e", "index": 2624, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(New_list)\n", "step-3": "<mask token>\nlst = [1, -3, 4, -56, 7, 3, -8, -5, 2, 4, 9]\nNew_list = list(filter(lambda x: x > 0, lst))\nprint(New_list)\n", "step-4": "'''4. Write a ...
[ 0, 1, 2, 3 ]
from wtforms import Form as BaseForm from wtforms.widgets import ListWidget class Form(BaseForm): def as_ul(self): widget = ListWidget() return widget(self)
normal
{ "blob_id": "5dffda8215b8cfdb2459ec6a9e02f10a352a6fd0", "index": 3173, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Form(BaseForm):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Form(BaseForm):\n\n def as_ul(self):\n widget = ListWidget()\n return widget(self)\n"...
[ 0, 1, 2, 3 ]
""" sed_thermal.py Author: Joshua Lande <joshualande@gmail.com> """ import numpy as np from scipy import integrate from . sed_integrate import logsimps from . sed_spectrum import Spectrum from . import sed_config from . import units as u class ThermalSpectrum(Spectrum): vectorized = True def __init__(s...
normal
{ "blob_id": "8560c0068eff894e5aa1d0788bd9e5ad05c14997", "index": 2262, "step-1": "<mask token>\n\n\nclass ThermalSpectrum(Spectrum):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def units_string():\n return '1/erg/cm^3'\n\n def integrate(self, units=...
[ 9, 12, 13, 14, 16 ]
""" Created on Dec 1, 2014 @author: Ira Fich """ import random from igfig.containers import WeightedList class Replacer(): """ A class that replaces itself with a subclass of itself when you instantiate it """ subclass_weight = 0 def __new__(cls, *args, **kwargs): subs = WeightedList(cls.__subclasses__(),...
normal
{ "blob_id": "3a878c91218dfbf23477ae5b7561e9eecfcd1350", "index": 5053, "step-1": "<mask token>\n\n\nclass Replacer:\n <mask token>\n <mask token>\n\n def __new__(cls, *args, **kwargs):\n subs = WeightedList(cls.__subclasses__(), [sub.subclass_weight for\n sub in cls.__subclasses__()])\...
[ 7, 10, 11, 13, 15 ]
x = 'From marquard@uct.ac.za' print(x[8]) x = 'From marquard@uct.ac.za' print(x[14:17]) greet = 'Hello Bob' xa = "aaa" print(greet.upper()) print(len('banana')*7) data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' pos = data.find('.') print(data[pos:pos+3]) stuff = dict() print(stuff.get('candy',-1...
normal
{ "blob_id": "e26f673dfae38148a56927ce82d5ea7ea2545e12", "index": 8540, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(x[8])\n<mask token>\nprint(x[14:17])\n<mask token>\nprint(greet.upper())\nprint(len('banana') * 7)\n<mask token>\nprint(data[pos:pos + 3])\n<mask token>\nprint(stuff.get('candy', -1...
[ 0, 1, 2, 3 ]
''' This module creates the models/tables in the database catalog using sqlalchemy ''' from catalog import db class Items(db.Model): ''' Model to store all the information about an item ''' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String) item = db.Column(db....
normal
{ "blob_id": "ad622ff2e1d9286246b2175694a9ae796f8d2557", "index": 7535, "step-1": "<mask token>\n\n\nclass Items(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, email, item, descrip...
[ 2, 5, 6, 7, 8 ]
from django.db import models # Create your models here. class AlertMailModel(models.Model): receipient_mail = models.EmailField() host_mail = models.EmailField() host_smtpaddress = models.CharField(max_length=25) mail_host_password = models.CharField(max_length=200) use_tls=models.BooleanField(defa...
normal
{ "blob_id": "2872c86294037b4585158e7ff6db414ba7ab90cc", "index": 1814, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass AlertMailModel(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclas...
[ 0, 1, 2, 3, 4 ]
# pylint: disable=missing-docstring,function-redefined import uuid from behave import given, then, when import requests from features.steps import utils from testsuite.oauth import authorize from testsuite import fhir ERROR_AUTHORIZATION_FAILED = 'Authorization failed.' ERROR_BAD_CONFORMANCE = 'Could not parse conf...
normal
{ "blob_id": "ef0c9f740f1ca0906aeb7a5c5e5d35baca189310", "index": 6128, "step-1": "<mask token>\n\n\n@given('I am logged in')\ndef step_impl(context):\n assert context.oauth is not None, ERROR_AUTHORIZATION_FAILED\n assert context.oauth.access_token is not None, ERROR_AUTHORIZATION_FAILED\n\n\n@given('I am ...
[ 9, 10, 12, 15, 17 ]
#!/usr/bin/env python import argparse import http.server import os class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): def log_message(*args, **kwargs): pass parser = argparse.ArgumentParser() parser.add_argument('port', action='store', # default=8000, type=int, ...
normal
{ "blob_id": "e839eba2514c29a8cfec462f8d5f56d1d5712c34", "index": 7413, "step-1": "<mask token>\n\n\nclass SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):\n\n def log_message(*args, **kwargs):\n pass\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass SimpleHTTPRequestHandler(http...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/python import argparse import os import subprocess import batch vmc_dir = os.environ['VMCWORKDIR'] macro = os.path.join(vmc_dir, 'macro/koala/daq_tasks/export_ems.C') exec_bin = os.path.join(vmc_dir,'build/bin/koa_execute') # arguments definitions parser = argparse.ArgumentParser() parser.add_argument("in...
normal
{ "blob_id": "58c7b405096a5fdc5eeacb5e5f314f2d1bb85af6", "index": 6229, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('infile', help='the file list to be processed')\nparser.add_argument('-d', '--directory', default='./', help=\n 'directory where files are located')\nparser.add_arg...
[ 0, 1, 2, 3, 4 ]
import msvcrt import random import os def clear(): ''' It clears the screen.''' os.system('cls') def InitMatrix(): ''' It initializes the matrix as a board game.''' m = [[0 for i in range(4)] for j in range(4)] for i in range(2): x = random.randint(0, 3) y = random...
normal
{ "blob_id": "ab69f4d6afb96d86381bcf507d7810980446c6ea", "index": 6407, "step-1": "<mask token>\n\n\ndef MoveUp():\n \"\"\"It computes to the matrix upper side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the up key is pressed.\...
[ 3, 8, 10, 12, 13 ]
# Simulador de sistema M/M/1. # # Variables de respuesta: # - Demora promedio por cliente # - Número promedio de clientes en cola # - Utilización promedio de cliente # # Funciones: # arribo() # partida() # nuevoEvento() # medidasDesempeño() # generarTiempoExponencial(t) # generarHi...
normal
{ "blob_id": "62cc731982846f08b3f3caace5df1bfafd421869", "index": 1701, "step-1": "<mask token>\n\n\ndef arribo():\n global reloj\n global tiempoUltEvento\n global estadoServ\n global tiempoServicioTotal\n global areaQ\n global numCliEnCola\n global cola\n global tiempoLibre\n global co...
[ 6, 7, 8, 9, 10 ]
import numpy as np # Copyright 2011 University of Bonn # Author: Hannes Schulz def cnan(x): """ check for not-a-number in parameter x """ if np.isnan(x).sum()>0: import pdb pdb.set_trace() def get_curve_3D(eig, alpha=0.25,g23=0.5,g12=0.5): # renumerated according to sato et al: l3 is smallest...
normal
{ "blob_id": "2a19c2d6e51e9c123236c58f82de1a39e5db40f4", "index": 220, "step-1": "import numpy as np\n\n# Copyright 2011 University of Bonn\n# Author: Hannes Schulz\n\ndef cnan(x):\n \"\"\" check for not-a-number in parameter x \"\"\"\n if np.isnan(x).sum()>0:\n import pdb\n pdb.set_trace()\n\...
[ 0 ]
''' quarter = 0.25 dime = 0.10 nickel = 0.05 penny = 0.01 ''' #def poschg(dollar_amount,number):
normal
{ "blob_id": "0deec9058c6f7b77ba4fa3bfc0269c8596ce9612", "index": 1215, "step-1": "<mask token>\n", "step-2": "'''\nquarter = 0.25\ndime = 0.10\nnickel = 0.05\npenny = 0.01\n'''\n\n#def poschg(dollar_amount,number):\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label class total_land_value_if_in_plan_type_group_SS...
normal
{ "blob_id": "52bb10e19c7a5645ca3cf91705b9b0affe75f570", "index": 4764, "step-1": "<mask token>\n\n\nclass total_land_value_if_in_plan_type_group_SSS(Variable):\n <mask token>\n\n def __init__(self, group):\n self.group = group\n Variable.__init__(self)\n\n def dependencies(self):\n ...
[ 6, 7, 9, 10, 11 ]
# A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object # import connect # from connect import connect #create class import pymysql # import MySQLdb conn = pymysql.connect(host='127.0.0.1',user='root',password='',...
normal
{ "blob_id": "ea045d04b40341f34c780dceab1f21df93b7207a", "index": 7689, "step-1": "<mask token>\n\n\nclass User:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Customer(User):\n\n def __init__(self, name, email, age):\n self.name = name\n self.email = email\n self.age = a...
[ 4, 5, 8, 10, 11 ]
import numpy as np import matplotlib.pyplot as plt from sklearn import mixture, metrics import utils import spsa_clustering N = 5000 mix_prob = np.array([0.4, 0.4, 0.2]) clust_means = np.array([[0, 0], [2, 2], [-3, 6]]) clust_gammas = np.array([[[1, -0.7], [-0.7, 1]], np.eye(2), [[1, 0.8], [0.8, 1]]]) data_set = [] t...
normal
{ "blob_id": "5807d1c2318ffa19d237d77fbe3f4c1d51da8601", "index": 7634, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _ in range(N):\n mix_ind = np.random.choice(len(mix_prob), p=mix_prob)\n data_point = np.random.multivariate_normal(clust_means[mix_ind],\n clust_gammas[mix_ind])\n da...
[ 0, 1, 2, 3, 4 ]
""" app_dist_Tables00.py illustrates use of pitaxcalc-demo release 2.0.0 (India version). USAGE: python app_dist_Tables00.py """ import pandas as pd from taxcalc import * import numpy as np from babel.numbers import format_currency import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec ...
normal
{ "blob_id": "c3967ab15b8278d958fa5ff6ff48bbfb0b086238", "index": 3729, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor year in range(BASE_YEAR, END_YEAR + 1):\n filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'\n df1 = pd.read_fwf(filename1)\n df1.drop('Unnamed: 0', axis=1, inplace=T...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import os, time, sys fifoname = '/dev/pi-blaster' # must open same name def child( ): pipeout = os.open(fifoname, os.O_WRONLY) # open fifo pipe file as fd zzz = 0 while 1: time.sleep(zzz) os.write(pipeout, 'Spam %03d\n' % zzz) zzz = (z...
normal
{ "blob_id": "7502e28197cb40044303a0a2163546f42375aeb6", "index": 6119, "step-1": "#!/usr/bin/env python\nimport os, time, sys\nfifoname = '/dev/pi-blaster' # must open same name\n\ndef child( ):\n pipeout = os.open(fifoname, os.O_WRONLY) # open fifo pipe file as fd\n zzz = 0\n ...
[ 0 ]
from collections import Counter from docx import Document import docx2txt plain_text = docx2txt.process("kashmiri.docx") list_of_words = plain_text.split() #print(Counter(list_of_words)) counter_list_of_words = Counter(list_of_words) elements = counter_list_of_words.items() # for a, b in sorted(elements, key=lambda x:...
normal
{ "blob_id": "9ad36f157abae849a1550cb96e650746d57f491d", "index": 9732, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor word, frequency in sorted(elements, key=lambda x: x[1], reverse=True):\n cell = table.add_row().cells\n cell[0].text = str(word)\n cell[1].text = str(frequency)\ndoc.save('re...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import os import sys import numpy as np from sklearn.metrics import roc_curve, auc def confusion_matrix(Or, Tr, thres): tpos = np.sum((Or >= thres) * (Tr == 1)) tneg = np.sum((Or < thres) * (Tr == 0)) fpos = np.sum((Or >= thres) * (Tr == 0)) fneg = np.sum((Or < thres) * (Tr == 1...
normal
{ "blob_id": "4892d4f364b03b53b1ad6f4c2177bbe2898edbda", "index": 3691, "step-1": "<mask token>\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x...
[ 2, 4, 5, 6, 8 ]
#!/usr/bin/env python3 import sys all_neighbors_coord = [] for i in range(-1, 2): for j in range(-1, 2): for k in range(-1, 2): if i != 0 or j != 0 or k != 0: all_neighbors_coord.append((i, j, k)) def add_coord(c1, c2): return (c1[0] + c2[0], c1[1] + c2[1], c1[2] + c2[2]) ...
normal
{ "blob_id": "e7060658ae1838b0870b2a3adb61c9f8d78c93c7", "index": 3245, "step-1": "<mask token>\n\n\nclass life:\n\n def __init__(self, world):\n self.world = world\n\n def get_world_size(self):\n xs = [c[0] for c in self.world]\n ys = [c[1] for c in self.world]\n zs = [c[2] for ...
[ 10, 11, 12, 14, 16 ]
#!/usr/bin/env python def main(): import sys from pyramid.paster import get_appsettings from sqlalchemy import engine_from_config from pyvideohub.models import ScopedSession, Base config_file = sys.argv[1] settings = get_appsettings(config_file) engine = engine_from_config(settings, 's...
normal
{ "blob_id": "dbb66930edd70729e4df7d3023e83a6eae65cccd", "index": 1030, "step-1": "<mask token>\n", "step-2": "def main():\n import sys\n from pyramid.paster import get_appsettings\n from sqlalchemy import engine_from_config\n from pyvideohub.models import ScopedSession, Base\n config_file = sys....
[ 0, 1, 2, 3 ]
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from math import sqrt from sys import exit from subprocess import Popen, DEVNULL from resmon import LineSegment, reorder_step def write_head(file): with open("head.tex", "r") as head: for line in head: f.write(line) def writ...
normal
{ "blob_id": "5c0ee6e8a0d80dbb77a7a376c411b85bf1405272", "index": 1880, "step-1": "<mask token>\n\n\ndef write_head(file):\n with open('head.tex', 'r') as head:\n for line in head:\n f.write(line)\n\n\ndef write_foot(file):\n with open('foot.tex', 'r') as head:\n for line in head:\n...
[ 2, 3, 4, 5, 6 ]
# put your python code here time_one = abs(int(input())) time_two = abs(int(input())) time_three = abs(int(input())) time_four = abs(int(input())) time_five = abs(int(input())) time_six = abs(int(input())) HOUR = 3600 # 3600 seconds in an hour MINUTE = 60 # 60 seconds in a minute input_one = time_one * HOUR + time...
normal
{ "blob_id": "7a4044acaa191509c96e09dcd48e5b951ef7a711", "index": 3582, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(abs(input_one - input_two))\n", "step-3": "time_one = abs(int(input()))\ntime_two = abs(int(input()))\ntime_three = abs(int(input()))\ntime_four = abs(int(input()))\ntime_five = a...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # coding: utf-8 # HR Employee Retension Rate, predicting an employee likely to leave or not. # In[ ]: import numpy as np # 数组常用库 import pandas as pd # 读入csv常用库 from patsy import dmatrices # 可根据离散变量自动生成哑变量 from sklearn.linear_model import LogisticRegression # sk-learn库Logistic Regression模型 from skl...
normal
{ "blob_id": "a1bf4b941b845b43ec640b19a001e290b46c488c", "index": 7021, "step-1": "<mask token>\n", "step-2": "<mask token>\ndata\ndata.describe()\ndata.dtypes\npd.crosstab(data.salary, data.left)\npd.crosstab(data.salary, data.left).plot(kind='bar')\nplt.show()\n<mask token>\nprint(q)\nprint(q.sum(1))\nprint(q...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 import datetime import time import board from busio import I2C import adafruit_bme680 # Create library object using our Bus I2C port i2c = I2C(board.SCL, board.SDA) bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False) # change this to match the location's pressure (hPa) at sea level b...
normal
{ "blob_id": "ae7fc034249b7dde6d6bca33e2e6c8f464284cfc", "index": 9718, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n file.write('\\ntimestamp: %s ' % st)\n print('\\ntimestamp: %s ' % st...
[ 0, 1, 2, 3, 4 ]
from functools import wraps from flask import request, abort # Apply Aspect Oriented Programming to server routes using roles # e.g. we want to specify the role, perhaps supplied # by the request or a jwt token, using a decorator # to abstract away the authorization # possible decorator implementation def roles_requ...
normal
{ "blob_id": "1adaca88cf41d4e4d3a55996022278102887be07", "index": 3707, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef roles_required(roles):\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(roles, 'required')\n print(args, kw...
[ 0, 1, 2, 3 ]
def most_frequent_char(lst): char_dict = {} for word in lst: for char in word: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 max_value = max(char_dict.values()) max_keys = [] for key, value in char_dict.items(): ...
normal
{ "blob_id": "be1ddaf5b4a7fb203fea62d061b06afb45d6867d", "index": 4690, "step-1": "<mask token>\n", "step-2": "def most_frequent_char(lst):\n char_dict = {}\n for word in lst:\n for char in word:\n if char in char_dict:\n char_dict[char] += 1\n else:\n ...
[ 0, 1 ]
import numpy as np import cv2 import myrustlib def detect_lines_hough(img): lines = cv2.HoughLinesP( cv2.bitwise_not(opening), rho = 1, theta = np.pi / 2, threshold=50, minLineLength=120, maxLineGap=10 ) return [line[0] for line in lines] # weird HoughLinesP ...
normal
{ "blob_id": "bb5bea4ea100950b59fb2b168b75dec349938aac", "index": 7195, "step-1": "<mask token>\n\n\ndef detect_lines_hough(img):\n lines = cv2.HoughLinesP(cv2.bitwise_not(opening), rho=1, theta=np.pi / \n 2, threshold=50, minLineLength=120, maxLineGap=10)\n return [line[0] for line in lines]\n\n\n<m...
[ 6, 7, 8, 9, 11 ]
''' THROW with or without parameters Which of the following is true about the THROW statement? Answer the question 50XP Possible Answers - The THROW statement without parameters should be placed within a CATCH block. - The THROW statement with parameters can only be placed within a CATCH block. - The...
normal
{ "blob_id": "75023c7600fcceda0dc225992e7c433291b1a190", "index": 7254, "step-1": "<mask token>\n", "step-2": "'''\nTHROW with or without parameters\n\n\nWhich of the following is true about the THROW statement?\n\nAnswer the question\n50XP\n\nPossible Answers\n\n - The THROW statement without parameters sho...
[ 0, 1 ]
from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '2018/6/1 hello python' @app.route('/news') def news(): return '内蒙古新闻资讯,请选择浏览' if __name__ == '__main__': manager.run()
normal
{ "blob_id": "f9d8280d765826b05bfa7989645e487431799f85", "index": 7809, "step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return '2018/6/1 hello python'\n\n\n@app.route('/news')\ndef news():\n return '内蒙古新闻资讯,请选择浏览'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/')\ndef index()...
[ 2, 3, 4, 5 ]
from unittest import TestCase, main class Solution: def productExceptSelf(self, nums): right, rs = 1, [1]*len(nums) for i in range(1,len(nums)): rs[i] = nums[i-1]*rs[i-1] for i in range(len(nums)-1, -1, -1): rs[i], right = rs[i]*right, right*nums[i] return rs class testsolution(Tes...
normal
{ "blob_id": "9e34fcec3af746af37cb68fd8617c706cc1066f6", "index": 1743, "step-1": "<mask token>\n\n\nclass testsolution(TestCase):\n\n def setUp(self):\n self.solution = Solution()\n self.inout = [([1, 2, 3, 4], [24, 12, 8, 6]), ([4, 5, 1, 8, 2], [80,\n 64, 320, 40, 160])]\n\n def t...
[ 3, 4, 5, 6, 8 ]
from pypack.Animal import Animal __author__ = 'igord' def nl(): print("\n") def main(): # print("Hello2") # animal = Animal(45) # animal.double_age() # print(animal.age) print("Start") msg = "ana i mujica" msg2 = msg.replace("a", "$") print(msg) print(msg2) ivana = "iva...
normal
{ "blob_id": "b0cdf75ff00d72ada75990dd850546414bc11125", "index": 1799, "step-1": "<mask token>\n\n\ndef nl():\n print('\\n')\n\n\ndef main():\n print('Start')\n msg = 'ana i mujica'\n msg2 = msg.replace('a', '$')\n print(msg)\n print(msg2)\n ivana = 'ivana'\n print(ivana * 2)\n fruit =...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python3 #coding=utf-8 """ dfsbuild.py 单Git仓库多Dockerfile构建工具,提高了构建效率 快速使用: chmod +x ./dfsbuild.py 只构建Git最近一次修改的Dockerfile ./dfsbuild.py -a auto -r registry.cn-shanghai.aliyuncs.com/userename 构建所有的Dockerfile ./dfsbuild.py -a all -r registry.cn-shanghai.aliyuncs.com/userename 构建特定的Dockerfile ./dfsbuil...
normal
{ "blob_id": "400f9b6fb0ab73a920e6b73373615b2f8d1103bb", "index": 2301, "step-1": "<mask token>\n\n\ndef walkDockerfiles(path, splitFirt=True):\n \"\"\" 遍历目录中的所有dockerfile\n \n Arguments:\n path {string} -- 目录路径\n \n Keyword Arguments:\n splitFirt {bool} -- 去除文件开头的path (default: {True...
[ 3, 8, 9, 10, 11 ]
import os from registration import Registration from login import Login def login(): """ redirect to login page""" login_page = Login() login_page.login_main_page() def registration(): """Register the new user""" registration_page = Registration() registration_page.registration_main_page() ...
normal
{ "blob_id": "8ebc11f4b9e28254ef40175b26744f2a5ab0c831", "index": 2930, "step-1": "import os\n\nfrom registration import Registration\nfrom login import Login\n\n\ndef login():\n \"\"\" redirect to login page\"\"\"\n login_page = Login()\n login_page.login_main_page()\n\n\ndef registration():\n \"\"\"...
[ 0 ]
#!/usr/bin/python # Copyright 2014 Google 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 a...
normal
{ "blob_id": "4989db28db0f823a54ff0942fbc40fc4640da38f", "index": 3224, "step-1": "<mask token>\n\n\nclass FlatbuffersConversionData(object):\n \"\"\"Holds data needed to convert a set of json files to flatbuffer binaries.\n\n Attributes:\n schema: The path to the flatbuffer schema file.\n input_files: ...
[ 15, 18, 20, 22, 25 ]
''' log.py version 1.0 - 18.03.2020 Logging fuer mehrere Szenarien ''' # Imports import datetime # Globale Variablen ERROR_FILE = "error.log" LOG_FILE = "application.log" def error(msg): __log_internal(ERROR_FILE, msg) def info(msg): __log_internal(LOG_FILE, msg) def __log_internal(filenam...
normal
{ "blob_id": "0475c6cab353f0d23a4c4b7f78c1b47ecc5f8d3b", "index": 4819, "step-1": "<mask token>\n\n\ndef error(msg):\n __log_internal(ERROR_FILE, msg)\n\n\ndef info(msg):\n __log_internal(LOG_FILE, msg)\n\n\ndef __log_internal(filename, msg):\n now = datetime.datetime.now()\n f = open(filename, 'a+')\...
[ 3, 4, 5, 6, 7 ]
#!/usr/bin/python3 """ @author : Chris Phibbs @created : Sunday Aug 30, 2020 14:05:56 AEST @file : q3 """ class Solution: def minDays(self, grid: List[List[int]]) -> int: # bfs - find 1, run bfs. Then loop through - if any other ones found then disconnected i, j = 0...
normal
{ "blob_id": "cddd5deba0ddc59a604d2926bdc687716e08f226", "index": 1557, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n <mask token>\n\n def checkLand(self, grid, x, y):\n print(f...
[ 1, 2, 3, 4, 5 ]
#(C)Inspire Search 2020/5/31 Coded by Tsubasa Kato (@_stingraze) #Last edited on 2020/6/1 11:36AM JST import sys import spacy import re #gets query from argv[1] text = sys.argv[1] nlp = spacy.load('en_core_web_sm') doc = nlp(text) ahref = "<a href=\"" ahref2 = "\"\>" #arrays for storing subject and object types sub...
normal
{ "blob_id": "ecc001394c1f3bba78559cba7eeb216dd3a942d8", "index": 4711, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor d in doc:\n word = d.text\n pos = d.pos_\n dep = d.dep_\n if re.search('subj', dep):\n word2 = (ahref + 'http://www.superai.online/solr/search.php?query=' +\n ...
[ 0, 1, 2, 3, 4 ]
from data_loaders.data_module import ChestDataModule from utils.visualisation import showInRow from models import get_model from transforms.finetuning import ChestTrainTransforms, ChestValTransforms from models.baseline import BaseLineClassifier from pytorch_lightning.loggers import WandbLogger from pytorch_lightnin...
normal
{ "blob_id": "05ca7bbc3285a9e37921c0e514a2e31b05abe051", "index": 6396, "step-1": "<mask token>\n", "step-2": "<mask token>\nseed_everything(12345)\n<mask token>\nif torch.cuda.is_available():\n classifier = classifier.cuda()\ntrainer.fit(classifier, dm)\n", "step-3": "<mask token>\nseed_everything(12345)\...
[ 0, 1, 2, 3, 4 ]
# -- !/python3.10 # Mikhail (myke) Kolodin, 2021 # 2021-10-21 2021-10-21 1.2 # retext.py # Заменить во входном тексте указанное слово на случайный вариант # из предложенного набора заменителей. # Параметры - в командной строке. import re, random, sys fin = 'retext-in.txt' fot = 'retext-out.txt' t1 = """ here we go...
normal
{ "blob_id": "d1a179acfda9e76a11f362671fafb50773e2b9d3", "index": 9405, "step-1": "<mask token>\n\n\ndef redo(text: str, aword: str, subs: list) ->str:\n \"\"\" заменятель \"\"\"\n return re.sub(f'(\\\\W){aword}(\\\\W)', '\\\\1' + random.choice(subs) + '\\\\2',\n ' ' + text + ' ').strip()\n\n\ndef te...
[ 3, 4, 5, 6, 7 ]
import cv2 import matplotlib.pyplot as plt import numpy as np ball = plt.imread('ball.png') albedo = plt.imread('ball_albedo.png') shading = cv2.cvtColor(plt.imread('ball_shading.png'), cv2.COLOR_GRAY2RGB) x,y,z = np.where(albedo != 0) print('Albedo:', albedo[x[0],y[0]]) print("Albedo in RGB space:", albedo[x[0],y[0]...
normal
{ "blob_id": "cc6f70e328b774972e272e9600274dfd9fca93ee", "index": 3073, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Albedo:', albedo[x[0], y[0]])\nprint('Albedo in RGB space:', albedo[x[0], y[0]] * 255)\n<mask token>\nplt.subplot(1, 2, 1)\nplt.imshow(ball)\nplt.subplot(1, 2, 2)\nplt.imshow(albed...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2015 RAPP # 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 app...
normal
{ "blob_id": "f4e287f5fce05e039c54f1108f6e73020b8d3d8f", "index": 9346, "step-1": "<mask token>\n\n\nclass AsyncHandler(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass AsyncHandler(object):\n <mask token>\n\n def __init__(self, future...
[ 1, 3, 4, 5, 6 ]
import sqlite3 import os #Search for a patient name #Every doctor enter a name, it will find the patinet name that is similar to the patient name #Once a match is found, the system will output a list of matched patient names. #Then, the doctor select the patient to continue def patientSelect(CONN, staff): c = CONN...
normal
{ "blob_id": "b3b4d27b60c71cbd979ad4887fa80408665ea1ac", "index": 2853, "step-1": "<mask token>\n\n\ndef patientSelect(CONN, staff):\n c = CONN.cursor()\n print('Search for Patient')\n select = input(\"Enter patient name(type 'exit' to leave): \")\n if select == 'exit':\n os.system('clear')\n ...
[ 7, 9, 11, 12, 13 ]
# Uses python3 import numpy as np def fibonaci(n): if n <= 1: return n F = np.empty(shape=(n + 1)) F[0] = 0 F[1] = 1 for i in range(2, len(F)): F[i] = F[i - 1] + F[i - 2] return F[n] n = int(input()) print(int(fibonaci(n)))
normal
{ "blob_id": "67516551b595c02e70a0ba4005df8a97ba71b17e", "index": 1419, "step-1": "<mask token>\n\n\ndef fibonaci(n):\n if n <= 1:\n return n\n F = np.empty(shape=n + 1)\n F[0] = 0\n F[1] = 1\n for i in range(2, len(F)):\n F[i] = F[i - 1] + F[i - 2]\n return F[n]\n\n\n<mask token>\...
[ 1, 2, 3, 4, 5 ]
""" 《Engineering a Compiler》 即《编译器设计第二版》 https://www.clear.rice.edu/comp412/ """ # 《parsing-techniques》 讲前端 ## http://parsing-techniques.duguying.net/ebook/2/1/3.html """ 前端看Parsing Techniques,后端看鲸书,都是最好的。 """ # 《essential of programming language》 # sicp """ 如果对编程语言设计方面感兴趣,想对编程语言和编译器设计有大概的概念,可以看看PLP。 想快速实践可以看《自制脚本语...
normal
{ "blob_id": "5663ded291405bcf0d410041485487bb17560223", "index": 3106, "step-1": "<mask token>\n", "step-2": "\n\"\"\"\n《Engineering a Compiler》\n即《编译器设计第二版》\nhttps://www.clear.rice.edu/comp412/\n\"\"\"\n# 《parsing-techniques》 讲前端\n## http://parsing-techniques.duguying.net/ebook/2/1/3.html\n\n\"\"\"\n前端看Parsin...
[ 0, 1 ]
''' sin(x) = x^1/1! - x^3/3! + x^5/5! - x^7/7! + ….. Input : x, n ( No. of terms I want in series ) Input : 3.14, 10 Output : sin(3.14) = sin(180) = 0 Radians vs Degrees ( 0, 30, 60, 90 ….) 2pi = 360 Pi = 180 Pseudo code : 1.Take input variables radians,num 2. sin = 0 3. Indices = 1 4. odd = 1 4...
normal
{ "blob_id": "a99426c0751885f17078e709fd523cf3a26f5286", "index": 5533, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef exponent(base, index):\n if index == 0 and base == 0:\n return -1\n elif index == 0:\n return 1\n elif base == 0:\n return 0\n else:\n prod...
[ 0, 2, 3, 4, 5 ]
#Exercise 5 #Define with names stair1, stair2, and stair3 (from bottom up to top), and insert within the building model, the 3 stair models of the building.
normal
{ "blob_id": "4c42bad4197b51be0e9d18307c7b954a29281fe1", "index": 3259, "step-1": "#Exercise 5\n#Define with names stair1, stair2, and stair3 (from bottom up to top), and insert within the building model, the 3 stair models of the building.", "step-2": null, "step-3": null, "step-4": null, "step-5": null,...
[ 1 ]
from socket import * from multiprocessing import Process import sys ADDR = ("127.0.0.1", 8888) udp_socket = socket(AF_INET, SOCK_DGRAM) # udp_socket.bind(("0.0.0.0",6955)) # udp套接字在一段时间不链接后,会自动重新分配端口,所以需要绑定 def login(): while True: name = input("请输入昵称(不能重复)") msg = "LOGIN" + "##" + name u...
normal
{ "blob_id": "fd6cf903490ff4352e4721282354a68437ecb1e0", "index": 8314, "step-1": "<mask token>\n\n\ndef login():\n while True:\n name = input('请输入昵称(不能重复)')\n msg = 'LOGIN' + '##' + name\n udp_socket.sendto(msg.encode(), ADDR)\n data, addr = udp_socket.recvfrom(1024)\n if da...
[ 4, 5, 7, 8, 9 ]
from .base import Sort
normal
{ "blob_id": "de3a96d46b7eaf198b33efe78b21ef0207dcc609", "index": 8424, "step-1": "<mask token>\n", "step-2": "from .base import Sort\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
""" Chess state handling model. """ from concurrent.futures import ThreadPoolExecutor from itertools import count from json import dumps from .base_board import BaseBoard, NoBoard from .table_board import TableBoard from .table_game import TableGame __all__ = ['Board', 'NoBoard'] class Board(BaseBoard): """ ...
normal
{ "blob_id": "796fada5dcd45ace8240760ac7e9bad41953ab56", "index": 9347, "step-1": "<mask token>\n\n\nclass Board(BaseBoard):\n <mask token>\n EMOJI = ['⌛', '‼', '♝', '♗', '♚', '♔', '♞', '♘', '♟', '♙', '♛', '♕',\n '♜', '♖', '▪', '▫']\n\n def __init__(self, board=None, _id=None, active_player=True):...
[ 8, 9, 10, 11, 12 ]
#!python3 import configparser parser = configparser.ConfigParser() parser.read("sim.conf") print(parser.get("config", "option1")) print(parser.get("config", "option2")) print(parser.get("config", "option3"))
normal
{ "blob_id": "cf5ab10ce743aa261867501e93f498022e5908fe", "index": 7360, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.read('sim.conf')\nprint(parser.get('config', 'option1'))\nprint(parser.get('config', 'option2'))\nprint(parser.get('config', 'option3'))\n", "step-3": "<mask token>\nparser = con...
[ 0, 1, 2, 3, 4 ]
# Generated by Django 3.0.4 on 2020-03-24 16:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('students', '0002_auto_20200324_1635'), ] operations = [ migrations.AddField( model_name='student', name='parent_mobi...
normal
{ "blob_id": "a372289d15b55f43887a37bb78a9fc308ddd0371", "index": 5582, "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 = [('students', ...
[ 0, 1, 2, 3, 4 ]
## ## Copyright (C) by Argonne National Laboratory ## See COPYRIGHT in top-level directory ## import re import os class G: pmi_vers = [] cmd_list = [] cmd_hash = {} class RE: m = None def match(pat, str, flags=0): RE.m = re.match(pat, str, flags) return RE.m def search(pat...
normal
{ "blob_id": "76382f353c47747ee730d83c2d3990049c4b0d98", "index": 6795, "step-1": "<mask token>\n\n\nclass G:\n pmi_vers = []\n cmd_list = []\n cmd_hash = {}\n\n\nclass RE:\n m = None\n\n def match(pat, str, flags=0):\n RE.m = re.match(pat, str, flags)\n return RE.m\n\n def search(...
[ 10, 13, 15, 18, 19 ]
from flask import Flask from sim.toggle import ToggleSensor from sim.sensor import Sensor app = Flask(__name__) sensors = [ ToggleSensor(id="s-01", description="lampadina"), ToggleSensor(id="s-02", description="lampadina"), ToggleSensor(id="s-03", description="allarme atomico"), ToggleSensor(id="s-04...
normal
{ "blob_id": "2843845848747c723d670cd3a5fcb7127153ac7e", "index": 264, "step-1": "<mask token>\n\n\n@app.route('/<sensor_id>', methods=['GET'])\ndef sensor_details(sensor_id):\n sensor_pos = search_index_by_id(sensor_id)\n if sensor_pos >= 0:\n return {'sensor': sensors[sensor_pos]}\n else:\n ...
[ 2, 3, 4, 6, 7 ]
# ToDo: """ 965. Univalued Binary Tree Easy A binary tree is univalued if every node in the tree has the same value. Return true if and only if the given tree is univalued. Note: The number of nodes in the given tree will be in the range [1, 100]. Each node's value will be an integer in the range [0, 99]. ...
normal
{ "blob_id": "7e9efb267a5464a6e53f81f63d82c28acba8bc8c", "index": 5543, "step-1": "# ToDo:\n\n\"\"\"\n965. Univalued Binary Tree\nEasy\n\nA binary tree is univalued if every node in the tree has the same value.\n\nReturn true if and only if the given tree is univalued.\n\nNote:\n\n The number of nodes in the g...
[ 0 ]
# ეს არის კოდი, რომელიც ქმნის აბსურდს import random def get_all_words(): words = [] # ეს არის ლისტი ყველა ისეთი სიტყვის with open("poem.txt") as poem: # რომლის ასოების სიმრავლეც 6-ზე ნაკლებია for line in poem: # გრძელ სიტყვებთან თამაში რთულ...
normal
{ "blob_id": "881d0c0808d8c0e656cdbf49450367553c100630", "index": 2100, "step-1": "<mask token>\n\n\ndef get_all_words():\n words = []\n with open('poem.txt') as poem:\n for line in poem:\n line = line.strip().split(' ')\n for word in line:\n if len(word) < 6:\n ...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-22 00:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('classroom', '0003_remove_anouncements_classroom'), ] ...
normal
{ "blob_id": "e9659555938211d067919ee5e0083efb29d42d7b", "index": 8600, "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 = [('classroom',...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python """Source base class. Based on the OpenSocial ActivityStreams REST API: http://opensocial-resources.googlecode.com/svn/spec/2.0.1/Social-API-Server.xml#ActivityStreams-Service """ __author__ = ['Ryan Barrett <activitystreams@ryanb.org>'] import datetime try: import json except ImportError: imp...
normal
{ "blob_id": "29428e9ca4373c9f19d1412046ebe4fc3b1c48e3", "index": 6300, "step-1": "<mask token>\n\n\nclass Source(object):\n <mask token>\n\n def __init__(self, handler):\n self.handler = handler\n\n def get_activities(self, user_id=None, group_id=None, app_id=None,\n activity_id=None, star...
[ 5, 6, 7, 8, 10 ]
class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ if(n % 4 != 0): return True; return False; """main(): sol = Solution(); sol.canWinNim(4); """
normal
{ "blob_id": "9a539fd3ce4e3ff75af82407150ab4b550b255c1", "index": 3284, "step-1": "class Solution(object):\n def canWinNim(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n\tif(n % 4 != 0):\n\t\treturn True;\n\treturn False;\n\"\"\"main():\n\tsol = Solution();\n\tsol.canWi...
[ 0 ]
from nbt import nbt from matplotlib import pyplot class Banana(object): id = 10 def srange(x1, xDoors, spaces): """ a counting thing that i dunno what does. """ for a in xrange(x1, x1 + xDoors): yield a for a in xrange(x1 + xDoors + spaces, x1 + spaces + xDoors * 2): yield a ...
normal
{ "blob_id": "4e9674ea46bdf930d1e99bcda56eaa300c84deef", "index": 7196, "step-1": "<mask token>\n\n\nclass Banana(object):\n id = 10\n\n\n<mask token>\n\n\ndef template_village_file(tick):\n \"\"\"\n Creates a template villages.dat file that i can modify later on\n \"\"\"\n cat = nbt.NBTFile()\n ...
[ 14, 15, 19, 21, 23 ]
from django.shortcuts import render from .models import Team,ContactForm from cars.models import Car from django.contrib import messages # Create your views here. def index(request): teams=Team.objects.all() cars = Car.objects.order_by("-created_date").filter(is_featured=True) all_cars=Car.objects.order_by(...
normal
{ "blob_id": "eca40c37e0e437a5f4e5643f5fb7cd3e38605471", "index": 2417, "step-1": "<mask token>\n\n\ndef about(request):\n teams = Team.objects.all()\n return render(request, 'pages/about.html', {'teams': teams})\n\n\n<mask token>\n\n\ndef contact(request):\n if request.method == 'POST':\n name = ...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- """The main application module for duffy.""" from flask import Flask from duffy import api_v1 from duffy.types import seamicro from duffy.extensions import db, migrate, marshmallow from duffy.config import ProdConfig,DevConfig def create_app(config_object=DevConfig): app = Flask(__name__...
normal
{ "blob_id": "11101273a02abec17fc884d5c1d5d182eb82ee0c", "index": 4625, "step-1": "<mask token>\n\n\ndef create_app(config_object=DevConfig):\n app = Flask(__name__.split('.')[0])\n app.config.from_object(config_object)\n app.config.from_envvar('DUFFY_SETTINGS', silent=True)\n register_extensions(app)...
[ 2, 3, 4, 5, 6 ]
# Problem 20: Factorial digit sum def factorial(num): sum = 1 while num != 0: sum *= num num -= 1 return sum def sum_digits(num): sum = 0 while num != 0: sum += num % 10 num //= 10 return sum print(sum_digits(factorial(100)))
normal
{ "blob_id": "cc6f02f9e1633fa15b97af5f926e083a65a8336e", "index": 5977, "step-1": "<mask token>\n", "step-2": "def factorial(num):\n sum = 1\n while num != 0:\n sum *= num\n num -= 1\n return sum\n\n\n<mask token>\n", "step-3": "def factorial(num):\n sum = 1\n while num != 0:\n ...
[ 0, 1, 2, 3, 4 ]
from .gsclient import GSClient from .gspath import GSPath __all__ = [ "GSClient", "GSPath", ]
normal
{ "blob_id": "7b726dd8ebbd5c49f9ce5bddb4779fcfbaaeb479", "index": 5651, "step-1": "<mask token>\n", "step-2": "<mask token>\n__all__ = ['GSClient', 'GSPath']\n", "step-3": "from .gsclient import GSClient\nfrom .gspath import GSPath\n__all__ = ['GSClient', 'GSPath']\n", "step-4": "from .gsclient import GSCli...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- """ Created on Fri Aug 21 12:39:59 2015 @author: user Needs to be run after the basic analysis which loads all the data into workspace """ import pandas as pd import numpy as np import matplotlib.pyplot as plt def AverageLeftRight(EyeData): #Take the average of two eyes to get more accurate gaz...
normal
{ "blob_id": "00ed68c68d51c5019fde0c489cd133be3d6985c3", "index": 9339, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef AverageLeftRight(EyeData):\n for eyes in EyeData:\n eyes['avg_x'] = (eyes['left_x'] + eyes['right_x']) / 2\n eyes['avg_y'] = (eyes['left_y'] + eyes['right_y']) / ...
[ 0, 1, 2, 3, 4 ]
import logging import os import textwrap from urllib.request import urlopen from bs4 import BeautifulSoup from tqdm import tqdm from doc_curation import book_data from doc_curation.md import get_md_with_pandoc from doc_curation.md.file import MdFile from doc_curation.scraping.misc_sites import iitk from doc_curation....
normal
{ "blob_id": "f3a63a22f8746d4a1f127bfe9e8c9d822109ab3c", "index": 463, "step-1": "<mask token>\n\n\ndef dump_all_sargas(base_dir):\n for kaanda_index in book_data.get_subunit_list(file_path=unit_info_file,\n unit_path_list=[]):\n if kaanda_index >= 6:\n continue\n sarga_list = b...
[ 3, 4, 6, 7, 8 ]
import abc import hashlib import hmac from typing import Any, Dict from urllib.parse import urlencode class IceCubedClientABC(abc.ABC): @abc.abstractproperty def _has_auth_details(self) -> bool: pass @abc.abstractmethod def sign(self, params: Dict[str, Any]) -> str: pass class IceCu...
normal
{ "blob_id": "8bd918896fb72c89a622ba4e18666bb90755cafd", "index": 4545, "step-1": "<mask token>\n\n\nclass IceCubedClientBase(IceCubedClientABC):\n BASE_URI = 'https://ice3x.com/api/v1/'\n\n def __init__(self, api_key: str=None, secret: str=None) ->None:\n \"\"\"Instantiate the client\n\n Args...
[ 5, 6, 7, 9, 10 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2020, Yutong Xie, UIUC. Using recursion to construct binary tree from postorder and inorder traversal ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val ...
normal
{ "blob_id": "b59dfd97a2b52ddef4e37557ea96bff9edf34989", "index": 1342, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Solution(object):\n\n def buildTree(self, inorder, postorder):\n \"\"\"\n :type ino...
[ 0, 1, 2, 3, 4 ]
# Given a stream of numbers, print average (or mean) of the stream at every point. def getAverage(prev_avg, val, n): return ((prev_avg * n) + val) / (n + 1) def findAndPrintMovingAvgs(arr): cur_avg = 0 for i in range(len(arr)): cur_avg = getAverage(cur_avg, arr[i], i) print "Avg at", i, "i...
normal
{ "blob_id": "3f4b484f435936137cb8511ec6e0aa89efb267c4", "index": 2480, "step-1": "# Given a stream of numbers, print average (or mean) of the stream at every point.\n\ndef getAverage(prev_avg, val, n):\n return ((prev_avg * n) + val) / (n + 1)\n\ndef findAndPrintMovingAvgs(arr):\n cur_avg = 0\n for i in...
[ 0 ]
from airbot import resolvers from airbot import utils import unittest from grapher import App import pprint OPENID_CONFIG = { 'ISSUER_URL': 'https://dev-545796.oktapreview.com', 'CLIENT_ID': '0oafvba1nlTwOqPN40h7', 'REDIRECT_URI': 'http://locahost/implicit/callback' } class TestEndToEnd(unittest.TestCas...
normal
{ "blob_id": "9725c4bfea1215e2fb81c31cbb8948fd1656aca9", "index": 3814, "step-1": "from airbot import resolvers\nfrom airbot import utils\nimport unittest\nfrom grapher import App\nimport pprint\n\n\nOPENID_CONFIG = {\n 'ISSUER_URL': 'https://dev-545796.oktapreview.com',\n 'CLIENT_ID': '0oafvba1nlTwOqPN40h7...
[ 0 ]
from rest_framework import serializers from plan.models import RoughRequirement, DetailedRequirement from plan.models import OfferingCourse, FieldOfStudy, IndicatorFactor from plan.models import BasisTemplate class SimpleOfferingCourseSerializer(serializers.ModelSerializer): class Meta: model = OfferingCou...
normal
{ "blob_id": "596f7dfacc931f5e756c71b8622f4001df19934b", "index": 5964, "step-1": "<mask token>\n\n\nclass RequirementSerializer(serializers.ModelSerializer):\n <mask token>\n\n\n class Meta:\n model = RoughRequirement\n fields = ['id', 'index', 'title', 'description',\n 'detailed_r...
[ 8, 11, 12, 13, 14 ]
from savers.saver import SaverInterface import os from config import SaverConfig import mysql.connector import json import logging class SQLSaver(SaverInterface): # This class takes in json files and will interpret the jsons as follows. # {'tablename':[{'columnname01':'somevalue','columnname02':'somevalue'},{'columnana...
normal
{ "blob_id": "e695b9458c0e98521e560dbb291f6f05bda1549f", "index": 421, "step-1": "<mask token>\n\n\nclass SQLSaver(SaverInterface):\n\n def connect(self):\n self.logging.info('Logging to %s@%s:%s -p %s', self.config.SQL_USER,\n self.config.SQL_HOST, self.config.SQL_DATABASE, self.config.\n ...
[ 10, 11, 12, 13, 16 ]
l={1,2,3,4} try: print(l) s=len(l) if s>5: raise TypeError print(d[2]) except TypeError: print("Error!!!length should be less than or equals to 5") except NameError: print("index out of range") else: for i in l: print(i) finally: print("execution done!!!!!!")
normal
{ "blob_id": "e59e60b0a4b7deca9c510bd6b9c58636c6d34c80", "index": 1027, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n print(l)\n s = len(l)\n if s > 5:\n raise TypeError\n print(d[2])\nexcept TypeError:\n print('Error!!!length should be less than or equals to 5')\nexcept Name...
[ 0, 1, 2, 3 ]
import io import socket import ssl from ..exceptions import ProxySchemeUnsupported from ..packages import six SSL_BLOCKSIZE = 16384 class SSLTransport: """ The SSLTransport wraps an existing socket and establishes an SSL connection. Contrary to Python's implementation of SSLSocket, it allows you to cha...
normal
{ "blob_id": "78d59e903fecd211aa975ae4c8dc01b17c8fad44", "index": 8471, "step-1": "<mask token>\n\n\nclass SSLTransport:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __exit__(self, *_):\n self.close()\n\n def fileno(self):\n return self.socket.fileno()\n\n ...
[ 19, 23, 27, 28, 30 ]
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os import pandas as pd print('tensorflow version: {}'.format(tf.__version__)) def __prepare_train_data(df, feature): group...
normal
{ "blob_id": "55030648a6b76636e456990c1d2b02baa35a695d", "index": 9221, "step-1": "<mask token>\n\n\ndef __prepare_train_data(df, feature):\n groups = df.groupby(['event', 'start'])\n data = []\n labels = []\n for id, group in groups:\n values = group['CylinderBorePressure'].values\n dat...
[ 2, 3, 4, 5, 6 ]
import os from subprocess import Popen, PIPE from Bio import SeqIO from Bio.Align.Applications import ClustalOmegaCommandline from Bio import Phylo from io import StringIO # from ete3 import Tree, TreeStyle import pylab class TreeDrawer: def __init__(self, sequences=None): self.sequences = sequences ...
normal
{ "blob_id": "5adb16c654a4e747f803590c42328fa6ba642e95", "index": 7599, "step-1": "<mask token>\n\n\nclass TreeDrawer:\n <mask token>\n <mask token>\n\n def draw_tree(self, filename):\n tree_file = open('dnaml.tree')\n x = tree_file.read()\n tree = Phylo.read(StringIO(x[:-2]), 'newic...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- from __future__ import absolute_import import sh import reqwire.helpers.cli log_methods = ( 'echo', 'error', 'fatal', 'info', 'warn', 'warning', ) def test_emojize_win32(mocker): mocker.patch('sys.platform', 'win32') assert reqwire.helpers.cli.emojize( ...
normal
{ "blob_id": "1a7a2c2cfb2aa94401defd7a7a500f7dd2e7e0aa", "index": 9680, "step-1": "<mask token>\n\n\ndef test_emojize_win32(mocker):\n mocker.patch('sys.platform', 'win32')\n assert reqwire.helpers.cli.emojize(':thumbs_up_sign: foo').encode('utf-8'\n ) == b'foo'\n\n\ndef test_emojize_linux(mocker):\n...
[ 7, 8, 9, 10, 11 ]
import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats XZ_MESH = np.meshgrid( np.linspace(0, 1, 100), np.linspace(0.5, 1, 100) ) XZ_GRID = np.append( XZ_MESH[0].reshape(-1, 1), XZ_MESH[1].reshape(-1, 1), 1 ) QI_MESH = np.meshgrid( np.linspace(0, 1, 100), np.linspace(0, 1, 100) ) Q...
normal
{ "blob_id": "05badb45c2249dc52b72a46779a8e619cd8a3ca9", "index": 7088, "step-1": "<mask token>\n\n\ndef get_pdf(kde, grid, resample=False, N=10000):\n if resample:\n x, y = kde.resample(N)\n kde = stats.kde.gaussian_kde(np.column_stack((x, y)).T)\n return kde(grid.T).reshape(100, 100)\n\n\nde...
[ 7, 9, 10, 11, 13 ]
#!/usr/bin/env python3 import subprocess import sys import pickle if len(sys.argv) != 3: print('Usage: std_dev_eval.py <std_dir> <ans>') quit() std_dir=sys.argv[1] std_ans=sys.argv[2] subprocess.call('rm -f {}/result'.format(std_dir), shell=True) op_f = open('{}/jobs'.format(std_dir), 'w') command = 'utils...
normal
{ "blob_id": "ba216642935d19b85e379b66fb514854ebcdedd9", "index": 666, "step-1": "<mask token>\n", "step-2": "<mask token>\nif len(sys.argv) != 3:\n print('Usage: std_dev_eval.py <std_dir> <ans>')\n quit()\n<mask token>\nsubprocess.call('rm -f {}/result'.format(std_dir), shell=True)\n<mask token>\nwith op...
[ 0, 1, 2, 3, 4 ]
import requests from bs4 import BeautifulSoup import urllib.request url = 'http://www.dytt8.net/' user = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } html = urllib.request.urlopen(url) html.encoding = 'utf-8' soup = Beauti...
normal
{ "blob_id": "2e571e3412bf9f3a42bf87976ea9a5ec68d5815c", "index": 9056, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in soup.find_all('a'):\n if 'href' in i.attrs:\n print(i.attrs['href'])\n", "step-3": "<mask token>\nurl = 'http://www.dytt8.net/'\nuser = {'User-Agent':\n 'Mozilla/5...
[ 0, 1, 2, 3 ]
# Copyright (c) 2023 Intel Corporation # 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 applicable law or agreed to in writ...
normal
{ "blob_id": "de88e2d2cf165b35f247ea89300c91b3c8c07fea", "index": 7844, "step-1": "<mask token>\n\n\nclass TemplateTestBCAlgorithm:\n\n @staticmethod\n @abstractmethod\n def list_to_backend_type(data: List) ->TTensor:\n \"\"\"\n Convert list to backend specific type\n\n :param data: ...
[ 9, 11, 12, 13, 14 ]
print("RUNNING ON CPU") from library import config, utils, broker_funcs, portfolio import numpy as np import pandas as pd # import matplotlib.pyplot as plt from fbm.fbmlib import fbm import time import pickle assert config.changePrice == True print(config.config) t0 = time.localtime() t0str = time.strftime("%H:%M:%S...
normal
{ "blob_id": "21aee78e8cbb1ca150bca880e79dc0d84326e2d4", "index": 4162, "step-1": "<mask token>\n", "step-2": "print('RUNNING ON CPU')\n<mask token>\nassert config.changePrice == True\nprint(config.config)\n<mask token>\nfor t in range(993, 4592):\n broker, totalOrders = broker_funcs.thresholdBrokerage(trade...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python import socket, os, datetime, time, re, sys import numpy as np import matplotlib.pyplot as plt from baseband import vdif import astropy.units as u from scipy.signal import resample_poly import matplotlib.patches as patches def fbcmd(message): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM...
normal
{ "blob_id": "8eb08fa497ccf3ddc8f4d2b886c9e5a9bdb2e052", "index": 8006, "step-1": "<mask token>\n\n\ndef fbcmd(message):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((ip, int(port)))\n sock.send(message.encode())\n if DEBUG:\n print('INFO: sent to ' + ip + ':' + por...
[ 4, 5, 6, 7, 8 ]
from tkinter import * from tkinter import messagebox root = Tk() def hello(): messagebox.showinfo("Say Hello", "Hello World") B1 = Button(root, text = "Say Hello", command = hello, font='arial 20') B1.pack() mainloop()
normal
{ "blob_id": "61e38ae6ae2a1ed061f9893742f45b3e44f19a68", "index": 6110, "step-1": "<mask token>\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\n<mask token>\nB1.pack()...
[ 1, 2, 3, 4, 5 ]
import os import time try: import cPickle as pickle except: import pickle #-------------# # Cache utils # #-------------# cachedir = os.path.expanduser('~/.cache/sherlock/') _cachedict = {} def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.e...
normal
{ "blob_id": "05cfd9d239b63c9b1e0c93a09e89cceb8d8e99e4", "index": 2462, "step-1": "<mask token>\n\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, file...
[ 7, 8, 9, 10, 12 ]
# encoding: utf-8 import paramiko import select import os import sys ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) host = "47.107.229.100" user = "root" pwd = "aliyun1996874353...A" class SSH: def __init__(self, host, user, pwd, port=22): self.host = host sel...
normal
{ "blob_id": "2342a651ec45623b887c4bc1168adb0731ba5ff6", "index": 8443, "step-1": "<mask token>\n\n\nclass SSH:\n <mask token>\n\n def exec_cmd(self, cmd):\n stdin, stdout, stderr = self.client.exec_command(cmd)\n res, err = stdout.read(), stderr.read()\n result = res if res else err\n ...
[ 5, 6, 8, 11, 12 ]
import pickle import time DECAY = 0.95 DEPTH = 2 def init_cache(g): ''' Initialize simrank cache for graph g ''' g.cache = {} def return_and_cache(g, element, val): ''' Code (and function name) is pretty self explainatory here ''' g.cache[element] = val return val def simrank_impl(g, node1, node2, t, is_wei...
normal
{ "blob_id": "535ee547475fbc2e1c0ee59e3e300beda1489d47", "index": 4215, "step-1": "import pickle\nimport time\nDECAY = 0.95\nDEPTH = 2\n\ndef init_cache(g):\n\t'''\n\tInitialize simrank cache for graph g\n\t'''\n\tg.cache = {}\n\ndef return_and_cache(g, element, val):\n\t'''\n\tCode (and function name) is pretty ...
[ 0 ]
import pandas as pd import notification def modify(nyt_url, jh_url): # read data from both sources into a dataframe # remove unwanted data, formats, and filters # join dataframes on index try: nyt_df = pd.read_csv(nyt_url, header=0, nam...
normal
{ "blob_id": "c60971b3b0649fce8c435813de4a738f4eacda27", "index": 4377, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef modify(nyt_url, jh_url):\n try:\n nyt_df = pd.read_csv(nyt_url, header=0, names=['Date', 'Cases',\n 'Deaths'], dtype={'Cases': 'Int64', 'Deaths': 'Int64'})\n ...
[ 0, 1, 2, 3 ]
from flask import Flask, render_template, send_from_directory from flask import request, send_file from flask_cors import CORS import os import json from crossdomain import crossdomain import constants import generation_tools from music_theory import name_chords_in_tracks import midi_tools from client_logging import Cl...
normal
{ "blob_id": "471cab65aac29f5b47de0ffef8f032dbbadf8dd0", "index": 1877, "step-1": "<mask token>\n\n\ndef add_logs_to_response(response):\n response['logs'] = ClientLogger.get_logs()\n ClientLogger.clear_logs()\n return response\n\n\n@app.route('/generate/melody', methods=['POST', 'OPTIONS'])\n@crossdomai...
[ 6, 8, 9, 11, 12 ]
#!python # -*- coding: utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * from window.window import * import sys app = QtGui.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
normal
{ "blob_id": "9e2af13a15a98702981e9ee369c3a132f61eac86", "index": 5174, "step-1": "<mask token>\n", "step-2": "<mask token>\nwindow.show()\nsys.exit(app.exec_())\n", "step-3": "<mask token>\napp = QtGui.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\nsys.exit(app.exec_())\n", "step-4": "from P...
[ 0, 1, 2, 3, 4 ]
import torch import typing __all__ = ['NoOp'] class Null(torch.optim.Optimizer): def __init__(self, parameters: typing.Iterator[torch.nn.Parameter], ): super(Null, self).__init__(parameters, {"lr": 0.0, "eps": 1e-8}) def step(self, closure=None): if closure is not None: closure() return N...
normal
{ "blob_id": "3c7237e5770dd5552c327dbf53451a2889ea8c6b", "index": 7198, "step-1": "<mask token>\n\n\nclass Null(torch.optim.Optimizer):\n <mask token>\n <mask token>\n\n\nclass NoOp(object):\n\n def __init__(self, parameters: typing.Iterator[torch.nn.Parameter]):\n self.optimizers = [Null(paramete...
[ 4, 6, 7, 8, 9 ]
# -*- coding:utf-8 -*- import re # 普通字符串 匹配本身 re_str = r'abc' result = re.fullmatch(re_str, 'abc') print(result) # 匹配任意字符 一个.只能匹配一个字符 re_str = r'a.c' result = re.fullmatch(re_str, 'abc') print(result) # \w匹配字母数字或下划线 # 匹配一个长度是5的字符串并且字符串的前两位是数字字母或者下划线后面是三个任意字符串 \w中文也能匹配 re_str = r'\w\w...' result = re.fullmatch(re_str, ...
normal
{ "blob_id": "e0e00688a75021c2f8b608d4c942f5e68f6a6a48", "index": 6282, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)\n<mask token>\nprint(result)...
[ 0, 1, 2, 3, 4 ]
import math import datetime as dt import cv2 import os from face import Face class Video: def __init__(self, vidSource, variableList=[], showWindow=True): self.vidcap = cv2.VideoCapture(vidSource) self.cascade = cv2.CascadeClassifier("face_cascade2.xml") self.visibleFaceList = [] # contains all Face objects wi...
normal
{ "blob_id": "7af0566161c909457d40d3856434f1fb1e800aab", "index": 1445, "step-1": "import math\nimport datetime as dt\nimport cv2\nimport os\nfrom face import Face\n\nclass Video:\n\tdef __init__(self, vidSource, variableList=[], showWindow=True):\n\t\tself.vidcap = cv2.VideoCapture(vidSource)\n\t\tself.cascade =...
[ 0 ]
import random s = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5} t = True while t: a = random.randint(1, 10) if a not in s: t = False s[a] = a print(s)
normal
{ "blob_id": "b9b113bdc5d06b8a7235333d3b3315b98a450e51", "index": 6562, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile t:\n a = random.randint(1, 10)\n if a not in s:\n t = False\n<mask token>\nprint(s)\n", "step-3": "<mask token>\ns = {(1): 1, (2): 2, (3): 3, (4): 4, (5): 5}\nt = Tru...
[ 0, 1, 2, 3, 4 ]
import numpy as np from scipy.stats import multivariate_normal from functions.io_data import read_data, write_data np.random.seed(0) class IsingModel(): def __init__(self, image, J, rate, sigma): self.width = image.shape[0] self.height = image.shape[1] self._J = J self._rate = rat...
normal
{ "blob_id": "6aa74826f9ca0803fa8c1d5af1d4cec4980e2ce6", "index": 9064, "step-1": "<mask token>\n\n\nclass IsingModel:\n\n def __init__(self, image, J, rate, sigma):\n self.width = image.shape[0]\n self.height = image.shape[1]\n self._J = J\n self._rate = rate\n self._sigma =...
[ 4, 5, 6, 7, 10 ]