code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
from package.pack import * add(2, 2) sub(2, 3)
normal
{ "blob_id": "9583a97ae4b1fbf5ecdf33d848b13bf0b28d2eb4", "index": 2452, "step-1": "<mask token>\n", "step-2": "<mask token>\nadd(2, 2)\nsub(2, 3)\n", "step-3": "from package.pack import *\nadd(2, 2)\nsub(2, 3)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
""" Given a sentence as `txt`, return `True` if any two adjacent words have this property: One word ends with a vowel, while the word immediately after begins with a vowel (a e i o u). ### Examples vowel_links("a very large appliance") ➞ True vowel_links("go to edabit") ➞ True vowel_links("an...
normal
{ "blob_id": "eefd94e7c04896cd6265bbacd624bf7e670be445", "index": 4347, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef vowel_links(txt):\n import re\n lst = txt.split(' ')\n for i in range(len(lst) - 1):\n if re.search('[aeiou]', lst[i][-1]) and re.search('[aeiou]', lst[i +\n ...
[ 0, 1, 2 ]
# from __future__ import annotations from typing import List,Union,Tuple,Dict,Set import sys input = sys.stdin.readline # from collections import defaultdict,deque # from itertools import permutations,combinations # from bisect import bisect_left,bisect_right import heapq # sys.setrecursionlimit(10**5) # class UnionFi...
normal
{ "blob_id": "13b2e05f12c6d0cd91e89f01e7eef610b1e99856", "index": 9158, "step-1": "<mask token>\n\n\ndef main():\n N, M, K = map(int, input().split())\n G = [[] for _ in range(N)]\n for _ in range(M):\n a, b, c = map(int, input().split())\n a -= 1\n b -= 1\n G[a].append((c, b)...
[ 1, 2, 3, 4, 5 ]
# Python program to count number of digits in a number. # print len(str(input('Enter No.: '))) num = input("Enter no.: ") i = 1 while num / 10: num = num / 10 i += 1 if num < 10: break print i
normal
{ "blob_id": "37748e3dd17f2bdf05bb28b4dfded12de97e37e4", "index": 9619, "step-1": "# Python program to count number of digits in a number.\n\n# print len(str(input('Enter No.: ')))\n\nnum = input(\"Enter no.: \")\n\ni = 1\nwhile num / 10:\n num = num / 10\n i += 1\n if num < 10:\n break\nprint i\n...
[ 0 ]
"""Seed file to make sample data for pets db.""" from models import db, User, Feedback from app import app # Create all tables db.drop_all() db.create_all() # If table isn't empty, empty it User.query.delete() Feedback.query.delete() # Add users and posts john = User(username="John",password="123",email="24",first...
normal
{ "blob_id": "d520f9d681125937fbd9dff316bdc5f922f25ff3", "index": 8050, "step-1": "<mask token>\n", "step-2": "<mask token>\ndb.drop_all()\ndb.create_all()\nUser.query.delete()\nFeedback.query.delete()\n<mask token>\ndb.session.add(john)\ndb.session.commit()\n<mask token>\ndb.session.add(feed)\ndb.session.commi...
[ 0, 1, 2, 3, 4 ]
import pytest from components import models pytestmark = pytest.mark.django_db def test_app_models(): assert models.ComponentsApp.allowed_subpage_models() == [ models.ComponentsApp, models.BannerComponent, ] def test_app_required_translatable_fields(): assert models.ComponentsApp.get_r...
normal
{ "blob_id": "b1622aa65422fcb69a16ad48a26fd9ed05b10382", "index": 8882, "step-1": "<mask token>\n\n\ndef test_app_models():\n assert models.ComponentsApp.allowed_subpage_models() == [models.\n ComponentsApp, models.BannerComponent]\n\n\n<mask token>\n\n\n@pytest.mark.django_db\ndef test_set_slug(en_loca...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: xurongzhong#126.com 技术支持qq群:6089740 # CreateDate: 2018-3-27 # pillow_rotate.py import glob import os from PIL import Image def rotate(files, dst, value=90): for file_ in files: img = Image.open(file_) img = img.rotate(value) name = "{...
normal
{ "blob_id": "cd104eec21be8a59e8fb3bd8ab061dd357fc126a", "index": 667, "step-1": "<mask token>\n\n\ndef rotate(files, dst, value=90):\n for file_ in files:\n img = Image.open(file_)\n img = img.rotate(value)\n name = '{}{}{}'.format(dst, os.sep, os.path.basename(file_))\n img.save(n...
[ 1, 2, 3, 4, 5 ]
import openpyxl as opx import pyperclip from openpyxl import Workbook from openpyxl.styles import PatternFill wb = Workbook(write_only=True) ws = wb.create_sheet() def parseSeq(lines,seqName): '''splits each column''' data = [] for line in lines: data.append(line.split(' ')) '''remov...
normal
{ "blob_id": "19e387cb731dad21e5ee50b0a9812df984c13f3b", "index": 7890, "step-1": "<mask token>\n\n\ndef parseSeq(lines, seqName):\n \"\"\"splits each column\"\"\"\n data = []\n for line in lines:\n data.append(line.split(' '))\n \"\"\"removes any spaces\"\"\"\n for i in range(len(data)):\n ...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import re from blessings import Terminal from validate_email import validate_email import requests import sys _site_ = sys.argv[1] _saida_ = sys.argv[2] _file_ = open(_saida_, "w") t = Terminal() r = requests.get(_site_, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6....
normal
{ "blob_id": "b52269237d66ea50c453395b9536f25f1310bf2e", "index": 287, "step-1": "#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nimport re\nfrom blessings import Terminal\nfrom validate_email import validate_email\nimport requests\nimport sys\n_site_ = sys.argv[1]\n_saida_ = sys.argv[2]\n_file_ = open(_saida_...
[ 0 ]
# wilfred.py # Authors # Stuart C. Larsen (SCL) # Daryl W. Bennet (DWB) # Set up three main modules (command, control, reconnaissance), # and then enter main event loop. # # Command: # Gather mission priorities and objectives, such as turn left, turn right # goto GPS 45, 65, land, take off. # # Control: # Fl...
normal
{ "blob_id": "a77fb90cdc6e7f9b70f9feeefc2b7f8e93a2d8c5", "index": 9875, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef mainLoop():\n wilfredCommunication = command.Command()\n wilfredCommunication.waitForClient()\n wilfredCommand = command.Command()\n while True:\n if not wilfre...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'VideoAd.compress' db.add_column(u'main_videoad', 'compres...
normal
{ "blob_id": "b4bcf9903f4a34c8b256c65cada29e952a436f74", "index": 2215, "step-1": "<mask token>\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n db.add_column(u'main_videoad', 'compress', self.gf(\n 'django.db.models.fields.BooleanField')(default=False),\n keep...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Swking @File : ZDT.py @Date : 2018/12/28 @Desc : """ import numpy as np class ZDT1: def __init__(self): self.dimension = 30 self.objFuncNum = 2 self.isMin = True self.min = np.zeros(self.dimension) self.max = np.zeros(self.dimension) + 1 self.s...
normal
{ "blob_id": "8ca16947054b681a5f43d8b8029191d031d3a218", "index": 8352, "step-1": "<mask token>\n\n\nclass ZDT2:\n\n def __init__(self):\n self.dimension = 30\n self.objFuncNum = 2\n self.isMin = True\n self.min = np.zeros(self.dimension)\n self.max = np.zeros(self.dimension)...
[ 12, 13, 16, 17, 18 ]
from .chair_model import run_chair_simulation, init_omega_t, \ JumpingModel, H_to_L from .utils import load_hcp_peaks, Condition, average_peak_counts
normal
{ "blob_id": "9087a7bf42070fdb8639c616fdf7f09ad3903656", "index": 6755, "step-1": "<mask token>\n", "step-2": "from .chair_model import run_chair_simulation, init_omega_t, JumpingModel, H_to_L\nfrom .utils import load_hcp_peaks, Condition, average_peak_counts\n", "step-3": "from .chair_model import run_chair_...
[ 0, 1, 2 ]
from appJar import gui app = gui("Calculator", "560x240") ### FUNCTIONS ### n1, n2 = 0.0, 0.0 result = 0.0 isFirst = True calc = "" def doMath(btn): global result, n1, n2, isFirst, calc inputNumber() if(btn == "Add"): calc = "a" if(btn == "Substract"): calc = "s" if(btn == "Multiply"): calc =...
normal
{ "blob_id": "084299da1c2f41de96e60d37088466c7b61de38e", "index": 9750, "step-1": "<mask token>\n\n\ndef doMath(btn):\n global result, n1, n2, isFirst, calc\n inputNumber()\n if btn == 'Add':\n calc = 'a'\n if btn == 'Substract':\n calc = 's'\n if btn == 'Multiply':\n calc = 'm...
[ 3, 5, 6, 7, 8 ]
from marshmallow import fields, post_load from rebase.common.schema import RebaseSchema, SecureNestedField from rebase.views.bid_limit import BidLimitSchema class TicketSetSchema(RebaseSchema): id = fields.Integer() bid_limits = SecureNestedField(BidLimitSchema, exclude=('ticket_set',), only=('id', 'p...
normal
{ "blob_id": "5ebc4f61810f007fd345b52531f7f4318820b9c8", "index": 6333, "step-1": "<mask token>\n\n\nclass TicketSetSchema(RebaseSchema):\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 TicketSetSchema(RebaseSchem...
[ 1, 2, 4, 5 ]
rf = open('A-large.in', 'r') wf = open('A-large.out', 'w') cases = int(rf.readline()) for case in range(1, cases + 1): digits = [False] * 10 n = int(rf.readline()) if n == 0: wf.write('Case #%s: INSOMNIA\n' % case) continue for i in range(1, 999999): cur = n * i for c in ...
normal
{ "blob_id": "0074b0cd1e4317e36ef4a41f8179464c2ec6c197", "index": 8250, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor case in range(1, cases + 1):\n digits = [False] * 10\n n = int(rf.readline())\n if n == 0:\n wf.write('Case #%s: INSOMNIA\\n' % case)\n continue\n for i in r...
[ 0, 1, 2 ]
from tkinter import * import re class Molecule: def __init__(self, nom, poids, adn): self.nom = nom self.poids = poids self.adn = adn def __repr__(self): return "{} : {} g".format(self.nom, self.poids) class Menu: def __init__(self): self.data = dict() se...
normal
{ "blob_id": "4d05e65dce9f689ae533a57466bc75fa24db7b4d", "index": 4558, "step-1": "<mask token>\n\n\nclass Menu:\n\n def __init__(self):\n self.data = dict()\n self.main = Tk()\n self.main.title('Molécules')\n self.main.config(bg='black')\n self.main.minsize(210, 220)\n ...
[ 17, 18, 23, 24, 26 ]
# -*- coding: utf-8 -*- """ Created on Fri Jul 19 13:42:09 2019 @author: Administrator """ from config.path_config import * import GV def ReadTxtName(rootdir): #读取文件中的每一行,转为list lines = [] with open(rootdir, 'r') as file_to_read: while True: line = file_to_read.read...
normal
{ "blob_id": "92bbccfbfebf905965c9cb0f1a85ffaa7d0cf6b5", "index": 3796, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef project_query_lz_main(question):\n txt_line = ReadTxtName(PROJECT_NAMES)\n for project_name in txt_line:\n if project_name in question:\n GV.SHOW = True\n ...
[ 0, 1, 2, 3, 4 ]
''' Created on Mar 27, 2019 @author: Iulia ''' from Graph import Graph from Controller import * from Iterators.Vertices import * from File import File from Iterators.EdgesIterator import EdgesIterator def test(): tup = File.readInput("file.txt") graph = tup[0] edgeData = tup[1] ctrl = Controller(grap...
normal
{ "blob_id": "b01ff71792895bb8839e09ae8c4a449405349990", "index": 7066, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test():\n tup = File.readInput('file.txt')\n graph = tup[0]\n edgeData = tup[1]\n ctrl = Controller(graph, edgeData)\n vertices = ctrl.nrVertices()\n itv = verti...
[ 0, 1, 2, 3, 4 ]
#calss header class _WATERWAYS(): def __init__(self,): self.name = "WATERWAYS" self.definitions = waterway self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['waterway']
normal
{ "blob_id": "33daf5753b27f6b4bcb7c98e28cf2168e7f0b403", "index": 9541, "step-1": "<mask token>\n", "step-2": "class _WATERWAYS:\n <mask token>\n", "step-3": "class _WATERWAYS:\n\n def __init__(self):\n self.name = 'WATERWAYS'\n self.definitions = waterway\n self.parents = []\n ...
[ 0, 1, 2, 3 ]
indelCost = 1 swapCost = 13 subCost = 12 noOp = 0 def alignStrings(x,y): nx = len(x) ny = len(y) S = matrix(nx+1, ny+1) #?? for i in range (nx+1) for j in range (ny+1) if i == 0: #if the string is empty S[i][j] = j #this will put all the letters from j in i elif j == 0: #if the second string ...
normal
{ "blob_id": "65aa85675393efa1a0d8e5bab4b1dbf388018c58", "index": 261, "step-1": "\nindelCost = 1\nswapCost = 13\nsubCost = 12\nnoOp = 0\n\t\ndef alignStrings(x,y):\n\t\n\tnx = len(x)\n\tny = len(y)\n\tS = matrix(nx+1, ny+1) #?? \n\t\n\tfor i in range (nx+1)\n\t\tfor j in range (ny+1)\n\t\t\tif i == 0:\t#if the s...
[ 0 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 17:34:32 2019 @author: fanlizhou Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt' Plot heatmap of amino acid usage and codon usage Plot codon usage in each gene for each amino acid. Genes were arranged so that the ge...
normal
{ "blob_id": "ae7a2de8742e353818d4f5a28feb9bce04d787bb", "index": 8382, "step-1": "<mask token>\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\n 'Analyze codon usage of SP and LP\\n')\n parser.add_argument('sp_file', help='one input SP data file\\n')\n parser.add_argument('...
[ 11, 13, 16, 20, 21 ]
from flask import Blueprint class NestableBlueprint(Blueprint): def register_blueprint(self, blueprint, **options): def deferred(state): # state.url_prefix => 自己url前缀 + blueprint.url_prefix => /v3/api/cmdb/ url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', bluepri...
normal
{ "blob_id": "2c505f3f1dfdefae8edbea0916873229bcda901f", "index": 764, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass NestableBlueprint(Blueprint):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass NestableBlueprint(Blueprint):\n\n def register_blueprint(self, blueprint, **options):\...
[ 0, 1, 2, 3, 4 ]
# coding: utf-8 import sys #from operator import itemgetter sysread = sys.stdin.readline read = sys.stdin.read from heapq import heappop, heappush from collections import defaultdict sys.setrecursionlimit(10**7) import math #from itertools import product#accumulate, combinations, product #import bisect# lower_bound etc...
normal
{ "blob_id": "f73a3bd7665ac9cc90085fcac2530c93bef69d3d", "index": 6705, "step-1": "<mask token>\n\n\ndef run():\n mod = 1000000007\n N, *AB = map(int, read().split())\n A_B = []\n INF = float('inf')\n zerozero = 0\n for i in range(N):\n a = AB[2 * i]\n b = AB[2 * i + 1]\n if...
[ 1, 2, 3, 4, 5 ]
""" Given a list of partitioned and sentiment-analyzed tweets, run several trials to guess who won the election """ import json import math import sys import pprint import feature_vector def positive_volume(f): return f['relative_volume'] * f['positive_percent'] def inv_negative_volume(f): return 1.0 - f['r...
normal
{ "blob_id": "d508cb0a8d4291f1c8e76d9d720be352c05ef146", "index": 8651, "step-1": "<mask token>\n\n\ndef positive_volume(f):\n return f['relative_volume'] * f['positive_percent']\n\n\n<mask token>\n\n\ndef normalized_sentiment(f):\n return (f['average_sentiment'] + 1) / 2\n\n\ndef normalized_square_sentimen...
[ 6, 7, 10, 12, 13 ]
from odoo import models, fields, api from datetime import datetime, timedelta from odoo import exceptions import logging import math _logger = logging.getLogger(__name__) class BillOfLading(models.Model): _name = 'freight.bol' _description = 'Bill Of Lading' _order = 'date_of_issue desc, writ...
normal
{ "blob_id": "f8e287abc7e1a2af005aa93c25d95ce770e29bf9", "index": 7378, "step-1": "<mask token>\n\n\nclass BillOfLading(models.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 <mask token>\n <mask token>...
[ 30, 32, 38, 47, 49 ]
import pandas as pd import numpy as np import geopandas as gp from sys import argv import os import subprocess n, e, s, w = map(int, argv[1:5]) output_dir = argv[5] print(f'{(n, e, s, w)=}') for lat in range(s, n + 1): for lon in range(w, e + 1): latdir = 'n' if lat >= 0 else 's' londir = 'e' if ...
normal
{ "blob_id": "9f36b846619ca242426041f577ab7d9e4dad6a43", "index": 3797, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(f'(n, e, s, w)={n, e, s, w!r}')\nfor lat in range(s, n + 1):\n for lon in range(w, e + 1):\n latdir = 'n' if lat >= 0 else 's'\n londir = 'e' if lon >= 0 else 'w'\n...
[ 0, 1, 2, 3, 4 ]
s=int(input()) print(s+2-(s%2))
normal
{ "blob_id": "0412369f89842e2f55aa115e63f46a1b71a0f322", "index": 2685, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(s + 2 - s % 2)\n", "step-3": "s = int(input())\nprint(s + 2 - s % 2)\n", "step-4": "s=int(input())\nprint(s+2-(s%2))", "step-5": null, "step-ids": [ 0, 1, 2, ...
[ 0, 1, 2, 3 ]
# Generated by Django 3.1.1 on 2020-10-07 04:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articals', '0001_initial'), ] operations = [ migrations.AddField( model_name='artical', name='thumb', fi...
normal
{ "blob_id": "d69bffb85d81ab3969bfe7dfe2759fa809890208", "index": 503, "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 = [('articals', '...
[ 0, 1, 2, 3, 4 ]
# flush in poker def IsContinuous(numbers): if not numbers or len(numbers) < 1 : return False numbers.sort() number_of_zero = 0 number_of_gap = 0 for i in range(len(numbers)): if numbers[i] == 0: number_of_zero += 1 small = number_of_zero big = small + 1 whi...
normal
{ "blob_id": "68a776d7fccc8d8496a944baff51d2a862fc7d31", "index": 1259, "step-1": "<mask token>\n", "step-2": "def IsContinuous(numbers):\n if not numbers or len(numbers) < 1:\n return False\n numbers.sort()\n number_of_zero = 0\n number_of_gap = 0\n for i in range(len(numbers)):\n ...
[ 0, 1, 2 ]
import typ @typ.typ(items=[int]) def gnome_sort(items): """ >>> gnome_sort([]) [] >>> gnome_sort([1]) [1] >>> gnome_sort([2,1]) [1, 2] >>> gnome_sort([1,2]) [1, 2] >>> gnome_sort([1,2,2]) [1, 2, 2] """ i = 0 n = len(items) while i < n: if i and items[i] < items[i - 1]: ...
normal
{ "blob_id": "70aba6c94b7050113adf7ae48bd4e13aa9a34587", "index": 1023, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@typ.typ(items=[int])\ndef gnome_sort(items):\n \"\"\"\n >>> gnome_sort([])\n []\n >>> gnome_sort([1])\n [1]\n >>> gnome_sort([2,1])\n [1, 2]\n >>> gnome_sort([1,2])\n [1, ...
[ 0, 1, 2 ]
import json from constants import * from coattention_layer import * from prepare_generator import * from tensorflow.keras.layers import Input from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint, Early...
normal
{ "blob_id": "a8d52d81ef6538e9cb8a0a9cab7cd0a778454c8e", "index": 6424, "step-1": "<mask token>\n\n\ndef coattention(num_embeddings):\n image_input = Input(shape=(196, 512))\n question_input = Input(shape=(SEQ_LENGTH,))\n output = CoattentionModel(num_embeddings)(question_input, image_input)\n model =...
[ 3, 4, 5, 6, 7 ]
## # hunt_and_kill.py # 05 Oct 2021 # Generates a maze using the hunt and kill algorithm # S from sys import argv from enum import Enum import random # Cardinal directions, can be OR'd and AND'd DIRS = { 'N': 1 << 0, 'E': 1 << 1, 'S': 1 << 2, 'W': 1 << 3 } O_DIRS = { 'N': 'S', ...
normal
{ "blob_id": "54002bc7e2a1991d2405acbe1d399e8803ac5582", "index": 7210, "step-1": "<mask token>\n\n\ndef walk_maze(maze: list[int], width: int, height: int, start: tuple[int, int]\n ) ->None:\n \"\"\"\n Does a random walk, setting the cells as it goes, until it cant find a\n path.\n \"\"\"\n maz...
[ 4, 6, 7, 8, 9 ]
import numpy import numpy.fft import numpy.linalg import copy from astropy.io import fits from scipy.interpolate import RectBivariateSpline from scipy.signal import convolve import offset_index # some basic definitions psSize = 9 # psSize x psSize postage stamps of stars # zero padded RectBivariateSpline, if on def R...
normal
{ "blob_id": "2ab6488276c74da8c3d9097d298fc53d1caf74b1", "index": 6243, "step-1": "<mask token>\n\n\ndef RectBivariateSplineZero(y1, x1, map1, kx=1, ky=1):\n return RectBivariateSpline(y1, x1, map1, kx=kx, ky=ky)\n y2 = numpy.zeros(numpy.size(y1) + 2)\n y2[1:-1] = y1\n y2[0] = 2 * y2[1] - y2[2]\n y...
[ 13, 14, 15, 18, 23 ]
import torch import torch.nn as nn import torch.nn.functional as F class Net(torch.nn.Module): def __init__(self, layer_sizes=[256, 128, 2], dropout_prob=None, device=None): super(Net, self).__init__() self.device = device if dropout_prob is not None and dropout_prob > 0.5: pr...
normal
{ "blob_id": "4711adcc7c95993ec13b9d06fa674aa064f79bfd", "index": 314, "step-1": "<mask token>\n\n\nclass Net(torch.nn.Module):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, layer_sizes=[256, 128, 2], dropout_prob=None, device\n ...
[ 1, 2, 3, 4, 5 ]
from ShazamAPI import Shazam import json import sys print("oi")
normal
{ "blob_id": "c248d653556ecdf27e56b57930832eb293dfd579", "index": 5413, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('oi')\n", "step-3": "from ShazamAPI import Shazam\nimport json\nimport sys\nprint('oi')\n", "step-4": "from ShazamAPI import Shazam\nimport json\nimport sys\n\nprint(\"oi\")\n",...
[ 0, 1, 2, 3 ]
# -*- coding: UTF-8 -*- # File name: ukWorkingDays # Created by JKChang # 29/07/2020, 11:20 # Tag: # Description: from datetime import date,timedelta,datetime from workalendar.europe import UnitedKingdom cal = UnitedKingdom() print(cal.holidays(2020)) def workingDate(start,end): cal = UnitedKingdom() res = [...
normal
{ "blob_id": "feed412278d9e711e49ef209ece0876c1de4a873", "index": 886, "step-1": "<mask token>\n\n\ndef workingDate(start, end):\n cal = UnitedKingdom()\n res = []\n delta = end - start\n for i in range(delta.days + 1):\n day = start + timedelta(days=i)\n if cal.is_working_day(day) or da...
[ 1, 2, 3, 4, 5 ]
"""Google Scraper Usage: web_scraper.py <search> <pages> <processes> web_scraper.py (-h | --help) Arguments: <search> String to be Searched <pages> Number of pages <processes> Number of parallel processes Options: -h, --help Show this screen. """ import re from functools impo...
normal
{ "blob_id": "68dcac07bbdb4dde983939be98ece127d963c254", "index": 3610, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_urls(search_string, start):\n temp = []\n url = 'http://www.google.com/search'\n payload = {'q': search_string, 'start': start}\n my_headers = {'User-agent': 'Mozi...
[ 0, 2, 3, 4, 5 ]
import time import argparse import utils from data_loader import DataLoader from generate_model_predictions import sacrebleu_metric, compute_bleu import tensorflow as tf import os import json from transformer import create_masks # Since the target sequences are padded, it is important # to apply a padding mask when c...
normal
{ "blob_id": "7613dde4f49044fbca13acad2dd75587ef68f477", "index": 2903, "step-1": "<mask token>\n\n\ndef loss_function(real, pred, loss_object, pad_token_id):\n \"\"\"Calculates total loss containing cross entropy with padding ignored.\n Args:\n real: Tensor of size [batch_size, length_logits, voca...
[ 5, 6, 7, 8, 9 ]
def check(root, a, b): if root: if (root.left == a and root.right == b) or (root.left ==b and root.right==a): return False return check(root.left, a, b) and check(root.right, a, b) return True def isCousin(root, a, b): # Your code here if check(root, a, b)==False: ret...
normal
{ "blob_id": "96cfee85194c9c30b3d74bbddc2a31b6933eb032", "index": 2226, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef isCousin(root, a, b):\n if check(root, a, b) == False:\n return False\n q = []\n q.insert(0, root)\n tmp = set()\n while len(q):\n l = len(q)\n ...
[ 0, 1, 2, 3 ]
import MySQLdb import settings import redis import socket import fcntl import struct import datetime db = MySQLdb.connect(settings.host, settings.user, settings.pwd, settings.db) cursor = db.cursor() def connect_mysql(): try: db.ping() except: db = MySQLdb.connect...
normal
{ "blob_id": "b46b9b086fc089e24cb39a0c2c4ac252591b2190", "index": 1540, "step-1": "import MySQLdb\nimport settings\nimport redis\nimport socket\nimport fcntl\nimport struct\nimport datetime\n\n\ndb = MySQLdb.connect(settings.host, settings.user, settings.pwd, settings.db)\ncursor = db.cursor()\ndef connect_mysql(...
[ 0 ]
from numpy import empty import pickle from dataset import Dataset from image import Image f = open("./digitdata/trainingimages", "r") reader = f.readlines() labels = open("./digitdata/traininglabels", "r") lreader = labels.readlines() trainImageList = [] j = 0 i = 0 while(j < len(reader)): image_array = empty([...
normal
{ "blob_id": "aff439361716c35e5f492680a55e7470b4ee0c42", "index": 5905, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile j < len(reader):\n image_array = empty([28, 28])\n for r in range(0, 28):\n row = reader[j]\n j += 1\n for c in range(0, 28):\n if row[c] == '#...
[ 0, 1, 2, 3, 4 ]
from disaggregation import DisaggregationManager import numpy as np from more_itertools import windowed x = np.random.random_sample(10 * 32 * 1024) w = windowed(x, n=1024, step=128) z = DisaggregationManager._overlap_average(np.array(list(w)), stride=128) print(z.shape) print(x.shape) assert z.shape == x.shape
normal
{ "blob_id": "6d4950ca61cd1e2ee7ef8b409577e9df2d65addd", "index": 4462, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(z.shape)\nprint(x.shape)\nassert z.shape == x.shape\n", "step-3": "<mask token>\nx = np.random.random_sample(10 * 32 * 1024)\nw = windowed(x, n=1024, step=128)\nz = Disaggregation...
[ 0, 1, 2, 3 ]
from context import vicemergencyapi from vicemergencyapi.vicemergency import VicEmergency from geographiclib.geodesic import Geodesic from shapely.geometry import Point def geoDistance(p1, p2): return Geodesic.WGS84.Inverse(p1.y, p1.x, p2.y, p2.x)['s12'] melbourne = Point(144.962272, -37.812274) def compare(f...
normal
{ "blob_id": "920f00632599945397364dd0f52f21234e17f9ef", "index": 9445, "step-1": "<mask token>\n\n\ndef geoDistance(p1, p2):\n return Geodesic.WGS84.Inverse(p1.y, p1.x, p2.y, p2.x)['s12']\n\n\n<mask token>\n\n\ndef compare(f):\n return geoDistance(f.getLocation(), melbourne)\n\n\n<mask token>\n", "step-2...
[ 2, 3, 4, 5, 6 ]
__title__ = 'pyaddepar' __version__ = '0.6.0' __author__ = 'Thomas Schmelzer' __license__ = 'MIT' __copyright__ = 'Copyright 2019 by Lobnek Wealth Management'
normal
{ "blob_id": "cc985ae061c04696dbf5114273befd62321756ae", "index": 9569, "step-1": "<mask token>\n", "step-2": "__title__ = 'pyaddepar'\n__version__ = '0.6.0'\n__author__ = 'Thomas Schmelzer'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2019 by Lobnek Wealth Management'\n", "step-3": null, "step-4": null...
[ 0, 1 ]
import unittest import TicTacToe class pVpTestCase(unittest.TestCase): # def test_something(self): # self.assertEqual(True, False) def twoplayer_setup(self): game1 = TicTacToe.Game() player1 = TicTacToe.Player('X', game1) player2 = TicTacToe.Player('O', game1) return (g...
normal
{ "blob_id": "de0521db3909054c333ac3877ff0adf15ab180fb", "index": 1732, "step-1": "<mask token>\n\n\nclass CvPTestCase(unittest.TestCase):\n\n def onecompplayer_setup(self):\n game1 = TicTacToe.Game()\n computer1 = TicTacToe.Computer('X', game1)\n player2 = TicTacToe.Player('O', game1)\n ...
[ 13, 15, 17, 20, 22 ]
from joecceasy import Easy def main(): paths = ['..','.'] absOfEntries = [ i.abs for i in Easy.WalkAnIter(paths) ] for i in absOfEntries: print( i ) if __name__=='__main__': main() """ def main(maxEntries = 99): i = -1 print( "Walker test, Walking cu...
normal
{ "blob_id": "b720a52f1c2e6e6be7c0887cd94441d248382242", "index": 1836, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n paths = ['..', '.']\n absOfEntries = [i.abs for i in Easy.WalkAnIter(paths)]\n for i in absOfEntries:\n print(i)\n\n\n<mask token>\n", "step-3": "<mask...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- from sklearn.feature_extraction.text import TfidfVectorizer import sentimentAnalysis as sA import sys import os import numpy as np from sklearn import decomposition from gensim import corpora, models if len(sys.argv) > 1: keyword = sys.argv[1] else: keyword = 'data' ...
normal
{ "blob_id": "ee47b60274ed2eb53a05203e0086d7815bcaaa6e", "index": 7759, "step-1": "# -*- coding: utf-8 -*-\r\n\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nimport sentimentAnalysis as sA\r\nimport sys\r\nimport os\r\nimport numpy as np\r\nfrom sklearn import decomposition\r\nfrom gensim impor...
[ 0 ]
# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text. # Example: For string "Ana has apples." given as a parameter the function will return the dicti...
normal
{ "blob_id": "14807568af046594644095a2682e0eba4f445b26", "index": 8053, "step-1": "<mask token>\n\n\ndef funct(string):\n dict = {}\n for i in string:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n return dict\n\n\n<mask token>\n\n\ndef counter():\n string =...
[ 2, 3, 4, 5, 6 ]
from http import HTTPStatus #from pytest_chalice.handlers import RequestHandler import app from chalice.test import Client def test_index_with_url(): with Client(app.app) as client: response = client.http.get('/?url=https://google.com') assert response.status_code == HTTPStatus.MOVED_PERMANENTLY ...
normal
{ "blob_id": "e7e9a53d4c41448521b324d51641a46827faa692", "index": 2607, "step-1": "<mask token>\n\n\ndef test_index_with_url():\n with Client(app.app) as client:\n response = client.http.get('/?url=https://google.com')\n assert response.status_code == HTTPStatus.MOVED_PERMANENTLY\n assert ...
[ 1, 2, 3, 4, 5 ]
import csv from functools import reduce class Csvread: def __init__(self, fpath): self._path=fpath with open (fpath) as file: read_f=csv.reader(file) print(read_f) #<_csv.reader object at 0x000002A53144DF40> self._sheet = list(read_f)[1:] #utworzenie listy ...
normal
{ "blob_id": "67793c8851e7107c6566da4e0ca5d5ffcf6341ad", "index": 8867, "step-1": "<mask token>\n\n\nclass Csvcalc:\n\n def __init__(self, cont):\n self._cont = cont\n\n def row_count(self):\n return len(self._cont)\n\n def get_row(self, row_no):\n return self._cont[row_no]\n\n de...
[ 7, 10, 11, 13, 15 ]
# coding:utf-8 from flask_sqlalchemy import SQLAlchemy from config.manager import app from config.db import db class Category(db.Model): __tablename__ = 'category' id = db.Column(db.Integer, primary_key=True) # 编号 name = db.Column(db.String(20), nullable=False) # 账号 addtime = db.Column(db.DateTime, ...
normal
{ "blob_id": "743aa4ccbb9a131b5ef3d04475789d3d1da1a2fa", "index": 2407, "step-1": "<mask token>\n\n\nclass Category(db.Model):\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 Category(db.Model):\n __tablename__...
[ 1, 3, 4, 5, 6 ]
from django.views.generic import (ListView, DetailView, CreateView, DeleteView, UpdateView, TemplateView) from django.views.generic.edit import ModelFormMixin from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.contrib.auth.decorators i...
normal
{ "blob_id": "a63e5186c0eb8b5ae8510b473168db3461166513", "index": 7784, "step-1": "<mask token>\n\n\nclass BaseModelApi(TemplateView, ModelFormMixin):\n\n def get_template_names(self):\n prefix = self.request.method\n if prefix in ['PUT', 'PATCH', 'POST']:\n prefix = 'form'\n na...
[ 14, 15, 21, 25, 26 ]
import matplotlib.pyplot as plt import numpy as np from tti_explorer.contacts import he_infection_profile plt.style.use('default') loc = 0 # taken from He et al gamma_params = { 'a': 2.11, 'loc': loc, 'scale': 1/0.69 } t = 10 days = np.arange(t) mass = he_infection_profile(t, gamma_params) fig, ax = pl...
normal
{ "blob_id": "fa5cbbd03641d2937e4502ce459d64d20b5ee227", "index": 8630, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.style.use('default')\n<mask token>\nax.bar(np.arange(5) + 0.1, [1 / 5, 1 / 5, 1 / 5, 1 / 5, 1 / 5], label=\n 'Kucharski profile', align='edge', color='C1', zorder=1, alpha=0.6)\nax...
[ 0, 1, 2, 3, 4 ]
import random from datetime import timedelta from typing import Union, Type, Tuple, List, Dict from django import http from django.test import TestCase, Client from django.utils import timezone from exam_web import errors from exam_web.models import Student, AcademyGroup, uuid_str, ExamSession, \ UserSession, Que...
normal
{ "blob_id": "44e4151279884ce7c5d5a9e5c82916ce2d3ccbc2", "index": 9789, "step-1": "<mask token>\n\n\nclass TestGetExamTickets(ApiTestCase):\n get_exams: ApiClient\n session: ExamSession\n student_session: UserSession\n questions: List[Question]\n tickets: List[ExamTicket]\n ticket_map: Dict[str,...
[ 15, 34, 42, 44, 45 ]
# -*- coding: utf-8 -*- import io import urllib.request from pymarc import MARCReader class Item: """ Represents an item from our Library catalogue (https://www-lib.soton.ac.uk) Usage: #>>> import findbooks #>>> item = findbooks.Item('12345678') #>>> item.getMarcFields() ...
normal
{ "blob_id": "abfff0901e5f825a473119c93f53cba206609428", "index": 7482, "step-1": "<mask token>\n\n\nclass Item:\n <mask token>\n <mask token>\n\n def __init__(self, barcode):\n self.barcode = barcode\n self.marc = None\n self.record = None\n self.title = None\n self.au...
[ 6, 7, 8, 11, 12 ]
""" Task. Given two integers a and b, find their greatest common divisor. Input Format. The two integers a, b are given in the same line separated by space. Constraints. 1<=a,b<=2·109. Output Format. Output GCD(a, b). """ def EuclidGCD(a, b): if b == 0: return a else: a = a%b return Euc...
normal
{ "blob_id": "39d82267f966ca106ee384e540c31a3e5e433318", "index": 2248, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef EuclidGCD(a, b):\n if b == 0:\n return a\n else:\n a = a % b\n return EuclidGCD(b, a)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef EuclidGCD...
[ 0, 1, 2, 3, 4 ]
# CSE 415 Winter 2019 # Assignment 1 # Jichun Li 1531264 # Part A # 1 def five_x_cubed_plus_1(x): return 5 * (x ** 3) + 1 #2 def pair_off(ary): result = [] for i in range(0, int(len(ary) / 2 * 2), 2): result.append([ary[i], ary[i + 1]]) if (int (len(ary) % 2) == 1): result.append([ar...
normal
{ "blob_id": "681788ffe7672458e8d334316aa87936746352b1", "index": 4054, "step-1": "def five_x_cubed_plus_1(x):\n return 5 * x ** 3 + 1\n\n\n<mask token>\n", "step-2": "def five_x_cubed_plus_1(x):\n return 5 * x ** 3 + 1\n\n\ndef pair_off(ary):\n result = []\n for i in range(0, int(len(ary) / 2 * 2),...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python3 # --------------------------------------------------- # SSHSploit Framework # --------------------------------------------------- # Copyright (C) <2020> <Entynetproject> # # This program is free soft...
normal
{ "blob_id": "caf83d35ce6e0bd4e92f3de3a32221705a529ec1", "index": 9467, "step-1": "<mask token>\n\n\ndef banner():\n os.system('clear')\n os.system('cat banner/banner.txt')\n print('')\n print('SSHSploit Framework v1.0')\n print('------------------------')\n print('')\n\n\n<mask token>\n", "st...
[ 1, 2, 4, 5, 6 ]
# $Header: //depot/cs/s/ajax_support.wsgi#10 $ from werkzeug.wrappers import Response from p.DRequest import DRequest from db.Support import SupportSession from db.Exceptions import DbError, SupportSessionExpired import db.Db as Db import db.Support import cgi import simplejson as json def application(environ, start_...
normal
{ "blob_id": "be58862b66708c9de8cf7642c9de52ec744b079e", "index": 805, "step-1": "<mask token>\n\n\ndef application(environ, start_response):\n \"\"\"AJAX scripts for email templates.\"\"\"\n request = DRequest(environ)\n resp = None\n try:\n Db.start_transaction()\n form = cgi.FieldStor...
[ 4, 5, 6, 7, 8 ]
import datetime import time import rfc822 from django.conf import settings from urllib2 import Request, urlopen, URLError, HTTPError from urllib import urlencode import re import string try: import django.utils.simplejson as json except: import json from django.core.cache import cache from tagging.models import T...
normal
{ "blob_id": "f720eaf1ea96ccc70730e8ba1513e1a2bb95d29d", "index": 4842, "step-1": "import datetime\nimport time\nimport rfc822\nfrom django.conf import settings\nfrom urllib2 import Request, urlopen, URLError, HTTPError\nfrom urllib import urlencode\nimport re \nimport string\ntry:\n import django.utils.simplejs...
[ 0 ]
# Generate some object patterns as save as JSON format import json import math import random from obstacle import * def main(map): obs = [] for x in range(1,35): obs.append(Obstacle(random.randint(0,map.getHeight()), y=random.randint(0,map.getWidth()), radius=20).toJsonObject()) jsonOb={'map': {'obstacle': obs}}...
normal
{ "blob_id": "b849a2902c8596daa2c6da4de7b9d1c07b34d136", "index": 7883, "step-1": "# Generate some object patterns as save as JSON format\nimport json\nimport math\nimport random\nfrom obstacle import *\n\ndef main(map):\n\tobs = []\n\tfor x in range(1,35):\n\t\tobs.append(Obstacle(random.randint(0,map.getHeight(...
[ 0 ]
# MÁSTER EN BIG DATA Y BUSINESS ANALYTICS # MOD 1 - FINAL EVALUATION - EX. 2: dado un archivo que contiene en cada línea # una palabra o conjunto de palabras seguido de un valor numérico denominado # “sentimiento” y un conjunto de tweets, se pide calcular el sentimiento de # aquellas palabras o conjunto de palabras que...
normal
{ "blob_id": "acd2d84529e197d6f9d134e8d7e25a51a442f3ae", "index": 8615, "step-1": "<mask token>\n\n\ndef get_tweets(filename):\n \"\"\" Process a json formatted file with tweets using pandas read_json \"\"\"\n try:\n tweets = []\n pd_tweets = pd.read_json(filename, lines=True)\n pd_twee...
[ 2, 3, 4, 5, 6 ]
import os from typing import List, Optional, Sequence import boto3 from google.cloud import storage from ..globals import GLOBALS, LOGGER def set_gcs_credentials(): if os.path.exists(GLOBALS.google_application_credentials): return secrets_client = boto3.client( "secretsmanager", reg...
normal
{ "blob_id": "a5eeafef694db04770833a4063358e8f32f467b0", "index": 8310, "step-1": "<mask token>\n\n\ndef set_gcs_credentials():\n if os.path.exists(GLOBALS.google_application_credentials):\n return\n secrets_client = boto3.client('secretsmanager', region_name=GLOBALS.\n aws_region, endpoint_ur...
[ 2, 3, 4, 5, 6 ]
import math def normal(data,mean,variance): # print data-mean return -1*(((data-mean)**2)/(2*variance)) - (0.5 * math.log(2*3.1415*variance)) a = math.log(0.33333) + normal(67.7854,6.0998,13.5408) b = math.log(0.33333) + normal(67.7854,119.3287,9.4803) c = math.log(0.33333) + normal(67.7854,65.7801,12.6203) d =...
normal
{ "blob_id": "0edca9893d62eea6513543a1d3dd960e9e95d573", "index": 7505, "step-1": "import math\n\ndef normal(data,mean,variance):\n\t# print data-mean\n\treturn -1*(((data-mean)**2)/(2*variance)) - (0.5 * math.log(2*3.1415*variance))\n\na = math.log(0.33333) + normal(67.7854,6.0998,13.5408)\nb = math.log(0.3333...
[ 0 ]
from django.db import models ch=[ ('Garment','Garment'), ('Hardgoods','Hardgoods'), ('Home Furnishing','Home Furnishing'), ] class Factory(models.Model): name = models.CharField(max_length=30,choices=ch) def __str__(self): return self.name class Fabric(models.Model): n...
normal
{ "blob_id": "a0dcfb738451c11ed4ff1428629c3f7bbf5c52c9", "index": 5649, "step-1": "<mask token>\n\n\nclass Category(models.Model):\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.category\n\n\nclass Subcategory(models.Model):\n name = models.ForeignKey(Categ...
[ 17, 20, 22, 24, 30 ]
#from getData import getRatings import numpy as np num_factors = 10 num_iter = 75 regularization = 0.05 lr = 0.005 folds=5 #to make sure you are able to repeat results, set the random seed to something: np.random.seed(17) def split_matrix(ratings, num_users, num_movies): #Convert data into (IxJ...
normal
{ "blob_id": "b4267612e7939b635542099e1ba31e661720607a", "index": 3129, "step-1": "<mask token>\n\n\ndef split_matrix(ratings, num_users, num_movies):\n X = np.zeros((num_users, num_movies))\n for r in np.arange(len(ratings)):\n X[ratings[r, 0] - 1, ratings[r, 1] - 1] = ratings[r, 2]\n return X\n\...
[ 2, 3, 4, 5, 7 ]
# coding: utf-8 """ MailSlurp API MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://ww...
normal
{ "blob_id": "a4ccf373695b7df60039bc8f6440a6ad43d265c1", "index": 3750, "step-1": "<mask token>\n\n\nclass FormControllerApi(object):\n <mask token>\n <mask token>\n <mask token>\n\n def submit_form_with_http_info(self, **kwargs):\n \"\"\"Submit a form to be parsed and sent as an email to an ad...
[ 2, 3, 4, 5, 7 ]
#!/usr/bin/python import sys BLACK = '\033[30;0m' RED = '\033[31;0m' GREEN = '\033[32;0m' YELLOW = '\033[33;0m' BLUE = '\033[34;0m' PINK = '\033[35;0m' CBLUE = '\033[36;0m' WHITE = '\033[37;0m' def colorPrint(color, str): print(color + str + '\033[0m'); def main(): if sys.argv.__len__() < ...
normal
{ "blob_id": "a49c00dab8d445ce0b08fd31a4a41d6c8976d662", "index": 2263, "step-1": "<mask token>\n\n\ndef colorPrint(color, str):\n print(color + str + '\\x1b[0m')\n\n\ndef main():\n if sys.argv.__len__() < 2:\n print('Wrong usage, exit')\n return\n colorPrint(YELLOW, sys.argv[1])\n\n\n<mask...
[ 2, 3, 4, 5, 6 ]
from urllib import request from urllib import error from urllib.request import urlretrieve import os, re from bs4 import BeautifulSoup import configparser from apng2gif import apng2gif config = configparser.ConfigParser() config.read('crawler.config') # 下載儲存位置 directoryLocation = os.getcwd() + '\\img' # 設置要爬的頁面 urlLis...
normal
{ "blob_id": "7bcdd6c5c6e41b076e476e1db35b663e34d74a67", "index": 1885, "step-1": "<mask token>\n\n\ndef saveImg(imgurl, downLoadType):\n fileLocation = directoryLocation + '\\\\' + downLoadType + '\\\\' + title\n if not os.path.exists(fileLocation):\n os.makedirs(fileLocation)\n file = fileLocati...
[ 3, 4, 5, 6, 7 ]
from pythonforandroid.recipe import CompiledComponentsPythonRecipe from multiprocessing import cpu_count from os.path import join class NumpyRecipe(CompiledComponentsPythonRecipe): version = '1.18.1' url = 'https://pypi.python.org/packages/source/n/numpy/numpy-{version}.zip' site_packages_name = 'numpy' ...
normal
{ "blob_id": "610610e7e49fc98927a4894efe62686e26e0cb83", "index": 3502, "step-1": "<mask token>\n\n\nclass NumpyRecipe(CompiledComponentsPythonRecipe):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def build_compiled_components(self, arch):\n ...
[ 3, 4, 5, 6, 7 ]
import os.path as path from googleapiclient.discovery import build from google.oauth2 import service_account # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1FSMATLJUNCbV8...
normal
{ "blob_id": "f9261c1844cc629c91043d1221d0b76f6e22fef6", "index": 6157, "step-1": "<mask token>\n\n\ndef main():\n service_account_json = path.join(path.dirname(path.abspath(__file__)),\n 'service_account.json')\n credentials = service_account.Credentials.from_service_account_file(\n service_a...
[ 3, 5, 6, 7, 8 ]
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: dev_nb/10_DogcatcherFlatten.ipynb import pandas as pd import argparse import csv import os import numpy as np import string def FivePrimeArea(df): ...
normal
{ "blob_id": "5c5922fd3a7a5eec121d94e69bc972089e435175", "index": 9406, "step-1": "<mask token>\n\n\ndef FivePrimeArea(df):\n df = df.sort_values(by=['chr', 'end'], ascending=True)\n df['FA_start'] = df['gene_start']\n df_exon = df[df['type'] == 'exon'].copy()\n df_exon = df_exon.drop_duplicates(subse...
[ 4, 6, 8, 9, 11 ]
from collections import deque s = list(input().upper()) new = list(set(s)) # 중복 제거 한 알파벳 리스트로 카운트 해줘야 시간초과 안남 n = {} for i in new: n[i] = s.count(i) cnt = deque() for k, v in n.items(): cnt.append(v) if cnt.count(max(cnt)) >1: print('?') else: print(max(n, key=n.get))
normal
{ "blob_id": "5dcb20f52b5041d5f9ea028b383e0f2f10104af9", "index": 9486, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in new:\n n[i] = s.count(i)\n<mask token>\nfor k, v in n.items():\n cnt.append(v)\nif cnt.count(max(cnt)) > 1:\n print('?')\nelse:\n print(max(n, key=n.get))\n", "step...
[ 0, 1, 2, 3, 4 ]
from datetime import datetime import pytz from pytz import timezone ##PDXtime = datetime.now() ##print(PDXtime.hour) ## ##NYCtime = PDXtime.hour + 3 ##print(NYCtime) ## ##Londontime = PDXtime.hour + 8 ##print(Londontime) Londontz = timezone('Europe/London') Londonlocaltime = datetime.now(Londontz) print(Londo...
normal
{ "blob_id": "d8cfd9de95e1f47fc41a5389f5137b4af90dc0f1", "index": 3949, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(Londonlocaltime)\nprint(Londonlocaltime.strftime('%H'))\n<mask token>\nprint(PDXlocaltime)\nprint(PDXlocaltime.strftime('%H'))\n<mask token>\nprint(NYClocaltime)\nprint(NYClocaltime...
[ 0, 1, 2, 3, 4 ]
from collections import OrderedDict import copy import numpy as np from scipy.optimize import curve_fit from ... import Operation as opmod from ...Operation import Operation from ....tools import saxstools class SpectrumFit(Operation): """ Use a measured SAXS spectrum (I(q) vs. q), to optimize the param...
normal
{ "blob_id": "7b5713c9a5afa911df1c2939751de30412162f15", "index": 446, "step-1": "<mask token>\n\n\nclass SpectrumFit(Operation):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SpectrumFit(Operation):\n <mask token>\n\n def __init__(self):\n input_names...
[ 1, 3, 4, 5, 6 ]
import numpy as np import matplotlib.pyplot as plt import pandas as pd month = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May'] df = pd.DataFrame([[53, 0, 5, 3, 3], [51, 0, 1, 3, 2], [70, 4, 7, 5, 1], [ 66, 4, 1, 4, 2], [64, 4, 4, 3, 2], [69, 4, 7, 8, 2], [45, 2, 8, 4, 2], ...
normal
{ "blob_id": "f5c277da2b22debe26327464ae736892360059b4", "index": 781, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.pcolor(df)\nplt.colorbar()\nplt.yticks(np.arange(0.5, len(df.index), 1), df.index)\nplt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)\nplt.show()\n", "step-3": "<mask token>...
[ 0, 1, 2, 3 ]
# -*- encoding:utf-8 -*- import os import unittest from HTMLTestRunner_cn import HTMLTestRunner from time import sleep from framework.SunFlower import SunFlower from testcase.TestCRM import TestCRM class TestCRMcreateCustomer(TestCRM): # 创建客户 def createCustomer(self): # 点击客户图标 self.driver....
normal
{ "blob_id": "74bc530d53cd86c52c44ba8e98d4d8f502032340", "index": 2423, "step-1": "<mask token>\n\n\nclass TestCRMcreateCustomer(TestCRM):\n <mask token>\n\n def test_weiChat(self):\n self.login()\n self.createCustomer()\n self.logout()\n\n\n<mask token>\n", "step-2": "<mask token>\n\...
[ 2, 3, 4, 5, 6 ]
import os from unittest import TestCase class TestMixin(TestCase): @classmethod def setUpClass(cls): cls.base_dir = os.path.dirname(os.path.abspath(__file__)) cls.fixtures_dir = os.path.join(cls.base_dir, 'fixtures') cls.bam_10xv2_path = os.path.join(cls.fixtures_dir, '10xv2.bam') ...
normal
{ "blob_id": "268a8252f74a2bdafdadae488f98997c91f5607c", "index": 2686, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TestMixin(TestCase):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestMixin(TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.base_dir = os.pat...
[ 0, 1, 2, 3 ]
import sys import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from uraeus.nmbd.python import simulation from uraeus.nmbd.python.engine.numerics.math_funcs import A, B database_directory = os.path.abspath('../../') sys.path.append(database_directory) from uraeus_fsae.simenv.assemblies i...
normal
{ "blob_id": "e0541c377eb6631e4ef5eb79b1204612ce8af48c", "index": 6107, "step-1": "<mask token>\n\n\ndef generate_circular_path(radius, offset):\n theta = np.deg2rad(np.linspace(0, 360, 360))\n x_data = radius * np.sin(theta) + offset[0]\n y_data = radius * np.cos(theta) + offset[1]\n radii = radius *...
[ 3, 8, 9, 10, 11 ]
# Imports import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils import data from torch.utils.data import DataLoader import torchvision.datasets as datasets import torchvision.transforms as transforms # Create Fully Connected Network class NN(nn.Module): def...
normal
{ "blob_id": "1edb92a4905048f3961e3067c67ef892d7b8a034", "index": 9154, "step-1": "<mask token>\n\n\nclass NN(nn.Module):\n\n def __init__(self, input_size, num_classes):\n super(NN, self).__init__()\n self.fc1 = nn.Linear(input_size, 50)\n self.fc2 = nn.Linear(50, num_classes)\n\n def ...
[ 4, 5, 6, 7, 8 ]
import logging from typing import Dict import numpy as np from meshkit import Mesh from rendkit.materials import DepthMaterial from vispy import gloo, app from vispy.gloo import gl logger = logging.getLogger(__name__) class Renderable: def __init__(self, material_name: str, at...
normal
{ "blob_id": "061c287d5f0a5feeeaedc80eea6b3fc4ff02286e", "index": 7191, "step-1": "<mask token>\n\n\nclass Renderable:\n\n def __init__(self, material_name: str, attributes: Dict[str, np.ndarray\n ], model_mat=np.eye(4), uv_scale=1.0):\n self.model_mat = model_mat\n self.material_name = ma...
[ 10, 11, 13, 16, 17 ]
import numpy as np import cv2 as cv import methods as meth from numpy.fft import fft2, fftshift, ifft2, ifftshift import pandas import os import noGPU as h import matplotlib.pyplot as plt class fullSys(): def __init__(self, dir, file, size, line): csv_reader = pandas.read_csv(file, index_col='Objective') ...
normal
{ "blob_id": "e3c9487f3221ca89b9014b2e6470ca9d4dbc925a", "index": 2239, "step-1": "<mask token>\n\n\nclass section:\n\n def __init__(self, i0, j0, subImg, Params):\n self.Params = Params\n self.subParams = {}\n self.subParams['wLen'] = [6.3e-07, 5.3e-07, 4.3e-07]\n self.subParams['s...
[ 9, 11, 13, 15, 19 ]
import time import random import math people = [('Seymour', 'BOS'), ('Franny', 'DAL'), ('Zooey', 'CAK'), ('Walt', 'MIA'), ('Buddy', 'ORD'), ('Les', 'OMA')] destination = 'LGA' flights = dict() for line in file('schedule.txt'): origin, dest, depart, arrive, price...
normal
{ "blob_id": "bd5f298027f82edf5451f5297d577005674de4c3", "index": 3577, "step-1": "import time\nimport random\nimport math\n\npeople = [('Seymour', 'BOS'),\n ('Franny', 'DAL'),\n ('Zooey', 'CAK'),\n ('Walt', 'MIA'),\n ('Buddy', 'ORD'),\n ('Les', 'OMA')]\n\ndestination ...
[ 0 ]
from math import * import math import re import numpy as np class atom: aid=0 atype='' x=0.0 y=0.0 z=0.0 rid=0 rtype='' model=[] chainid='' def getlen(atm1,atm2): dist=sqrt(pow(atm1.x-atm2.x,2)+pow(atm1.y-atm2.y,2)+pow(atm1.z-atm2.z,2)) return dist def ...
normal
{ "blob_id": "78123c806e5a8c0cc7511a5024769f8c61621efa", "index": 9877, "step-1": "<mask token>\n\n\nclass atom:\n aid = 0\n atype = ''\n x = 0.0\n y = 0.0\n z = 0.0\n rid = 0\n rtype = ''\n model = []\n chainid = ''\n\n\ndef getlen(atm1, atm2):\n dist = sqrt(pow(atm1.x - atm2.x, 2) ...
[ 5, 6, 8, 9, 10 ]
"""Ex026 Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra "A". Em que posição ela aparece a primeira vez. Em que posição ela aparece pela última vez.""" frase = str(input('Digite uma frase: ')).strip().lower() n_a = frase.count('a') f_a = frase.find('a')+1 l_a= frase.rfind('a')-1...
normal
{ "blob_id": "58f3b8c5470c765c81f27d39d9c28751a8c2b719", "index": 277, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(f'Sua frase tem {n_a} letras a')\nprint(f'A letra A aparece pela primeira vez na {f_a}° posição')\nprint(f'A letra A apaerece pela ultima vez na {l_a}° posição')\n", "step-3": "<ma...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- """ Created on Tue Mai 15 11:34:22 2018 @author: Diogo Leite """ from SQL_obj_new.Dataset_config_dataset_new_sql import _DS_config_DS_SQL class Dataset_conf_ds(object): """ This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table data...
normal
{ "blob_id": "76d2c3f74e8fae160396b4015ccec478dba97b87", "index": 7422, "step-1": "<mask token>\n\n\nclass Dataset_conf_ds(object):\n <mask token>\n\n def __init__(self, id_ds_conf_ds=-1, value_configuration=-1,\n FK_id_configuration_DCT_DCD=-1, FK_id_dataset_DS_DCD=-1):\n \"\"\"\n Cons...
[ 2, 3, 5, 6, 7 ]
from flask import Flask from raven.contrib.flask import Sentry from flask.signals import got_request_exception app = Flask(__name__) sentry = Sentry(dsn=app.config['SENTRY_DSN']) @got_request_exception.connect def log_exception_to_sentry(app, exception=None, **kwargs): """ Logs an exception to sentry. :p...
normal
{ "blob_id": "f739fb56eae1ada2409ef7d75958bad2018f5134", "index": 2743, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@got_request_exception.connect\ndef log_exception_to_sentry(app, exception=None, **kwargs):\n \"\"\"\n Logs an exception to sentry.\n\n :param app: The current application\n ...
[ 0, 1, 2, 3 ]
import time import itertools import re from pyspark import SparkContext, SparkConf from pyspark.rdd import portable_hash from datetime import datetime APP_NAME = 'in-shuffle-secondary-sort-compute' INPUT_FILE = '/data/Taxi_Trips.csv.xsmall' OUTPUT_DIR = '/data/output-in-shuffle-sort-compute-{timestamp}.txt' COMMA_DE...
normal
{ "blob_id": "05d6f15102be41937febeb63ed66a77d3b0a678e", "index": 8517, "step-1": "<mask token>\n\n\ndef key_func(entry):\n return entry[0], entry[1]\n\n\ndef make_pair(entry):\n key = entry[FIRST_KEY], entry[SECOND_KEY]\n return key, entry\n\n\ndef unpair(entry):\n return entry[0][0], entry[1][0], en...
[ 5, 6, 8, 10, 11 ]
def solution(A): if not A: return 1 elif len(A) == 1: if A[0] == 1: return 2 else: return 1 A.sort() prev = 0 for i in A: if i != (prev + 1): return i - 1 else: prev = i return prev + 1
normal
{ "blob_id": "8c3c066ed37fe0f67acfd2d5dc9d57ec2b996275", "index": 5640, "step-1": "<mask token>\n", "step-2": "def solution(A):\n if not A:\n return 1\n elif len(A) == 1:\n if A[0] == 1:\n return 2\n else:\n return 1\n A.sort()\n prev = 0\n for i in A:\n...
[ 0, 1, 2 ]
import visgraph.dbcore as vg_dbcore dbinfo = { 'user':'visgraph', 'password':'ohhai!', 'database':'vg_test', } def vgtest_basic_database(): #vg_dbcore.initGraphDb(dbinfo) gstore = vg_dbcore.DbGraphStore(dbinfo) n1 = gstore.addNode(ninfo={'name':'foo', 'size':20}) n2 = gstore.addNode(ninfo={'name':'bar',...
normal
{ "blob_id": "ffee0b0e00b4cebecefc3671332af3e2ffe7491b", "index": 8155, "step-1": "import visgraph.dbcore as vg_dbcore\n\ndbinfo = {\n'user':'visgraph',\n'password':'ohhai!',\n'database':'vg_test',\n}\n\ndef vgtest_basic_database():\n#vg_dbcore.initGraphDb(dbinfo)\n\n gstore = vg_dbcore.DbGraphStore(dbinfo)\n\...
[ 0 ]
import os from celery import Celery import django from django.conf import settings from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings') #celery_app = Celery('nightcrawler.tasks.keep_it', broker=settings.CELERY_BROKER_URL) celery_app = Celery('nightcrawler', broker=sett...
normal
{ "blob_id": "d4bc6bfe6bef730273db38f3c99352bbc3f48a5f", "index": 7604, "step-1": "<mask token>\n\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-2": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\n<mask t...
[ 1, 2, 3, 4, 5 ]
from turtle import * def drawSquare(): for i in range(4): forward(100) left(90) if __name__ == '__main__': drawSquare() up() forward(200) down() drawSquare() mainloop()
normal
{ "blob_id": "1ce5b97148885950983e39b7e99d0cdfafe4bc16", "index": 5382, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef drawSquare():\n for i in range(4):\n forward(100)\n left(90)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef drawSquare():\n for i in range(4):\n ...
[ 0, 1, 2, 3 ]
import os import pandas as pd import numpy as np from dataloader import * from keras.optimizers import Adam, SGD from mylib.models.misc import set_gpu_usage set_gpu_usage() from mylib.models import densesharp, metrics, losses from keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard, EarlyStopping, ReduceL...
normal
{ "blob_id": "94b3fa700d7da0ca913adeb0ad5324d1fec0be50", "index": 7104, "step-1": "<mask token>\n\n\ndef main(batch_size, crop_size, learning_rate, segmentation_task_ratio,\n weight_decay, save_folder, epochs, alpha):\n print(learning_rate)\n print(alpha)\n print(weight_decay)\n train_dataset = Clf...
[ 1, 2, 3, 4, 5 ]
from flask import Flask, render_template app = Flask(__name__) @app.route('/',methods=["GET","POST"]) def inicio(): nombre = "jose" return render_template("inicio.html",nombre=nombre) app.run(debug=True)
normal
{ "blob_id": "caa28bd64141c8d2f3212b5e4e77129d81d24c71", "index": 2290, "step-1": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef inicio():\n nombre = 'jose'\n return render_template('inicio.html', nombre=nombre)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/', methods=[...
[ 1, 2, 3, 4, 5 ]
#coding=utf-8 '初始化Package,加载url,生成app对象' import web from myapp.urls import urls app = web.application(urls, globals())
normal
{ "blob_id": "4480b305a6f71ff64022f2b890998326bf402bf0", "index": 1669, "step-1": "<mask token>\n", "step-2": "<mask token>\napp = web.application(urls, globals())\n", "step-3": "<mask token>\nimport web\nfrom myapp.urls import urls\napp = web.application(urls, globals())\n", "step-4": "#coding=utf-8\r\n'初始...
[ 0, 1, 2, 3 ]
import cv2 import numpy as np import os from tqdm import tqdm DIR = '/home/nghiatruong/Desktop' INPUT_1 = os.path.join(DIR, 'GOPR1806.MP4') INPUT_2 = os.path.join(DIR, '20190715_180940.mp4') INPUT_3 = os.path.join(DIR, '20190715_181200.mp4') RIGHT_SYNC_1 = 1965 LEFT_SYNC_1 = 1700 RIGHT_SYNC_2 = 5765 LEFT_SYNC_2 = 128...
normal
{ "blob_id": "f8f538773693b9d9530775094d9948626247a3bb", "index": 6950, "step-1": "<mask token>\n\n\ndef add_frame_id(video, output_dir):\n reader = cv2.VideoCapture(video)\n if not reader.isOpened():\n return -1\n os.makedirs(output_dir, exist_ok=True)\n frame_count = int(reader.get(cv2.CAP_PR...
[ 2, 3, 4, 5, 6 ]
from models.bearing_registry import BearingRegistry from models.faction import Faction from models.maneuver import Maneuver import time class Activation: """ This class represents the Activation phase of a turn """ def __init__(self, game): """ Constructor game: Th...
normal
{ "blob_id": "0774bad4082e0eb04ae3f7aa898c0376147e9779", "index": 2645, "step-1": "<mask token>\n\n\nclass Activation:\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Activation:\n <mask token>\n\n def __init__(self, game):\n \"\"\"\n Constructor\...
[ 1, 3, 4, 5, 6 ]
from django.contrib.auth import get_user_model from django.test import TestCase from .models import Order from markets.models import Market from tickers.models import Ticker from trades.models import Trade USER_MODEL = get_user_model() class Matching: @staticmethod def get_bid_ask( market : Market): ...
normal
{ "blob_id": "866ee2c4fa52bf9bda4730c7a9d46bb4798adcd4", "index": 1775, "step-1": "<mask token>\n\n\nclass Matching:\n <mask token>\n <mask token>\n\n @staticmethod\n def process_order(self, order: Order):\n if order.status == Order.STATUS_WAITING_NEW:\n order.status = Order.STATUS_N...
[ 7, 8, 9, 11, 12 ]
from rest_framework import serializers from .models import Good, Favorite, Comment class GoodSerializer(serializers.ModelSerializer): class Meta: model = Good fields = ('user', 'article', 'created_at') class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Favori...
normal
{ "blob_id": "fc8b9029955de6b11cbfe8e24107c687f49685c1", "index": 9179, "step-1": "<mask token>\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Comment\n fields = 'text', 'image', 'user', 'article', 'created_at'\n", "step-2": "<mask token>\n\n\nclass Favor...
[ 1, 2, 3, 4, 5 ]