code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import os import unittest from mock import Mock from tfsnippet.utils import * class HumanizeDurationTestCase(unittest.TestCase): cases = [ (0.0, '0 sec'), (1e-8, '1e-08 sec'), (0.1, '0.1 sec'), (1.0, '1 sec'), (1, '1 sec'), (1.1, '1.1 secs'), (59, '59 secs...
normal
{ "blob_id": "9189c1dd21b0858df3138bcf4fc7568b378e6271", "index": 885, "step-1": "<mask token>\n\n\nclass NotSetTestCase(unittest.TestCase):\n <mask token>\n\n\nclass _CachedPropertyHelper(object):\n\n def __init__(self, value):\n self.value = value\n\n @cached_property('_cached_value')\n def c...
[ 11, 12, 13, 18, 22 ]
# uncompyle6 version 3.2.3 # Python bytecode 3.6 (3379) # Decompiled from: Python 2.7.5 (default, Jul 13 2018, 13:06:57) # [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] # Embedded file name: ./authx/migrations/0001_initial.py # Compiled at: 2018-08-23 19:33:14 # Size of source mod 2**32: 2715 bytes from __future__ import un...
normal
{ "blob_id": "1073845131afb2446ca68ee10092eeb00feef800", "index": 3585, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- """Chatbot learning 학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다. """ from tensorflow.keras import models from tensorflow.keras import layers from tensorflow.keras import optimizers, losses, metrics from tensorflow.keras import preprocessing import numpy as np import pa...
normal
{ "blob_id": "bd06030ace665a0686c894a863e5c779b6d0931c", "index": 6447, "step-1": "<mask token>\n\n\ndef convert_text_to_index(sentences, vocabulary, type):\n sentences_index = []\n for sentence in sentences:\n sentence_index = []\n if type == DECODER_INPUT:\n sentence_index.extend(...
[ 3, 6, 7, 8, 9 ]
import argparse import datetime import importlib import pprint import time import random import numpy as np import torch from torch.utils.tensorboard import SummaryWriter from utils import get_git_state, time_print, AverageMeter, ProgressMeter, save_checkpoint def train(cfg, epoch, data_loader, model): data_tim...
normal
{ "blob_id": "81688d51696156905736b5de7a4929387fd385ab", "index": 91, "step-1": "<mask token>\n\n\ndef train(cfg, epoch, data_loader, model):\n data_time = AverageMeter('Data', ':6.3f')\n batch_time = AverageMeter('Time', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n progress = ProgressMeter(len(...
[ 2, 3, 4, 5, 6 ]
from django import forms class TeacherForm(forms.Form): name = forms.CharField(label='Your Name', max_length=100, widget=forms. TextInput(attrs={'class': 'form-control text-center w-75 mx-auto'})) email = forms.EmailField(widget=forms.TextInput(attrs={'class': 'form-control text-center w-75 mx...
normal
{ "blob_id": "7c5877eea78c3fa8b7928219edd52e2502c16c09", "index": 6392, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TeacherForm(forms.Form):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TeacherForm(forms.Form):\n name = forms.CharField(label='Your Name', max...
[ 0, 1, 2, 3 ]
zi=["L","Ma","Mi","J","Vi","S","D"] V=[] for i in range(0,len(zi)): x=input("dati salariul de: {} ".format(zi[i])) V.append(int(x)) print("Salariul in fiecare zi: {}".format(V)) print(sum(V)) print(round(sum(V)/7,2)) print(max(V)) vMax=[] vMin=[] for i in range(0,len(zi)): if V[i]==max(V): ...
normal
{ "blob_id": "6c91114e0c32628b64734000c82354105032b2fd", "index": 7954, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(0, len(zi)):\n x = input('dati salariul de: {} '.format(zi[i]))\n V.append(int(x))\nprint('Salariul in fiecare zi: {}'.format(V))\nprint(sum(V))\nprint(round(sum(V) /...
[ 0, 1, 2, 3 ]
#https://codecombat.com/play/level/village-champion # Incoming munchkins! Defend the town! # Define your own function to fight the enemy! # In the function, find an enemy, then cleave or attack it. def attttaaaaacccckkkk(): enemy = hero.findNearest(hero.findEnemies()) #enemy = hero.findNearestEnemy() if e...
normal
{ "blob_id": "ce365e011d8cc88d9aa6b4df18ea3f4e70d48f5c", "index": 4887, "step-1": "<mask token>\n", "step-2": "def attttaaaaacccckkkk():\n enemy = hero.findNearest(hero.findEnemies())\n if enemy:\n if enemy and hero.isReady('cleave'):\n hero.cleave(enemy)\n else:\n hero...
[ 0, 1, 2, 3 ]
import numpy as np catogory = np.array([50, 30, 40, 20]) data = np.array([[20, 50, 10, 15, 20], [30, 40, 20, 65, 35], [75, 30, 42, 70, 45], [40, 25, 35, 22, 55]]) print(catogory) print(data) print(catogory.dot(data)) print(data.T.dot(catogory))
normal
{ "blob_id": "e4b49faaad648c6e85274abb18f994083a74013d", "index": 7160, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(catogory)\nprint(data)\nprint(catogory.dot(data))\nprint(data.T.dot(catogory))\n", "step-3": "<mask token>\ncatogory = np.array([50, 30, 40, 20])\ndata = np.array([[20, 50, 10, 15...
[ 0, 1, 2, 3 ]
import xlsxwriter workbook = xlsxwriter.Workbook('商品编码.xlsx') worksheet = workbook.add_worksheet() with open('商品编码.txt', 'rt') as f: data = f.read() data = data.splitlines(True) count = 1 row = 0 for x in data: if count < 3: count += 1 continue x = x.split(',') column = 0 for e in x:...
normal
{ "blob_id": "59a8a4cf4b04a191bfb70fd07668141dbfeda790", "index": 6822, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('商品编码.txt', 'rt') as f:\n data = f.read()\n<mask token>\nfor x in data:\n if count < 3:\n count += 1\n continue\n x = x.split(',')\n column = 0\n fo...
[ 0, 1, 2, 3 ]
x = 1 while x <= 24: if x % 5 == 0: x = x + 1 continue print(x) x = x + 1
normal
{ "blob_id": "61cfc583cd87ac0528cb07f4e051392167414920", "index": 1960, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile x <= 24:\n if x % 5 == 0:\n x = x + 1\n continue\n print(x)\n x = x + 1\n", "step-3": "x = 1\nwhile x <= 24:\n if x % 5 == 0:\n x = x + 1\n ...
[ 0, 1, 2 ]
#os for file system import os from sys import platform as _platform import fnmatch import inspect files = 0 lines = 0 extension0 = '.c' extension1 = '.cpp' extension2 = '.h' extension3 = '.hpp' filename = inspect.getframeinfo(inspect.currentframe()).filename startPath = os.path.dirname(os.path.abspath(...
normal
{ "blob_id": "d287123acdbabdd5a223e774c89945ab888fcbcc", "index": 5439, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('files_with_extensions.txt', 'w', encoding='utf-8') as filewrite:\n for r, d, f in os.walk(startPath):\n for file in f:\n if file.endswith(extension0) or fi...
[ 0, 1, 2, 3, 4 ]
# Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return([]) if no...
normal
{ "blob_id": "93ec15a37bd5f022e8f6e226e3bf0e91cc0457c6", "index": 2178, "step-1": "class Node:\n <mask token>\n\n\nclass Solution(object):\n\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n ...
[ 3, 4, 5, 6, 7 ]
# coding: utf-8 import os, sys import numpy as np from math import exp, sqrt, pi def factorial(n): value = 1 for i in range(n,1,-1): value *= i return value def double_factorial(n): k = 1 for i in range(n, 1, -2): k *= i #print("n:", n, "double factorial:", k) return k ...
normal
{ "blob_id": "005650e2747c61b730960a29891b6ba6c8bd381b", "index": 1334, "step-1": "<mask token>\n\n\ndef double_factorial(n):\n k = 1\n for i in range(n, 1, -2):\n k *= i\n return k\n\n\n<mask token>\n\n\ndef gaussian_integral(alpha, m):\n if int(m / 2) * 2 == m:\n n = int(m / 2)\n ...
[ 2, 3, 4, 5, 6 ]
""" 默认查询所有 > db.test1000.find() { "_id" : ObjectId("5c3559ab648171cce9135dd6"), "name" : "zhangdapeng" } { "_id" : ObjectId("5c3559af648171cce9135dd7"), "name" : "zhangdapeng1" } { "_id" : ObjectId("5c3559b2648171cce9135dd8"), "name" : "zhangdapeng2" } { "_id" : ObjectId("5c3559b4648171cce9135dd9"),...
normal
{ "blob_id": "d8e0198244c3df77fa0258cc97a55042e36d056f", "index": 7756, "step-1": "<mask token>\n", "step-2": "\"\"\"\n默认查询所有\n > db.test1000.find()\n { \"_id\" : ObjectId(\"5c3559ab648171cce9135dd6\"), \"name\" : \"zhangdapeng\" }\n { \"_id\" : ObjectId(\"5c3559af648171cce9135dd7\"), \"name\" : \"zhan...
[ 0, 1 ]
from pathlib import Path file = Path(__file__).parent / 'input.txt' Y = 2000000 MAX_X = 4000000 MIN_X = 0 MAX_Y = 4000000 MIN_Y = 0 # file = Path(__file__).parent / 'test_input.txt' # Y = 10 # MAX_X = 20 # MIN_X = 0 # MAX_Y = 20 # MIN_Y = 0 text = file.read_text().splitlines() class Beacon(): def __init__(self, ...
normal
{ "blob_id": "f3a1a926feabcabc870f0a41ae239939c331d09d", "index": 4106, "step-1": "<mask token>\n\n\nclass Beacon:\n\n def __init__(self, pos, sensor) ->None:\n self.pos = pos\n self.sensor = sensor\n <mask token>\n\n def __repr__(self) ->str:\n return f'{self}'\n <mask token>\n ...
[ 24, 28, 30, 34, 35 ]
import requests from lxml import etree from pymongo import MongoClient from lib.rabbitmq import Rabbit from lib.log import LogHandler from lib.proxy_iterator import Proxies import yaml import json import datetime import re import time setting = yaml.load(open('config_local.yaml')) log = LogHandler('article_consumer')...
normal
{ "blob_id": "cd1d8a73b6958775a212d80b50de74f4b4de18bf", "index": 6319, "step-1": "<mask token>\n\n\nclass CrawlerDetail:\n\n def __init__(self):\n self.proxy = Proxies()\n\n def start_consume(self):\n channel = connection.channel()\n channel.queue_declare(queue='usual_article')\n ...
[ 4, 5, 6, 8, 9 ]
import scraperwiki, lxml.html, urllib2, re from datetime import datetime #html = scraperwiki.scrape("http://www.public.health.wa.gov.au/2/1035/2/publication_of_names_of_offenders_list.pm") doc = lxml.html.parse(urllib2.urlopen("http://www.public.health.wa.gov.au/2/1035/2/publication_of_names_of_offenders_list.pm")) ro...
normal
{ "blob_id": "e870900249b121f2416d7be543752ebf6392b6be", "index": 6868, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor tr in root.xpath(\"//div[@id='verdiSection10']/div/div/table/tbody/tr\")[1:]:\n data = {'conviction_date': datetime.strptime(re.match(\n '(\\\\d+/\\\\d+/\\\\d+)', tr[0].text...
[ 0, 1, 2, 3, 4 ]
# -*- coding: UTF-8 -*- import lava from lava.api.constants.vk import QueueType from lava.api.device import Device from lava.api.util import Destroyable __all__ = ["Session"] sessions = set() class Session(Destroyable): def __init__(self, physical_device, queue_index=None): super(Session, self).__init...
normal
{ "blob_id": "193dcf7bd658f88afe0a1f2fa28605f262e45bc2", "index": 1554, "step-1": "<mask token>\n\n\nclass Session(Destroyable):\n\n def __init__(self, physical_device, queue_index=None):\n super(Session, self).__init__()\n self.instance = lava.instance()\n if physical_device not in lava.d...
[ 5, 6, 7, 8, 9 ]
#roblem: Have the function PrimeTime(num) # take the num parameter being passed and return # the string true if the parameter is a prime number, \ # otherwise return the string false. # The range will be between 1 and 2^16. def PrimeTime(num): prime1 = (num-1)%6 prime2 = (num+1)%6 if prime1 * prime2 =...
normal
{ "blob_id": "5068a78a1aa31a277b3b5854ddd1d8990d07b104", "index": 3627, "step-1": "<mask token>\n", "step-2": "def PrimeTime(num):\n prime1 = (num - 1) % 6\n prime2 = (num + 1) % 6\n if prime1 * prime2 == 0:\n return 'True'\n else:\n return 'False'\n\n\n<mask token>\n", "step-3": "de...
[ 0, 1, 2, 3 ]
import os import json import librosa # Constants # Dataset used for training DATASET_PATH = "dataset" # Where the data is stored JSON_PATH = "data.json" # Number of samples considered to preprocess data SAMPLES_TO_CONSIDER = 22050 # 1 sec worth of sound # Main function to preprocess the data def prepare_dataset(dat...
normal
{ "blob_id": "ba808d23f6a8226f40e1c214012a1535ee1e9e98", "index": 2947, "step-1": "<mask token>\n\n\ndef prepare_dataset(dataset_path, json_path, n_mfcc=13, hop_length=512,\n n_fft=2048):\n data = {'mappings': [], 'labels': [], 'MFCCs': [], 'files': []}\n for i, (dir_path, dir_names, filenames) in enumer...
[ 1, 2, 3, 4, 5 ]
# Generated by Django 2.0.4 on 2018-04-30 14:01 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('base...
normal
{ "blob_id": "d13589979ba7b6facd8339111323270c9920a9bf", "index": 8127, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- class Solution: """ @param head: The first node of the linked list. @return: The node where the cycle begins. if there is no cycle, return null """ def detectCycle(self, head): # write your code here # 先确定是否有环,然后确定环的大小,再遍历确定位置。 cycle_...
normal
{ "blob_id": "3319614d154b16190f3cd8f4f65c3b0e0da277e9", "index": 9751, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n <mask token>\n", "step-3": "class Solution:\n <mask token>\n\n def detectCycle(self, head):\n cycle_len = -1\n one_node, two_node = head, he...
[ 0, 1, 2, 3, 4 ]
import requests from bs4 import BeautifulSoup ''' OCWから学院一覧を取得するスクリプト(6個くらいだから必要ない気もする) gakuinListの各要素は次のような辞書に鳴っている { 'name' : 学院名, 'url' : その学院の授業の一覧のurl, } ''' def getGakuinList(): url = "http://www.ocw.titech.ac.jp/" response = requests.get(url) soup = BeautifulSoup(response.content,"lxml") topMainNav = sou...
normal
{ "blob_id": "24274dddbeb1be743cfcac331ee688d48c9a46dd", "index": 8647, "step-1": "<mask token>\n\n\ndef getLectures(name, url):\n urlprefix = 'http://www.ocw.titech.ac.jp'\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'lxml')\n table = soup.find('table', class_='ranking-list...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 17:14:14 2018 @author: Winry """ import pandas as pd # 显示所有的列 pd.set_option('display.max_columns', None) # 读取数据 file_name = "data_11_8.csv" file_open = open(file_name) df = pd.read_csv(file_open) file_open.close() Newtaxiout_time = df['Newtaxiout_time'] time = df['t...
normal
{ "blob_id": "f5a474cdc8aa22322b252b980c0334a9db21bd5c", "index": 9300, "step-1": "<mask token>\n", "step-2": "<mask token>\npd.set_option('display.max_columns', None)\n<mask token>\nfile_open.close()\n<mask token>\nfor i in range(len(df)):\n count = []\n count = df2['Newappend1'][(df2['Newappend1'] > New...
[ 0, 1, 2, 3, 4 ]
def login(): usernameInput = input("Username : ") passwordInput = input("Password : ") if usernameInput == "admin" and passwordInput == "1234": return (showMenu()) else: print("User or Password Wrong.") return login() def showMenu(): print("---Please Choose Menu---") prin...
normal
{ "blob_id": "34dd6966a971e3d32e82a17cd08c3b66bb88163b", "index": 1277, "step-1": "<mask token>\n\n\ndef showMenu():\n print('---Please Choose Menu---')\n print('1. Vat7')\n print('2. Calculation')\n print('3. Vat Calulation')\n return menuSelect()\n\n\n<mask token>\n\n\ndef priceResult():\n pri...
[ 2, 4, 5, 6, 7 ]
# operatorTest02.py x = 5 x += 3 #복함 대입 연산자 print("x : ", x) print("-"*30) total = 0 total += 1 total
normal
{ "blob_id": "4f8bc19bb113c9eac7c2ac774ac7b16f569d9704", "index": 3083, "step-1": "<mask token>\n", "step-2": "<mask token>\nx += 3\nprint('x : ', x)\nprint('-' * 30)\n<mask token>\ntotal += 1\ntotal\n", "step-3": "x = 5\nx += 3\nprint('x : ', x)\nprint('-' * 30)\ntotal = 0\ntotal += 1\ntotal\n", "step-4": ...
[ 0, 1, 2, 3 ]
from tkinter import ttk import tkinter as tk import pyodbc #ConnectingDatabase# from tkinter import messagebox conn = pyodbc.connect('Driver={SQL Server};' 'Server=MUTHUCOMPUTER;' 'Database=Class4c v1;' 'Trusted_Connection=yes;') cursor = ...
normal
{ "blob_id": "8058ff209af03b7365ffad2a9ce2e2805b548f53", "index": 9927, "step-1": "<mask token>\n\n\ndef save():\n Names = Name.get()\n Ages = Age.get()\n Genders = Gender.get()\n Heights = height.get()\n weights = weight.get()\n rollnos = StudentId.get()\n Sports = Sport.get()\n cursor.ex...
[ 4, 5, 6, 7, 8 ]
#!/usr/local/bin/python # -*- coding: utf-8 -*- # importing regular stuff import os import sys import thread import threading import time import datetime from datetime import datetime import random import filecmp import ConfigParser import socket #my stuff will go here import include.action as action import include.l...
normal
{ "blob_id": "a3301180e53da4a6970c082e72d8721b29dcae2e", "index": 1403, "step-1": "#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\n# importing regular stuff\nimport os\nimport sys\nimport thread\nimport threading\nimport time\nimport datetime\nfrom datetime import datetime\nimport random\nimport filecmp\nimpo...
[ 0 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-30 14:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0007_auto_20170127_2254'), ] operations = [ migrations.AlterField(...
normal
{ "blob_id": "65ea27851d9db0f0a06d42bd37eff633d22a1548", "index": 9528, "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 = [('books', '00...
[ 0, 1, 2, 3, 4 ]
''' 단어 수학 시간 : 68ms (~2초), 메모리 : 29200KB (~256MB) 분류 : greedy ''' import sys input = sys.stdin.readline # 입력 N = int(input()) # 단어의 개수 arr = [list(input().strip()) for _ in range(N)] # 풀이 alphabet = [] for word in arr: for a in word: if a not in alphabet: alphabet.append(a) value_list = [] ...
normal
{ "blob_id": "6efc7ff304a05dfc5a7bed7d646e5d6ac034ce85", "index": 4706, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor word in arr:\n for a in word:\n if a not in alphabet:\n alphabet.append(a)\n<mask token>\nfor a in alphabet:\n value = 0\n for word in arr:\n if a no...
[ 0, 1, 2, 3, 4 ]
api_id = "2168275" api_hash = "e011a9cb95b7e7e153aa5840985fc883"
normal
{ "blob_id": "c6d6fcc242e1b63104a3f3eb788880635257ff4c", "index": 7503, "step-1": "<mask token>\n", "step-2": "api_id = '2168275'\napi_hash = 'e011a9cb95b7e7e153aa5840985fc883'\n", "step-3": "api_id = \"2168275\"\napi_hash = \"e011a9cb95b7e7e153aa5840985fc883\"\n", "step-4": null, "step-5": null, "step-...
[ 0, 1, 2 ]
# -*- coding: utf-8 -*- """pytest People functions, fixtures and tests.""" import pytest import ciscosparkapi from tests.utils import create_string # Helper Functions # pytest Fixtures @pytest.fixture(scope="session") def me(api): return api.people.me()
normal
{ "blob_id": "9b7ffa2bb62a8decbec51c6bdea38b4338726816", "index": 1891, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@pytest.fixture(scope='session')\ndef me(api):\n return api.people.me()\n", "step-3": "<mask token>\nimport pytest\nimport ciscosparkapi\nfrom tests.utils import create_string\n\...
[ 0, 1, 2, 3 ]
from kivy.uix.boxlayout import BoxLayout from kivy.graphics import * from kivy.clock import Clock from kivy.properties import StringProperty, BooleanProperty from kivy.uix.popup import Popup import time from math import sin, pi from kivy.lang import Builder from ui.custom_widgets import I18NPopup, I18NLabel Builder....
normal
{ "blob_id": "96086885e5353f3b4b3277c1daf4ee74831c3b73", "index": 8841, "step-1": "<mask token>\n\n\nclass Dripper(BoxLayout):\n\n def __init__(self, **kwargs):\n super(Dripper, self).__init__(**kwargs)\n self.index = 0.0\n self.sections = 20\n self.section_height = 1\n self....
[ 10, 12, 14, 15, 19 ]
# 효율적인 해킹 # https://www.acmicpc.net/problem/1325 from collections import deque import sys input = sys.stdin.readline n, m = map(int, input().split()) graph = [[] for _ in range(n + 1)] for _ in range(m): a, b = map(int, input().split()) graph[b].append(a) # B를 해킹하면 A도 해킹할 수 있다 def bfs(start): visited =...
normal
{ "blob_id": "8a631adc8d919fb1dded27177818c4cb30148e94", "index": 610, "step-1": "<mask token>\n\n\ndef bfs(start):\n visited = [False] * (n + 1)\n visited[start] = True\n q = deque()\n q.append(start)\n cnt = 1\n while q:\n now = q.popleft()\n for i in graph[now]:\n if ...
[ 1, 2, 3, 4, 5 ]
"""Implementation of the Brainpool standard, see https://tools.ietf.org/pdf/rfc5639.pdf#15 """ from sage.all import ZZ, GF, EllipticCurve from utils import increment_seed, embedding_degree, find_integer, SimulatedCurves, VerifiableCurve, \ class_number_check CHECK_CLASS_NUMBER = False def gen_brainpool_prime...
normal
{ "blob_id": "b717abaeecea2e97c6ec78d3e0e4c97a8de5eec3", "index": 9169, "step-1": "<mask token>\n\n\nclass Brainpool(VerifiableCurve):\n <mask token>\n\n def security(self):\n self._secure = False\n try:\n curve = EllipticCurve(GF(self._p), [self._a, self._b])\n except Arithm...
[ 8, 9, 10, 12, 17 ]
############################################## # Binary Tree # # by Vishal Nirmal # # # # A Binary Tree ADT implementation. # ############################################## class BinaryTree: def __init_...
normal
{ "blob_id": "3eaced9609c7adfa5457d7dcad8b2dfaeb697b16", "index": 3220, "step-1": "class BinaryTree:\n\n def __init__(self, data=None):\n self.data = data\n self.left = None\n self.right = None\n\n def insert(self, data):\n if self.data != None:\n arr = [self]\n ...
[ 12, 15, 18, 19, 22 ]
import sys def ler (t): i =0 for s in sys.stdin: l=s.split(" ") t.append(l) def melhor (t): i=1 x=int(t[0][0].strip("\n")) n=len(t) while(i<n): u=int((t[i][2]).strip()) if(u<x) i+=1 def vendedor(): t=[] ler(t) melhor(t) vendedor()
normal
{ "blob_id": "76664114382bdeb0bffb996e4dd4448b6c87520d", "index": 9719, "step-1": "import sys \n\ndef ler (t):\n\ti =0\n\tfor s in sys.stdin:\n\t\tl=s.split(\" \")\n\t\tt.append(l)\n\ndef melhor (t):\n\ti=1\n\tx=int(t[0][0].strip(\"\\n\"))\n\tn=len(t)\n\twhile(i<n):\n\t\tu=int((t[i][2]).strip())\n\t\tif(u<x)\n\t\...
[ 0 ]
"""This is the body of the low-level worker tool. A worker is intended to run as a process that imports a module, mutates it in one location with one operator, runs the tests, reports the results, and dies. """ import difflib import importlib import inspect import json import logging import subprocess import sys impo...
normal
{ "blob_id": "73a778c6e4216c23ac8d82eef96ce7b73b18f661", "index": 9100, "step-1": "<mask token>\n\n\nclass WorkerOutcome:\n \"\"\"Possible outcomes for a worker.\n \"\"\"\n NORMAL = 'normal'\n EXCEPTION = 'exception'\n NO_TEST = 'no-test'\n TIMEOUT = 'timeout'\n SKIPPED = 'skipped'\n\n\n<mask...
[ 3, 5, 6, 8, 9 ]
""" Module for generic standard analysis plots. """ import numpy as np import matplotlib.pyplot as plt import cartopy as cart import xarray as xr import ecco_v4_py as ecco def global_and_stereo_map(lat, lon, fld, plot_type='pcolormesh', cmap='YlOrRd', ...
normal
{ "blob_id": "b039ed74e62f3a74e8506d4e14a3422499046c06", "index": 860, "step-1": "<mask token>\n\n\ndef plot_depth_slice(x, depth, fld, stretch_depth=-500, plot_type=\n 'pcolormesh', cmap='YlOrRd', title=None, cmin=None, cmax=None, dpi=100,\n show_colorbar=True):\n \"\"\"2D plot of depth vs some other va...
[ 1, 2, 3, 4, 5 ]
# # struct_test.py # Nazareno Bruschi <nazareno.bruschi@unibo.it> # # Copyright (C) 2019-2020 University of Bologna # # 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.o...
normal
{ "blob_id": "d8d0c181fcfc9e0692369cc7a65259c43a68e931", "index": 5688, "step-1": "<mask token>\n", "step-2": "<mask token>\nPULPNNInstallPath = cwd = os.getcwd() + '/../'\nPULPNNSrcDirs = {'script': PULPNNInstallPath + 'scripts/'}\nPULPNNInstallPath32bit = cwd = os.getcwd() + '/../32bit/'\nPULPNNInstallPath64b...
[ 0, 1, 2, 3 ]
''' Created on 27 Mar 2015 @author: Jon ''' import matplotlib.pyplot as plt from numerical_functions import Timer import numerical_functions.numba_funcs.indexing as indexing import numpy as np import unittest class Test(unittest.TestCase): def test_take(self): x = np.linspace( 0, 100 ) ...
normal
{ "blob_id": "ee80169afd4741854eff8619822a857bbf757575", "index": 291, "step-1": "<mask token>\n\n\nclass Test(unittest.TestCase):\n <mask token>\n\n def test_take_comparison(self):\n x = np.arange(1000000.0)\n idx = np.random.random_integers(0, 100000.0, 1000000.0)\n indexing.take(x, i...
[ 5, 7, 8, 11, 12 ]
#!/usr/bin/python import gzip import os infiles = [] ids=[] ages=[] with open('all_C_metadata.txt') as f: f.readline() f.readline() for line in f: infiles.append(line.split('\t')[0]) ids.append(line.split('\t')[1]) ages.append(line.split('\t')[2]) with open('all_C_samples/diversi...
normal
{ "blob_id": "c02f46e8d89dd4b141c86df461ecbb8ed608b61b", "index": 7826, "step-1": " #!/usr/bin/python\n\nimport gzip\nimport os\n\ninfiles = []\nids=[]\nages=[]\nwith open('all_C_metadata.txt') as f:\n f.readline()\n f.readline()\n for line in f:\n infiles.append(line.split('\\t')[0])\n ids...
[ 0 ]
from get_info import parse_matches as pm def all_match_data(year): """ Searches through the parse_matches data for all games in a specific season prints them out with a game ID and returns the data in a list to the main program :param year: Specific format YYYY between 2008 - 2017 :return: year_ma...
normal
{ "blob_id": "bc53af24bb46d2be3122e290c4732b312f4ebdf5", "index": 5313, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef all_match_data(year):\n \"\"\"\n Searches through the parse_matches data for all games in a specific season prints them out with a game ID and\n returns the data in a lis...
[ 0, 1, 2, 3 ]
from datetime import datetime import whois def age_domain(url): try: w = whois.whois(url) if(w): for l in w.expiration_date: d1 = datetime.date(l) print(d1) for l1 in w.creation_date: d2 = datetime.date(l1) print(d2) diff = (d1 - ...
normal
{ "blob_id": "07d574060ded0d98734b4f184dcba7377b3a5480", "index": 685, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef age_domain(url):\n try:\n w = whois.whois(url)\n if w:\n for l in w.expiration_date:\n d1 = datetime.date(l)\n print(d1)\n ...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- "Widget for exporting the data" import asyncio from pathlib import Path from typing import List from bokeh.models import Div, CustomAction, CustomJS from view.dialog import FileDialog from utils.gui import startfile class ...
normal
{ "blob_id": "d120172e65f329b1137df38b693e5fe7145bc80d", "index": 2840, "step-1": "<mask token>\n\n\nclass CSVExporter:\n <mask token>\n <mask token>\n\n def reset(self, *_):\n \"\"\"reset all\"\"\"\n\n @staticmethod\n async def _run(dlg: SaveFileDialog, mainview, ctrl, doc):\n paths ...
[ 2, 7, 8, 9, 10 ]
# -*- coding: utf-8 -*- #!/bin/python3 import websocket import json import time from loraCrypto import LoRaCrypto from binascii import hexlify ''' 没有加密的数据 { cmd: 'tx'; EUI: string; port: number; data: string } 加密的数据 { cmd: 'tx'; EUI: string; port: number; encdata: string; seqno: number; } ''' GATEWAY_ID = "...
normal
{ "blob_id": "3683b1f799fa315d736e4b62c9c093360afa893f", "index": 2052, "step-1": "# -*- coding: utf-8 -*-\n#!/bin/python3\nimport websocket\nimport json\nimport time\nfrom loraCrypto import LoRaCrypto\nfrom binascii import hexlify\n\n'''\n没有加密的数据\n{\n\tcmd: 'tx';\n\tEUI: string;\n\tport: number;\n\tdata: string\...
[ 0 ]
import math from historia.utils import unique_id, position_in_range from historia.pops.models.inventory import Inventory from historia.economy.enums.resource import Good, NaturalResource from historia.economy.enums.order_type import OrderType from historia.economy.models.price_range import PriceRange from historia.econ...
normal
{ "blob_id": "887a39f1eeb81e6472938c2451e57866d3ac4a45", "index": 661, "step-1": "<mask token>\n\n\nclass Pop(object):\n <mask token>\n\n def __init__(self, province, pop_job, population):\n \"\"\"\n Creates a new Pop.\n manager (Historia)\n province (SecondaryDivision)\n ...
[ 15, 26, 28, 32, 33 ]
import torch from torchvision import datasets, transforms import numpy as np import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from PIL import Image import requests from io import BytesIO from net import Net class predict_guitar(): def __init__(self): """Model is lo...
normal
{ "blob_id": "8743be809953f59bd14431e509042c4c51d9fab4", "index": 4175, "step-1": "<mask token>\n\n\nclass predict_guitar:\n <mask token>\n\n def softmax(self, vector):\n \"\"\"Softmax function for calculating probs\"\"\"\n e = np.exp(vector)\n return e / e.sum()\n <mask token>\n", ...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python import sys def solve(n, k): wrap = 2 ** n snaps_that_matter = k % wrap return snaps_that_matter == wrap - 1 def main(): lines = sys.stdin.readlines() T = int(lines[0]) for i, line in enumerate(lines[1:]): N, K = line.split(' ') on = solve(int(N), int...
normal
{ "blob_id": "1803f634c8e833f4a92ae35bcfafb04dfd1d2305", "index": 7661, "step-1": "#!/usr/bin/env python\n\nimport sys\n\ndef solve(n, k):\n wrap = 2 ** n\n snaps_that_matter = k % wrap\n return snaps_that_matter == wrap - 1\n\ndef main():\n lines = sys.stdin.readlines()\n T = int(lines[0])\n \n...
[ 0 ]
# -*- coding: utf-8 -*- """ Created on Fri Nov 2 16:07:25 2018 @author: Yigao """ import re from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from wordcloud import WordCloud import matplotlib.pyplot as plt ## create a tokenizer hfilename = "file.txt" linecount=0 hashcount=0 wordcount=0 BagO...
normal
{ "blob_id": "fd04f6f4a03fdbe40e400d04e5759ef9ef30f974", "index": 6634, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open(hfilename, 'r') as file:\n for line in file:\n tweetSplitter = TweetTokenizer(strip_handles=True, reduce_len=True)\n WordList = tweetSplitter.tokenize(line)\n ...
[ 0, 1, 2, 3, 4 ]
from time import perf_counter_ns from anthony.utility.distance import compare, compare_info from icecream import ic start = perf_counter_ns() ic(compare("tranpsosed", "transposed")) print(f"Example Time: {(perf_counter_ns() - start)/1e+9} Seconds") ic(compare_info("momther", "mother"))
normal
{ "blob_id": "98b0e42f3ed1a234f63c4d3aa76ceb9fce7c041d", "index": 3631, "step-1": "<mask token>\n", "step-2": "<mask token>\nic(compare('tranpsosed', 'transposed'))\nprint(f'Example Time: {(perf_counter_ns() - start) / 1000000000.0} Seconds')\nic(compare_info('momther', 'mother'))\n", "step-3": "<mask token>...
[ 0, 1, 2, 3, 4 ]
# This file is Copyright (c) 2020 LambdaConcept <contact@lambdaconcept.com> # License: BSD from math import log2 from nmigen import * from nmigen.utils import log2_int from nmigen_soc import wishbone from nmigen_soc.memory import MemoryMap from lambdasoc.periph import Peripheral class gramWishbone(Peripheral, Elab...
normal
{ "blob_id": "3775ba538d6fab13e35e2f0761a1cacbe087f339", "index": 4723, "step-1": "<mask token>\n\n\nclass gramWishbone(Peripheral, Elaboratable):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass gramWishbone(Peripheral, Elaboratable):\n\n def __init__(self, core, data_width=32, gra...
[ 1, 2, 3, 4, 5 ]
""" Test the OOD-detection capabilities of models by scaling a random feature for all sample in the data set. """ # STD import os import pickle from copy import deepcopy from collections import defaultdict import argparse from typing import Tuple, Dict, List # EXT import numpy as np from tqdm import tqdm import torch...
normal
{ "blob_id": "bf3e7f1aa9fd20b69e751da9ac8970c88b1144eb", "index": 9363, "step-1": "<mask token>\n\n\ndef run_perturbation_experiment(nov_an: NoveltyAnalyzer, X_test: np.ndarray,\n scoring_func: str=None) ->Tuple[Dict[str, List[float]], Dict[str, List[\n float]]]:\n \"\"\"Runs the perturbation experiment ...
[ 1, 2, 3, 4, 5 ]
# # * Python 57, Correct Lineup # * Easy # * For the opening ceremony of the upcoming sports event an even number of # * athletes were picked. They formed a correct lineup, i.e. such a lineup in # * which no two boys or two girls stand together. The first person in the lineup # * was a girl. As a part of the perfor...
normal
{ "blob_id": "6c5f60e7a122e3da5e6705bfacf73a361f6c1362", "index": 1120, "step-1": "def correctLineup1(athletes: list) ->list:\n return [(athletes[i + 1] if i % 2 == 0 else athletes[i - 1]) for i in\n range(len(athletes))]\n\n\n<mask token>\n", "step-2": "def correctLineup1(athletes: list) ->list:\n ...
[ 1, 2, 3, 4, 5 ]
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header class SENDMAIL(object): def __init__(self): self.smtpserver = 'smtp.qq.com' self.username = 'wu_chang_hao@qq.com' # 比如QQ邮箱 self.password = 'xxxxxxxxx...
normal
{ "blob_id": "bcab83e0ae6ee4925393b50bdefdfeb85c42ad2c", "index": 1914, "step-1": "<mask token>\n\n\nclass SENDMAIL(object):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SENDMAIL(object):\n\n def __init__(self):\n self.smtpserver = 'smtp.qq.com'\n ...
[ 1, 3, 4, 5, 6 ]
from MyFeistel import MyFeistel, LengthPreservingCipher import pytest import base64 import os class TestMyFeistel: def test_Functionality(self): key = base64.urlsafe_b64encode(os.urandom(16)) feistel = MyFeistel(key, 10) # decrypt(encrypt(msg)) == msg for i in xrange(20): ...
normal
{ "blob_id": "2464da1c4d2ddab3a053f0a14e3cc9a8beabe031", "index": 6031, "step-1": "<mask token>\n\n\nclass TestLengthPreservingCipher:\n\n def test_Functionality(self):\n key = base64.urlsafe_b64encode(os.urandom(16))\n lpc = LengthPreservingCipher(key, 10)\n for i in xrange(20):\n ...
[ 2, 4, 5, 6, 7 ]
# Copyright (c) 2011-2014 by California Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice,...
normal
{ "blob_id": "707c83bc83f606b570af973094574e6675cfc83f", "index": 8793, "step-1": "<mask token>\n\n\nclass Ridge(object):\n \"\"\"A ridge.\n\n Attributes:\n\n - `E_r`: Equality set of a facet\n\n - `ar, br`: Affine hull of the facet\n s.t. P_{E_0} = P intersection {x | ar x = br}.\n \"\"\"\n\n...
[ 7, 9, 16, 18, 20 ]
#!/usr/bin/env pytest # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: TopJSON driver test suite. # Author: Even Rouault # ############################################################################### # Copyr...
normal
{ "blob_id": "270dba92af583e37c35ed5365f764adfdc2f947d", "index": 2112, "step-1": "<mask token>\n\n\ndef test_ogr_toposjon_objects_is_dict():\n ds = ogr.Open('data/topojson/topojson2.topojson')\n lyr = ds.GetLayer(0)\n assert lyr.GetName() == 'a_layer'\n assert lyr.GetLayerDefn().GetFieldCount() == 2\...
[ 1, 2, 3, 4, 5 ]
import torch import tarfile import pickle import pandas import json import argparse from pathlib import Path import numpy as np import shutil from shutil import copyfile import os import re import pandas as pd import sys from numpy import asarray from numpy import savetxt sys.path.append("..") def parse_arguments(): ...
normal
{ "blob_id": "da55d9a6534525e58b6c1d2db997e90a1c9b0f36", "index": 1427, "step-1": "<mask token>\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, required=True, help=\n 'dir holding sequences as separate files')\n parser.add_argument('--...
[ 2, 3, 4, 5, 6 ]
# coding: utf-8 from django.test.client import Client from django.contrib.contenttypes.models import ContentType from main.models import Descriptor, ResourceThematic, ThematicArea from utils.tests import BaseTestCase from models import * def minimal_form_data(): ''' Define a minimal fields for submit a medi...
normal
{ "blob_id": "a253ab5ef80a61c3784862625cde81de4c4ef984", "index": 2094, "step-1": "<mask token>\n\n\nclass MultimediaTest(BaseTestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def test_add_media(self):\n \"\"\"\n Tests create media\n \"\"\"\n self.login_editor()\n...
[ 8, 9, 12, 14, 16 ]
from flask import render_template, url_for, escape, redirect, abort from app import core from database import db @core.route('/post') @core.route('/categorie') @core.route('/tag') def returnToHome(): return redirect(url_for('home'))
normal
{ "blob_id": "c27d6279d1ea84bab3c0abd4ca9a08de202219da", "index": 1748, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@core.route('/post')\n@core.route('/categorie')\n@core.route('/tag')\ndef returnToHome():\n return redirect(url_for('home'))\n", "step-3": "from flask import render_template, url...
[ 0, 1, 2 ]
import logging from sleekxmpp import ClientXMPP from sleekxmpp.exceptions import IqError, IqTimeout class EchoBot(ClientXMPP): def __init__(self, jid, password): ClientXMPP.__init__(self, jid, password) self.add_event_handler("session_start", self.session_start) self.register_plugin('xep_0...
normal
{ "blob_id": "3b531c5935f0be89536c95ff471f96b4249d951c", "index": 2521, "step-1": "<mask token>\n\n\nclass EchoBot(ClientXMPP):\n\n def __init__(self, jid, password):\n ClientXMPP.__init__(self, jid, password)\n self.add_event_handler('session_start', self.session_start)\n self.register_pl...
[ 2, 3, 4, 5, 6 ]
# 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다. # 1. 주식 하나를 산다. # 2. 원하는 만큼 가지고 있는 주식을 판다. # 3. 아무것도 안한다. # 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게 날 별로 주식의 가격을 알려주었을 때, 최대 이익이 얼마나 되는지 계산을 해달라고 부탁했다. # 예를 들어 날 수가 3일이고 날 별로 주가가 10, 7, 6일 때, 주...
normal
{ "blob_id": "d3f6fb612e314ee2b86f6218719ecac2cc642c59", "index": 2992, "step-1": "# 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다.\n\n# 1. 주식 하나를 산다.\n# 2. 원하는 만큼 가지고 있는 주식을 판다.\n# 3. 아무것도 안한다.\n\n# 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게...
[ 1 ]
import gdalnumeric #Input File src = "../dati/islands/islands.tif" #Output tgt = "../dati/islands/islands_classified.jpg" srcArr = gdalnumeric.LoadFile(src) classes = gdalnumeric.numpy.histogram(srcArr,bins=2)[1] print classes #Color look-up table (LUT) - must be len(classes)+1. #Specified as R,G,B tuples lut = [[...
normal
{ "blob_id": "f29d377e8a8fd6d2e156da665478d7a4c167f7d5", "index": 3601, "step-1": "import gdalnumeric\n\n#Input File\nsrc = \"../dati/islands/islands.tif\"\n\n#Output\ntgt = \"../dati/islands/islands_classified.jpg\"\n\nsrcArr = gdalnumeric.LoadFile(src)\n\nclasses = gdalnumeric.numpy.histogram(srcArr,bins=2)[1]\...
[ 0 ]
# Copyright (c) 2008-2016 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test the `interpolation` module.""" from __future__ import division import logging import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_eq...
normal
{ "blob_id": "9e987e057ee5322765415b84e84ef3c4d2827742", "index": 5466, "step-1": "<mask token>\n\n\n@pytest.fixture()\ndef test_data():\n \"\"\"Return data used for tests in this file.\"\"\"\n x = np.array([8, 67, 79, 10, 52, 53, 98, 34, 15, 58], dtype=float)\n y = np.array([24, 87, 48, 94, 98, 66, 14, ...
[ 7, 9, 10, 11, 13 ]
class cal4: def setdata(self,n1): self.n1 = n1 def display(self): return n1*n1 n1 = int(input("Enter number: ")) c = cal4() print(c.display())
normal
{ "blob_id": "65b90fccd0ee74b369475aa9fe33f159881c8b82", "index": 6645, "step-1": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n <mask token>\n\n\n<mask token>\n", "step-2": "class cal4:\n\n def setdata(self, n1):\n self.n1 = n1\n\n def display(self):\n return n1 * n1\...
[ 2, 3, 4, 5, 6 ]
import pytest from ansiblediscover.graph.node import Node def test_build_identifier(): assert 'role:server_base' == Node.build_identifier('server_base', 'role') def test_identifier(): node = Node('server_base', 'role', 'irrelevant') assert 'role:server_base' == node.identifier() def test_add_successo...
normal
{ "blob_id": "8e22db940124f92d3048055cf72dcaa79564cdc6", "index": 1953, "step-1": "<mask token>\n\n\ndef test_build_identifier():\n assert 'role:server_base' == Node.build_identifier('server_base', 'role')\n\n\ndef test_identifier():\n node = Node('server_base', 'role', 'irrelevant')\n assert 'role:serve...
[ 5, 6, 7, 8, 9 ]
# Кицела Каролина ИВТ 3 курс # Вариант 6 # Найти сумму всех чисел с плавающей точкой b = ("name", " DeLorean DMC-12", "motor_pos", "rear", "n_of_wheels", 4, "n_of_passengers", 2, "weight", 1.230, "height", 1.140, "length", 4.216, "width", 1.857, "max_speed", 177) print sum(b[9:16:2])
normal
{ "blob_id": "b5160a2574dd2c4eec542d7aca8288da0feadaba", "index": 5702, "step-1": "# Кицела Каролина ИВТ 3 курс \n# Вариант 6 \n# Найти сумму всех чисел с плавающей точкой\n\nb = (\"name\",\t\"\tDeLorean\tDMC-12\",\t\"motor_pos\",\t\"rear\",\t\"n_of_wheels\",\t4,\n\"n_of_passengers\",\t2,\t\"weight\",\t1.230,\t\...
[ 0 ]
import random import json import os from pico2d import * import game_framework import game_world import menu_world import game_state from Start_menu import Menu name = "MenuState" boy = None Start_menu = None menu_time =None def enter(): global Start_menu Start_menu = Menu() menu_world.add_object(Start...
normal
{ "blob_id": "fee2ddca5888c9db00d2d7a4fe11ba20c4e31685", "index": 1909, "step-1": "<mask token>\n\n\ndef enter():\n global Start_menu\n Start_menu = Menu()\n menu_world.add_object(Start_menu, 0)\n\n\n<mask token>\n\n\ndef handle_events():\n global Start_menu, menu_time\n events = get_events()\n ...
[ 4, 6, 7, 8, 10 ]
from unittest import TestCase from attendance import Member __author__ = 'colin' class TestMember(TestCase): def test_here(self): member = Member("John", "Doe") self.assertFalse(member.attended) member.here() self.assertTrue(member.attended)
normal
{ "blob_id": "a6713a4edece14a88bd9c8ddd483ff8e16acdbcc", "index": 9695, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TestMember(TestCase):\n\n def test_here(self):\n member = Member('John', 'Doe')\n self.assertFalse(member.attended)\n member.here()\n self.assertT...
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/env python3 import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import torchmetrics class BaselineModule(pl.LightningModule): def __init__(self, input_size, num_classes=4, lr=3e-4): super().__init__() self.backbone = nn.Sequential( # CBR-Ti...
normal
{ "blob_id": "7d43b20ebee2f4cd509bbd896c9e6ae8b2c4b354", "index": 7128, "step-1": "<mask token>\n\n\nclass BaselineModule(pl.LightningModule):\n <mask token>\n\n def _get_hidden_size(self, input_size):\n self.backbone(torch.randn(1, 3, input_size, input_size))\n\n def forward(self, input_tensor):\...
[ 3, 5, 6, 7, 9 ]
## Import modules import matplotlib, sys, datetime, time matplotlib.use('TkAgg') from math import * from numpy import * from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib import dates import matplotlib.pyplot as plt from Tkinter ...
normal
{ "blob_id": "2de12085ddc73fed85dda8ce3d6908b42fdc4bcc", "index": 3046, "step-1": "<mask token>\n\n\ndef show_humidity():\n a.clear()\n a.plot(fds, humidity, 'b.--')\n a.set_ylabel('Humidity %', color='b')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='blue')\n for tick in a.xaxis.get_major...
[ 2, 3, 5, 6, 7 ]
import numpy as np import matplotlib.pyplot as plt import sys import os from azavg_util import plot_azav from binormalized_cbar import MidpointNormalize from diagnostic_reading import ReferenceState dirname = sys.argv[1] datadir = dirname + '/data/' plotdir = dirname + '/plots/' if (not os.path.isdir(plotdir)): ...
normal
{ "blob_id": "e5c30488c8c1682171c57a11a8ecedc5ccd4d851", "index": 5607, "step-1": "<mask token>\n", "step-2": "<mask token>\nif not os.path.isdir(plotdir):\n os.makedirs(plotdir)\n<mask token>\nplot_azav(fig, ax, ro_m, rr, cost, sint, contours=False, notfloat=False,\n units='')\nplt.title('$({\\\\rm{Ro}}_...
[ 0, 1, 2, 3, 4 ]
# i change it for change1 # change 1.py in master i = 1 # fix bug for boss
normal
{ "blob_id": "92f4f1c8a4e04b07ed7c05d5bb733c0b9c28bd05", "index": 5325, "step-1": "<mask token>\n", "step-2": "i = 1\n", "step-3": "# i change it for change1\n# change 1.py in master\ni = 1\n# fix bug for boss\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import, unicode_literals import os from qtpy.QtCore import * # from qtpy.QtGui import * from qtpy.QtWidgets import * from six import string_types from ..widgets import PathParamWidget, RelPathParamWidget, FilePath...
normal
{ "blob_id": "ee91e8c9dcb940882733b2d23b74a76d0392f4fe", "index": 2126, "step-1": "<mask token>\n\n\nclass TypeDirPath(TypeBase):\n\n @classmethod\n def control(cls, delegate, property_item, parent):\n return PathParamWidget(delegate, parent=parent)\n <mask token>\n\n @classmethod\n def valu...
[ 21, 41, 43, 45, 61 ]
import time import optparse from IPy import IP as IPTEST ttlValues = {} THRESH = 5 def checkTTL(ipsrc,ttl): if IPTEST(ipsrc).iptype() == 'PRIVATE': return if not ttlValues.has_key(ipsrc): pkt = srl(IP(dst=ipsrc) / TCMP(),retry=0,timeout=0,verbose=0) ttlValues[ipsrc] = pkt.ttl ...
normal
{ "blob_id": "7081211336793bfde60b5c922f6ab9461a475949", "index": 1616, "step-1": "import time\r\nimport optparse\r\nfrom IPy import IP as IPTEST\r\nttlValues = {}\r\nTHRESH = 5\r\ndef checkTTL(ipsrc,ttl):\r\n if IPTEST(ipsrc).iptype() == 'PRIVATE':\r\n return\r\n if not ttlValues.has_key(ipsrc):\r\n...
[ 0 ]
import pygame from Actor import Actor import PlayerInput class TestActor(Actor): def __init__(self): super(TestActor, self).__init__() def act(self): self.key_commands() def key_commands(self): if PlayerInput.is_key_down(pygame.K_LEFT): self.set_location(self.x - 1, ...
normal
{ "blob_id": "9cb11c2bf032aa16abd3463ecdb8997addedc912", "index": 1570, "step-1": "<mask token>\n\n\nclass TestActor(Actor):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestActor(Actor):\n <mask token>\n\n def act(self):\n self.key_commands()\n <m...
[ 1, 2, 3, 4, 5 ]
''' Created on Jul 10, 2018 @author: daniel ''' #from multiprocessing import Process, Manager #from keras.utils import np_utils import sys import os from keras.utils import np_utils from _codecs import decode sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from DataHandlers.SegNetDataHandler import Seg...
normal
{ "blob_id": "cb03fcf9c9cb61b3546865fe40cc411745e1fc94", "index": 6872, "step-1": "<mask token>\n\n\ndef computeDice(im1, im2):\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n if im1.shape != im2.shape:\n raise ValueError(\n 'Shape mismatch: im1 and im2...
[ 2, 3, 4, 5, 6 ]
"""script for subpixel experiment (not tested) """ import numpy as np from tqdm import tqdm import logging from pathlib import Path import paddle import paddle.optimizer import paddle.io from utils.loader import dataLoader from utils.loader import modelLoader from utils.loader import pretrainedLoader from utils.tools...
normal
{ "blob_id": "fc89fdf17f887ea398be5b36d4d6f0444d64b3e0", "index": 8026, "step-1": "<mask token>\n\n\n@paddle.no_grad()\nclass Val_model_subpixel(object):\n <mask token>\n\n def loadModel(self):\n from utils.loader import modelLoader\n self.net = modelLoader(model=self.model, **self.params)\n ...
[ 3, 5, 6, 7, 8 ]
from faker import Faker from generators.uniform_distribution_gen import UniformDistributionGen from generators.random_relation_gen import RandomRelationGen from base.field_base import FieldBase from generators.normal_distribution_gen import NormalDistributionGen from generators.first_name_generator import FirstNameGene...
normal
{ "blob_id": "0926606a222e1277935a48ba7f0ea886fb4e298a", "index": 5234, "step-1": "<mask token>\n\n\nclass A:\n <mask token>\n\n\nclass B:\n\n def __init__(self) ->None:\n self.alpha: str = ''\n self.C: C = None\n\n\nclass C:\n\n def __init__(self) ->None:\n self.alpha: str = ''\n ...
[ 5, 6, 7, 8, 9 ]
import utils from problems_2019 import intcode def run(commands=None): memory = utils.get_input()[0] initial_inputs = intcode.commands_to_input(commands or []) program = intcode.Program(memory, initial_inputs=initial_inputs, output_mode=intcode.OutputMode.BUFFER) while True: _, return_signal...
normal
{ "blob_id": "e3aa38b5d01823ed27bca65331e9c7315238750a", "index": 8974, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@utils.part\ndef part_1():\n commands = ['south', 'take food ration', 'west', 'north', 'north',\n 'east', 'take astrolabe', 'west', 'south', 'south', 'east', 'north',\n ...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 import argparse import boutvecma import easyvvuq as uq import chaospy import os import numpy as np import time from dask.distributed import Client from dask_jobqueue import SLURMCluster import matplotlib.pyplot as plt if __name__ == "__main__": parser = argparse.ArgumentParser(description...
normal
{ "blob_id": "416f4c6bbd2f2b9562ab2d1477df4ebc45070d8d", "index": 5060, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='EasyVVUQ applied to BOUT++')\n parser.add_argument('--batch', '-b', help=\n 'Run on a batch (SLURM)...
[ 0, 1, 2, 3 ]
import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from pathlib import Path from scipy.io import loadmat from skimage.transform import resize from sklearn....
normal
{ "blob_id": "5c315a49ead80e8d8ce057bd774f97bce098de59", "index": 5443, "step-1": "<mask token>\n\n\ndef model(input_shape):\n X_input = Input(input_shape)\n X = Conv2D(8, (4, 4), strides=(1, 1), name='conv0', kernel_regularizer=\n regularizers.l2(0.001), padding='same')(X_input)\n X = BatchNormal...
[ 1, 2, 3, 4, 5 ]
import sys import os.path root_dir = os.path.dirname(os.path.dirname(__file__)) jsondb_dir = os.path.join(root_dir, 'jsondb') sys.path.append(jsondb_dir)
normal
{ "blob_id": "eeb588a162fa222c0f70eb832a0026d0d8adbe9b", "index": 6769, "step-1": "<mask token>\n", "step-2": "<mask token>\nsys.path.append(jsondb_dir)\n", "step-3": "<mask token>\nroot_dir = os.path.dirname(os.path.dirname(__file__))\njsondb_dir = os.path.join(root_dir, 'jsondb')\nsys.path.append(jsondb_dir...
[ 0, 1, 2, 3 ]
from .ros_publisher import *
normal
{ "blob_id": "6e7cca4f766ca89d2e2f82a73f22742b0e8f92a8", "index": 5870, "step-1": "<mask token>\n", "step-2": "from .ros_publisher import *\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ One cycle policy based on Leslie Smith's paper(https://arxiv.org/pdf/1803.09820.pdf) Created on Wed Mar 31 13:53:39 2021 """ import logging import numpy as np import tensorflow as tf import matplotlib.pyplot as plt logging.getLogger('tensorflow').setLevel(logging.ERR...
normal
{ "blob_id": "056235f8f65a3d6a310ee8a8742c1369b5398f28", "index": 7749, "step-1": "<mask token>\n\n\nclass OneCycleScheduler(Callback):\n <mask token>\n\n def __init__(self, lr_max, steps, mom_min=0.85, mom_max=0.95,\n phase_1_pct=0.3, div_factor=25.0):\n super(OneCycleScheduler, self).__init_...
[ 7, 11, 15, 16, 19 ]
from django.conf.urls import url from . import views from .views import ShopView, ShopListView urlpatterns = [ url(r'^coffeeshops/(\d+)$', ShopView.as_view()), url(r'^coffeeshops$', ShopListView.as_view()), ]
normal
{ "blob_id": "54a705de2597140a72e47f5afe86614b619461b7", "index": 1109, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [url('^coffeeshops/(\\\\d+)$', ShopView.as_view()), url(\n '^coffeeshops$', ShopListView.as_view())]\n", "step-3": "from django.conf.urls import url\nfrom . import view...
[ 0, 1, 2, 3 ]
import numpy as np import torch def pad_sequences_1d(sequences, dtype=torch.long, device=torch.device("cpu"), fixed_length=None): """ Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray) into a (n+1)-d array, only allow the first dim has variable lengths. Args: sequence...
normal
{ "blob_id": "788d9fa03c4311a8077d492b1a2b06d1f88826a3", "index": 5570, "step-1": "<mask token>\n\n\ndef pad_sequences_1d(sequences, dtype=torch.long, device=torch.device('cpu'\n ), fixed_length=None):\n \"\"\" Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray)\n into a (n+1...
[ 3, 4, 5, 6, 7 ]
""" time: X * Y space: worst case X * Y """ class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 Y = len(grid) X = len(grid[0]) def dfs(y, x): if y < 0 or x < 0 or y > Y-1 or x > X-1: ...
normal
{ "blob_id": "58bd14d240242ed58dcff35fe91cebeae4899478", "index": 9087, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def numIslands(self, grid: List[List[str]]) ->int:\n if not grid:\...
[ 0, 1, 2, 3, 4 ]
from job_description import JobDescription from resume import Resume from resume_manager import ResumeManager
normal
{ "blob_id": "a998433e45c1d5135749c5164e8ec1f2eb0e572a", "index": 1693, "step-1": "<mask token>\n", "step-2": "from job_description import JobDescription\nfrom resume import Resume\nfrom resume_manager import ResumeManager\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ...
[ 0, 1 ]
from ctypes import * class GF_IPMPX_Data(Structure): _fields_=[ ("tag", c_char), ("Version", c_char), ("dataID", c_char) ]
normal
{ "blob_id": "b3f4815495c781fe6cc15f77b4ee601680117419", "index": 8592, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass GF_IPMPX_Data(Structure):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass GF_IPMPX_Data(Structure):\n _fields_ = [('tag', c_char), ('Version', c_char), ('dataID', ...
[ 0, 1, 2, 3, 4 ]
list = [3, 1, 2, 5, 4, 7, 6] def sort(list): for i in range(len(list) - 1): if list[i] > list[i + 1]: a = list[i] list[i] = list[i + 1] list[i + 1] = a print(list) sort(list)
normal
{ "blob_id": "219929d52b5f1a0690590e83b41d2b4f0b2b3a51", "index": 336, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sort(list):\n for i in range(len(list) - 1):\n if list[i] > list[i + 1]:\n a = list[i]\n list[i] = list[i + 1]\n list[i + 1] = a\n ...
[ 0, 1, 2, 3 ]
import subprocess import datetime def ping_address(host,n): ping = subprocess.Popen( ["ping","-c",str(n),host], stdout = subprocess.PIPE, stderr = subprocess.PIPE) out,error = ping.communicate() return out, error def ping_address_windows(host,n): ping = subprocess.Popen( ["...
normal
{ "blob_id": "3f2221f5f3a699020dd5986acb793e3083976dff", "index": 7176, "step-1": "<mask token>\n\n\ndef parse_msg(msg):\n line_org = msg.split('\\n')\n N = len(line_org) - 2\n line = line_org[N]\n return line\n\n\ndef get_vals(msg):\n rhs = msg.split('=')\n try:\n nums = rhs[1].split('/'...
[ 4, 5, 6, 7, 8 ]
from typing import List from pydantic import BaseModel class BinBase(BaseModel): name: str = None title: str = None class BinCreate(BinBase): owner_id: int password: str class Bin(BinBase): id: int # TODO: token? class Config(): orm_mode = True class UserBase(BaseModel): ...
normal
{ "blob_id": "1c0f194bbdc6f7e3e4feb114e521aa958f11e83e", "index": 3263, "step-1": "<mask token>\n\n\nclass UserCreate(UserBase):\n password: str\n\n\nclass User(UserBase):\n id: int\n\n\n class Config:\n orm_mode = True\n", "step-2": "<mask token>\n\n\nclass BinCreate(BinBase):\n owner_id: in...
[ 2, 5, 6, 7, 8 ]
from django.db import models class Category(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: verbose_name = 'Categoria' class Books(models.Model): name = model...
normal
{ "blob_id": "0584ff5cb252fba0fe1fc350a5fb023ab5cbb02b", "index": 6750, "step-1": "<mask token>\n\n\nclass Student(models.Model):\n name = models.CharField(max_length=70)\n cpf = models.CharField(max_length=14)\n birth_date = models.DateField()\n city = models.CharField(max_length=50)\n registratio...
[ 3, 7, 8, 9, 11 ]
import pandas as pd import os """ This code relies heavily on the form of the data. Namely it will fail if the authors of the same book are not comma separated. It will also be inaccurate or even fail if the same author for different books is not spelt in exactly the same way. """ loc = r'C:\Users\james\OneDrive\Do...
normal
{ "blob_id": "f57490c8f4a5ba76824c3b41eb18905eb2213c23", "index": 5107, "step-1": "<mask token>\n\n\ndef split(string):\n \"\"\"\n Function takes input of a string and returns an array of strings\n the original string should be comma separated with a space after\n the comma in order for this function ...
[ 1, 2, 3, 4, 5 ]
import re from mapa import graficar_lista, graficar_matriz class nodo: def __init__(self, x, y, n, c): self.columna = x self.fila = y self.nombre = n self.color = c pattern_matriz = r"[M|m][A|a][T|t][R|r][I|i][Z|z]\s*\(.*,.*,.*,.*,.*\)\{" pattern_fila = r"[F|f][I|i][L|l][A|a]\s*\(...
normal
{ "blob_id": "70373c74e459efb2a310d94ae906910423e8bfd4", "index": 6631, "step-1": "<mask token>\n\n\nclass nodo:\n\n def __init__(self, x, y, n, c):\n self.columna = x\n self.fila = y\n self.nombre = n\n self.color = c\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass nodo:...
[ 2, 3, 4, 5, 6 ]
#! /usr/bin/env python3 import EchooFunctions, cgi, MySQLdb, hashlib, time, requests, os print ('Content-type: text/html\n') form = cgi.FieldStorage() #database connection user = "i494f18_team34" db_pass = "my+sql=i494f18_team34" db_con = MySQLdb.connect(host="db.soic.indiana.edu", port = 3306, user=user, passwd=db_...
normal
{ "blob_id": "dc88686d3cbb4223b4de6847bf4fc29b93054b00", "index": 495, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Content-type: text/html\\n')\n<mask token>\nif 'echooUser' in str(os.environ):\n userName = EchooFunctions.getUserName()\n userName = userName[0]\n userID = EchooFunctions....
[ 0, 1, 2, 3, 4 ]
from .models import RecommendedArtifact from .serializers import RecommendedArtifactSerialize from rest_framework.decorators import api_view from rest_framework.response import Response from datetime import datetime import requests, bs4 # constant value service_key = "{jo's museum key}" @api_view(['GET']) def artifa...
normal
{ "blob_id": "707e3e60d6d9a3db5b9bc733e912b34e2cec5974", "index": 8585, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@api_view(['GET'])\ndef artifact_save_recommend(request, pageNo):\n artifact_url = (\n f'http://www.emuseum.go.kr/openapi/relic/list?serviceKey={service_key}&numOfRows=100&p...
[ 0, 2, 3, 4, 5 ]
from pydis.datastruct.sds import SdsImp class RPCStub(object): def __init__(self): pass def SET(self, key, value): self print("{}: {}".format(key, value))
normal
{ "blob_id": "74f85732b4e1f4ef2b82a48818cbaedb18a56083", "index": 8122, "step-1": "<mask token>\n\n\nclass RPCStub(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass RPCStub(object):\n\n def __init__(self):\n pass\n <mask token>\n", "step-3": "<mask token>\n\n\ncl...
[ 1, 2, 3, 4, 5 ]