code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
# -*- coding: utf-8 -*- file1 = raw_input("Enter the path of your first file: ") file2 = raw_input("Enter the path of your second file: ") Basex = open(file1).read().split() Basey = open(file2).read().split() if Basex != Basey: print("The files are different!") else: print("The files are the same!")
normal
{ "blob_id": "661d82adc7d0746635fb57abf6d0e70ee615ada4", "index": 5974, "step-1": "<mask token>\n", "step-2": "<mask token>\nif Basex != Basey:\n print('The files are different!')\nelse:\n print('The files are the same!')\n", "step-3": "file1 = raw_input('Enter the path of your first file: ')\nfile2 = r...
[ 0, 1, 2, 3 ]
import sys sys.stdin = open('줄긋기.txt') T = int(input()) for tc in range(1, T + 1): N = int(input()) dot = [list(map(int, input().split())) for _ in range(N)] ran = [] for a in range(N - 1): for b in range(a + 1, N): if dot[a][1] - dot[b][1] == 0: if 'inf' not in ran: ...
normal
{ "blob_id": "03854f48751460fdc27d42ee5c766934ee356cfd", "index": 6161, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor tc in range(1, T + 1):\n N = int(input())\n dot = [list(map(int, input().split())) for _ in range(N)]\n ran = []\n for a in range(N - 1):\n for b in range(a + 1, N)...
[ 0, 1, 2, 3 ]
def drive(carspeed): if carspeed>200: print("very fast") elif carspeed>100: print("toofast") elif carspeed>70 and carspeed<80: print("optimal speed") else: print("below speed limit") print(drive(234)) print(drive(34)) drive(134) #how none will be removed? def compare(a): if a>11: print("big") elif a==1...
normal
{ "blob_id": "de3eaa5823fb396050527c148273c30bed6ce8ca", "index": 2644, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef compare(a):\n if a > 11:\n print('big')\n elif a == 10:\n print('reallybig')\n\n\n<mask token>\n", "step-3": "def drive(carspeed):\n if carspeed > 200:\n ...
[ 0, 1, 2, 3, 4 ]
# -*- coding=utf-8 -*- # ! /usr/bin/env python3 """ 抽奖活动-摇一摇活动 """ import time import allure from libs.selenium_libs.common.base import Base from libs.selenium_libs.page_object.page_activity import PageActivity from libs.selenium_libs.page_object.page_personal_center import PagePersonalCenter class LuckDrawActivity...
normal
{ "blob_id": "6b1970ee2b0d24504f4dea1f2ad22a165101bfbe", "index": 8958, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass LuckDrawActivity(Base):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass LuckDrawActivity(Base):\n\n @allure.step('参加抽奖活动')\n def join_luck_draw_activity(self, d...
[ 0, 1, 2, 3, 4 ]
#loadconc.py - possibly these classes will be added to ajustador/loader.py when ready # -*- coding:utf-8 -*- from __future__ import print_function, division import numpy as np from ajustador import xml,nrd_fitness import glob import os import operator msec_per_sec=1000 nM_per_uM=1000 nM_per_mM=1e6 class trace(ob...
normal
{ "blob_id": "20649decd3ff21b1aa814d0a04180195cac3629b", "index": 498, "step-1": "<mask token>\n\n\nclass CSV_conc(object):\n <mask token>\n <mask token>\n\n\nclass CSV_conc_set(object):\n\n def __init__(self, rootname, stim_time=0, features=[]):\n self.stim_time = stim_time * msec_per_sec\n ...
[ 3, 7, 8, 9, 10 ]
from flask import Flask, request from flask import jsonify from preprocessing import QueryProcessor from flask_cors import CORS app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] resul...
normal
{ "blob_id": "e582787a912f479830ed99575b2c6adb8088b4e5", "index": 257, "step-1": "<mask token>\n\n\n@app.route('/search_general', methods=['POST'])\ndef query():\n message = None\n searchQuery = request.json['searchQuery']\n result = qp.generateQuery(searchQuery)\n response = jsonify(result)\n resp...
[ 2, 3, 4, 5, 6 ]
#Write your function here def over_nine_thousand(lst): sum = 0 for number in lst: sum += number if (sum > 9000): break return sum #Uncomment the line below when your function is done print(over_nine_thousand([8000, 900, 120, 5000])) #9020
normal
{ "blob_id": "c2f39e33030cbe7c5d4827b47fb28d7604bdbc6d", "index": 8135, "step-1": "<mask token>\n", "step-2": "def over_nine_thousand(lst):\n sum = 0\n for number in lst:\n sum += number\n if sum > 9000:\n break\n return sum\n\n\n<mask token>\n", "step-3": "def over_nine_thou...
[ 0, 1, 2, 3 ]
import torch import util import numpy as np import argparse import losses args = argparse.Namespace() args.device = torch.device('cpu') args.num_mixtures = 20 args.init_mixture_logits = np.ones(args.num_mixtures) args.softmax_multiplier = 0.5 args.relaxed_one_hot = False args.temperature = None temp = np.arange(args....
normal
{ "blob_id": "8f558593e516aa4a769b7c5e1c95c8bc23a36420", "index": 1232, "step-1": "<mask token>\n\n\ndef get_grads_correct(seed):\n util.set_seed(seed)\n theta_grads_correct = []\n phi_grads_correct = []\n log_weight, log_q = losses.get_log_weight_and_log_q(generative_model,\n inference_network...
[ 5, 6, 8, 9, 10 ]
""" Primos <generadores> 30 pts Realice una generador que devuelva de todos lo numeros primos existentes de 0 hasta n-1 que cumpla con el siguiente prototipo: def gprimo(N): pass a = gprimo(10) z = [e for e in a] print(z) # [2, 3 ,5 ,7 ] """ def gprimo(nmax): for x in range(1,nmax): for i in ra...
normal
{ "blob_id": "732886306d949c4059b08e1bc46de3ad95ba56cb", "index": 1685, "step-1": "<mask token>\n\n\ndef gprimo(nmax):\n for x in range(1, nmax):\n for i in range(2, x):\n if x % i != 0:\n continue\n else:\n break\n else:\n yield x\n\...
[ 1, 2, 3, 4, 5 ]
# Cutting a Rod | DP-13 # Difficulty Level : Medium # Last Updated : 13 Nov, 2020 # Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is...
normal
{ "blob_id": "9cca73ebdf2b05fe29c14dc63ec1b1a7c917b085", "index": 6508, "step-1": "<mask token>\n\n\ndef cut_rod2(price, n):\n val = [(0) for x in range(n + 1)]\n val[0] = 0\n for i in range(1, n + 1):\n max_val = -1\n for j in range(i):\n max_val = max(max_val, price[j] + val[i ...
[ 2, 3, 4, 5, 7 ]
import rasterio as rio from affine import Affine colour_data = [] def generate_colour_data(width, height, imagiry_data, pixel2coord): """Extract color data from the .tiff file """ for i in range(1, height): for j in range(1, width): colour_data.append( [ ...
normal
{ "blob_id": "7e8b192e77e857f1907d5272d03c1138a10c61f4", "index": 4803, "step-1": "<mask token>\n\n\ndef generate_colour_data(width, height, imagiry_data, pixel2coord):\n \"\"\"Extract color data from the .tiff file \"\"\"\n for i in range(1, height):\n for j in range(1, width):\n colour_d...
[ 1, 2, 3, 4, 5 ]
""" Author: Yudong Qiu Functions for solving unrestricted Hartree-Fock """ import numpy as np from qc_python import basis_integrals from qc_python.common import chemical_elements, calc_nuclear_repulsion def solve_unrestricted_hartree_fock(elems, coords, basis_set, charge=0, spinmult=1, maxiter=150, enable_DIIS=True...
normal
{ "blob_id": "ccc2a976d06e2fa6c91b25c4f95a8f0da32e9b5e", "index": 7878, "step-1": "<mask token>\n\n\ndef DIIS_extrapolate_F(diis_err_mats, diis_fmats):\n n_diis = len(diis_err_mats)\n assert n_diis == len(diis_fmats\n ), 'Number of Fock matrices should equal to number of error matrices'\n Bmat = -...
[ 1, 2, 3, 4, 5 ]
import random from common.ast import * from mutate.mutate_ctrl import * def _check_parent_type(node, nodes, types): par = node while(nodes[par] != None): par = nodes[par] if type(par) in types: return True return False def mutate_operator(root, nodes, path): candidates = [...
normal
{ "blob_id": "c0524301a79788aa34a039fc46799021fb45362c", "index": 7141, "step-1": "<mask token>\n\n\ndef mutate_operator(root, nodes, path):\n candidates = [node for node in nodes.keys() if type(node) in OP_TYPES.\n keys() and _check_parent_type(node, nodes, OP_PARENT_TYPES)]\n if len(candidates) == ...
[ 3, 4, 5, 6, 7 ]
import pygame class SpriteObject(pygame.sprite.Sprite): def __init__(self, x, y, w, h, color): pygame.sprite.Sprite.__init__(self) self.angle = 0 self.original_image = pygame.Surface([w, h], pygame.SRCALPHA) self.original_image.fill(color) self.image = self.original_...
normal
{ "blob_id": "b90c6a3f8fe084bc2acc0b733750124a1387527c", "index": 1712, "step-1": "<mask token>\n\n\nclass SpriteObject(pygame.sprite.Sprite):\n <mask token>\n\n def update(self):\n self.rotate()\n\n def rotate(self):\n self.angle += 0.3\n self.image = pygame.transform.rotate(self.or...
[ 3, 4, 5, 6, 8 ]
# -*- coding: utf-8 -*- try: from greenlet import getcurrent as get_current_greenlet except ImportError: get_current_greenlet = int from thread import get_ident as get_current_thread from threading import Lock if get_current_greenlet is int: # Use thread get_ident = get_current_thread else: # Use gree...
normal
{ "blob_id": "f55b286448f114f3823f099a576af7bec1780a8c", "index": 461, "step-1": "<mask token>\n\n\nclass Local(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __delattr__(self, item):\n self.__lock__.acquire()\n try:\n try:\n ...
[ 8, 11, 12, 15, 16 ]
from collections import OrderedDict import torch from torch import nn, Tensor import warnings from typing import Tuple, List, Dict, Optional, Union class GeneralizedRCNN(nn.Module): def __init__(self, backbone, rpn, roi_heads, transform): super(GeneralizedRCNN, self).__init__() self.transform = t...
normal
{ "blob_id": "83ecb6b6237d7ee61f762b191ebc891521067a41", "index": 9206, "step-1": "<mask token>\n\n\nclass GeneralizedRCNN(nn.Module):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass GeneralizedRCNN(nn.Module):\n\n def __init__(self, backbone, rpn, roi_heads, transform):\n s...
[ 1, 2, 3, 4, 5 ]
""" Url router for the federated search application """ from django.conf.urls import include from django.urls import re_path urlpatterns = [ re_path(r"^rest/", include("core_federated_search_app.rest.urls")), ]
normal
{ "blob_id": "6903584b27c0720cebf42ed39968b18f0f67f796", "index": 6167, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [re_path('^rest/', include(\n 'core_federated_search_app.rest.urls'))]\n", "step-3": "<mask token>\nfrom django.conf.urls import include\nfrom django.urls import re_pat...
[ 0, 1, 2, 3 ]
import numpy as np import urllib2 from io import StringIO def demo_polyfit0(): x, y = np.loadtxt('stock.txt', unpack=True) print '-'.join(map(str, np.polyfit(x, y, 1))) def demo_polyfit1(): d = urllib2.urlopen("http://www.qlcoder.com/download/145622513871043.txt").read().decode("utf-8") print d ...
normal
{ "blob_id": "61571ba9f647f430879b9fa5db884ec4c93c334f", "index": 9659, "step-1": "import numpy as np\nimport urllib2\nfrom io import StringIO\n\n\ndef demo_polyfit0():\n x, y = np.loadtxt('stock.txt', unpack=True)\n print '-'.join(map(str, np.polyfit(x, y, 1)))\n\n\ndef demo_polyfit1():\n d = urllib2.ur...
[ 0 ]
tabela = [[1,-45,-20,0,0,0,0],[0,20,5,1,0,0,9500],[0,0.04,0.12,0,1,0,40],[0,1,1,0,0,1,551]] colunas = ["Z","A","B","S1","S2","S3","Solução"] linhas = ["Z","S1","S2","S3"] n_colunas=7 n_linhas=4 #Inicio do algoritmo #Buscar o menor numero negativo na linha 0 menor_posicao=-1 menor_valor=0 for coluna in rang...
normal
{ "blob_id": "785dcaf7de68174d84af3459cde02927bc2e10cc", "index": 8951, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor coluna in range(0, n_colunas):\n if tabela[0][coluna] < menor_valor:\n menor_valor = tabela[0][coluna]\n menor_posicao = coluna\n<mask token>\nwhile menor_posicao != ...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @File : corr2d.py @Author : jeffsheng @Date : 2020/1/3 @Desc : 卷积层中的互相关(cross-correlation)运算 卷积层需要学习的参数是:卷积核和偏置大小 """ import tensorflow as tf def corr2d(X, K): """ 定义二维互相关运算函数 :param X:输入数组 :param K: 核数组 :return:二维互相关的运算结果 """ h, w = K.sh...
normal
{ "blob_id": "3f473701b186b5287258ba74e478cccdad0f29bf", "index": 2463, "step-1": "<mask token>\n\n\ndef corr2d(X, K):\n \"\"\"\n 定义二维互相关运算函数\n :param X:输入数组\n :param K: 核数组\n :return:二维互相关的运算结果\n \"\"\"\n h, w = K.shape\n Y = tf.Variable(tf.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)))...
[ 1, 2, 3, 4, 5 ]
Dict={0:0, 1:1} def fibo(n): if n not in Dict: val=fibo(n-1)+fibo(n-2) Dict[n]=val return Dict[n] n=int(input("Enter the value of n:")) print("Fibonacci(", n,")= ", fibo(n)) # uncomment to take input from the user nterms = int(input("How many terms? ")) # check if the number of terms is valid ...
normal
{ "blob_id": "5a1c4cc572431f89709d20296d43e8d889e8c5b0", "index": 5180, "step-1": "Dict={0:0, 1:1}\ndef fibo(n):\n if n not in Dict:\n val=fibo(n-1)+fibo(n-2)\n Dict[n]=val\n return Dict[n]\nn=int(input(\"Enter the value of n:\"))\nprint(\"Fibonacci(\", n,\")= \", fibo(n))\n\n# uncomment to ta...
[ 0 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # sockdemo.py # # test import struct, threading, signal a = '' if not a: print 'a' else: print 'b' import datetime, time, os print datetime.datetime.now().strftime('%m-%d %H:%M:%S') def double(x): return x*x arr = [1, 2, 3, 4, 5] print map(double, arr) print 2**16 ...
normal
{ "blob_id": "54d6121898dc027d6ecaf9c9e7c25391778e0d21", "index": 7311, "step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# sockdemo.py\n#\n# test\n\nimport struct, threading, signal\n\na = ''\n\nif not a:\n\tprint 'a'\nelse:\n\tprint 'b'\n\nimport datetime, time, os\n\nprint datetime.datetime.now().strf...
[ 0 ]
# Generated by Django 2.0.2 on 2018-06-10 18:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Expression', fields=[ ...
normal
{ "blob_id": "87e0b9dc518d439f71e261d5c5047153324919ba", "index": 9547, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
import sys import vector import matrix def convert_arg_to_list(arg): try: return [float(elem) for elem in arg] except: sys.exit("Invalid content inside {}".format(arg)) if __name__ == "__main__": try: vector1 = sys.argv[1].split(' ') vector2 = sys.argv[2].split(' ') exc...
normal
{ "blob_id": "347bfb2d8809b55046f698620a690099cc83fb56", "index": 6433, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef convert_arg_to_list(arg):\n try:\n return [float(elem) for elem in arg]\n except:\n sys.exit('Invalid content inside {}'.format(arg))\n\n\n<mask token>\n", "...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import (Port, Stop, Direction, Button, Color, ...
normal
{ "blob_id": "f6ebc3c37a69e5ec49d91609db394eec4a94cedf", "index": 9982, "step-1": "<mask token>\n", "step-2": "<mask token>\nbrick.sound.beep()\nwait(1000)\nmotor_a.run_target(500, 720)\nwait(1000)\nbrick.sound.beep(1000, 500)\n", "step-3": "<mask token>\nmotor_a = Motor(Port.A)\nbrick.sound.beep()\nwait(1000...
[ 0, 1, 2, 3, 4 ]
from rest_framework import serializers from films.models import * from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): films = serializers.PrimaryKeyRelatedField(many=True, queryset=Film.objects.all()) theaters = serializers.PrimaryKeyRelatedField(many=True, queryset=F...
normal
{ "blob_id": "e6aa28ae312ea5d7f0f818b7e86b0e76e2e57b48", "index": 4652, "step-1": "<mask token>\n\n\nclass FilmSerializer(serializers.ModelSerializer):\n owner = serializers.ReadOnlyField(source='owner.username')\n\n\n class Meta:\n model = Film\n fields = 'id', 'title', 'year_prod', 'genre', ...
[ 7, 9, 10, 11, 13 ]
""" Ниже на четырёх языках программирования записана программа, которая вводит натуральное число 𝑥, выполняет преобразования, а затем выводит результат. Укажите наименьшее значение 𝑥, при вводе которого программа выведет число 10. Тупо вручную ввёл. Крч 9. Хз, как на экзамене делать)) """ x = int(input()) a = 3 * x ...
normal
{ "blob_id": "181e9ac4acf0e69576716f3589359736bfbd9bef", "index": 2380, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile a != b:\n if a > b:\n a -= b\n else:\n b -= a\nprint(a)\nprint('---')\n<mask token>\nwhile number < 100:\n x = number\n a = 3 * x + 23\n b = 3 * x - 17\...
[ 0, 1, 2, 3 ]
import time import os import psutil start = time.time() from queue import Queue from copy import copy process = psutil.Process(os.getpid()) class Node: object_id = 0 weight = 0 value = 0 def __init__(self,object_id,weight,value): self.object_id=object_id self.weight=weight ...
normal
{ "blob_id": "be408b349e2795101b525ad8d948dbf52cab81bf", "index": 4281, "step-1": "<mask token>\n\n\nclass Node:\n object_id = 0\n weight = 0\n value = 0\n\n def __init__(self, object_id, weight, value):\n self.object_id = object_id\n self.weight = weight\n self.value = value\n\n\...
[ 4, 5, 7, 8, 9 ]
#!/usr/bin/python # coding=utf-8 import time import atexit # for signal handling import signal import sys # ---------------------- # Encoder stuff # ---------------------- import RPi.GPIO as GPIO # init GPIO.setmode(GPIO.BCM) # use the GPIO names, _not_ the pin numbers on the board # Raspberry Pi pin configuratio...
normal
{ "blob_id": "53841ba56589955e09b03018af1d0ae79b3756c4", "index": 5595, "step-1": "<mask token>\n\n\ndef leftEncoderCallback(answer):\n global leftSteps\n leftSteps = leftSteps + 1\n global leftDistance\n leftDistance = leftDistance + 0.24\n print('Left Encoder.')\n\n\ndef rightEncoderCallback(answ...
[ 5, 7, 8, 9, 10 ]
from .models import Stock from .serializers import StockSerializer from rest_framework import generics class StockListCreate(generics.ListCreateAPIView): queryset = Stock.objects.all() serializer_class = StockSerializer
normal
{ "blob_id": "9adf18b3a65bf58dd4c22a6fe026d0dd868533fb", "index": 5468, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass StockListCreate(generics.ListCreateAPIView):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass StockListCreate(generics.ListCreateAPIView):\n query...
[ 0, 1, 2, 3 ]
from threading import Lock from typing import Callable, Any from remote.domain.commandCallback import CommandCallback from remote.domain.commandStatus import CommandStatus from remote.service.remoteService import RemoteService from ui.domain.subroutine.iSubroutineRunner import ISubroutineRunner class RemoteSubroutin...
normal
{ "blob_id": "75270fb4ed059f134b47b8937717cb7fe05d9499", "index": 8833, "step-1": "<mask token>\n\n\nclass RemoteSubroutineRunner(ISubroutineRunner):\n <mask token>\n\n def execute_charge_subroutine(self, callback: CommandCallback) ->None:\n \"\"\"\n\n :raises BlockingIOError: command already ...
[ 14, 15, 17, 19, 21 ]
# coding: utf-8 # In[1]: import sys sys.path.extend(['detection', 'train']) # from detection folder from MtcnnDetector import MtcnnDetector from detector import Detector from fcn_detector import FcnDetector # from train folder from model_factory import P_Net, R_Net, O_Net import config as config from preprocess.uti...
normal
{ "blob_id": "f97a892e6e0aa258ad917c4a73a66e89b0dc3253", "index": 267, "step-1": "<mask token>\n", "step-2": "<mask token>\nsys.path.extend(['detection', 'train'])\n<mask token>\nif test_mode in ['RNet', 'ONet']:\n detectors[1] = Detector(R_Net, 24, batch_size[1], model_path[1])\n if test_mode == 'ONet':\...
[ 0, 1, 2, 3, 4 ]
import itertools def zbits(n,k): zeros = "0" * k ones = "1" * (n-k) binary = ones+zeros string = {''.join(i) for i in itertools.permutations(binary, n)} return(string) assert zbits(4, 3) == {'0100', '0001', '0010', '1000'} assert zbits(4, 1) == {'0111', '1011', '1101', '1110'} assert zbits(5, 4)...
normal
{ "blob_id": "a8d13c3fbf6051eba392bcdd6dcb3e946696585f", "index": 9065, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef zbits(n, k):\n zeros = '0' * k\n ones = '1' * (n - k)\n binary = ones + zeros\n string = {''.join(i) for i in itertools.permutations(binary, n)}\n return string\n\n...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 import numpy as np import os import random import pandas as pd def read_chunk(reader, chunk_size): data = {} for i in range(chunk_size): ret = reader.read_next() for k, v in ret.items(): if k not in data: data[k] = [] data[k].appe...
normal
{ "blob_id": "dc28c3426f47bef8b691a06d54713bc68696ee44", "index": 8309, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef read_chunk(reader, chunk_size):\n data = {}\n for i in range(chunk_size):\n ret = reader.read_next()\n for k, v in ret.items():\n if k not in data:\...
[ 0, 1, 2, 3 ]
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
normal
{ "blob_id": "f82ddc34fde76ddfbbe75116526af45b83c1b102", "index": 7895, "step-1": "<mask token>\n\n\nclass KnowValues(unittest.TestCase):\n\n def test_ls_contributing(self):\n \"\"\" To test the list of contributing centers \"\"\"\n sv = nao(gto=mol)\n pb = prod_basis()\n pb.sv = sv...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import swapper from haystack.constants import Indexable from haystack.fields import CharField, DateTimeField from haystack.indexes import SearchIndex class BasePageIndex(SearchIndex): text = CharField(document=True, use_template=True...
normal
{ "blob_id": "8e1eef3c5a9ca3ea504bbc269b48446527637626", "index": 1323, "step-1": "<mask token>\n\n\nclass PageIndex(BasePageIndex, Indexable):\n template = CharField(model_attr='template')\n template_title = CharField(model_attr='get_template_display')\n get_template_display = CharField(model_attr='get_...
[ 2, 4, 5, 6, 7 ]
''' Project Euler Problem #41 - Pandigital prime David 07/06/2017 ''' import time import math maxPandigitalPrime = 2 def isPrime(num): if(num<=1): return False elif(num==2): return True elif(num%2==0): return False else: sqrt_num = math.sqrt(num) bound = int(...
normal
{ "blob_id": "7ca7693b842700a7b15242b656648e8a7e58cd23", "index": 1691, "step-1": "<mask token>\n\n\ndef isPrime(num):\n if num <= 1:\n return False\n elif num == 2:\n return True\n elif num % 2 == 0:\n return False\n else:\n sqrt_num = math.sqrt(num)\n bound = int(s...
[ 2, 3, 4, 5, 6 ]
from ctypes import * class GF_AVCConfigSlot(Structure): _fields_=[ ("size", c_uint16), ("data", c_char), ("id", int) ]
normal
{ "blob_id": "f3b194bbc3c174549b64d6e6b1a8f4438a0c9d38", "index": 4791, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass GF_AVCConfigSlot(Structure):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass GF_AVCConfigSlot(Structure):\n _fields_ = [('size', c_uint16), ('data', c_char), ('id'...
[ 0, 1, 2, 3, 4 ]
from torch.utils.data import DataLoader from config import Config from torchnet import meter import numpy as np import torch from torch import nn from tensorboardX import SummaryWriter from Funcs import MAvgMeter from vae.base_vae import VAE from vae.data_util import Zinc_dataset import time import torch.optim class ...
normal
{ "blob_id": "8b7894e274647e48e3a1fe12473937bd6c62e943", "index": 8741, "step-1": "<mask token>\n\n\nclass Trainer:\n\n def __init__(self, model=None, opt=Config()):\n self.model = model\n self.opt = opt\n self.criterion = opt.criterion\n self.pred_id = self.opt.predictor_id\n ...
[ 4, 5, 6, 7, 8 ]
import subprocess from collections import namedtuple from os.path import basename, splitext def hdfs_get_filelist(blob_path, delimiter="_"): """ Lists hdfs dir and returns named tuples with information of file based on its filename. """ def hdfs_listdir(blob_path): command = 'hdfs dfs -ls ' + blob_pa...
normal
{ "blob_id": "6909e70db4f907e26ad604f95c79a405010907bd", "index": 2086, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef hdfs_get_filelist(blob_path, delimiter='_'):\n \"\"\" Lists hdfs dir and returns named tuples with information of file based on its filename. \"\"\"\n\n def hdfs_listdir(blo...
[ 0, 1, 2, 3, 4 ]
# Imports from __future__ import print_function import numpy from numpy.random import randint from enum import Enum __all__ = ["common", "plot"] class result(Enum): CRIT = 16 HIT = 8 EVADE = 4 FOCUS = 2 BLANK = 1 def result_str(res): str = "" if res & result.BLANK: str += "BLANK" i...
normal
{ "blob_id": "5261346f96e7520b6ef75a292b3d44a6f00d868c", "index": 5566, "step-1": "<mask token>\n\n\nclass result(Enum):\n CRIT = 16\n HIT = 8\n EVADE = 4\n FOCUS = 2\n BLANK = 1\n\n\n<mask token>\n\n\nclass die:\n\n def __init__(self):\n self.rerolled = False\n\n def __str__(self):\n ...
[ 24, 26, 29, 33, 38 ]
# Generated by Django 3.2.5 on 2021-08-05 23:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('lectures', '0003_auto_20210805_1954'), ] operations = [ migrations.RenameField( model_name='lecture', old_name='is_requird',...
normal
{ "blob_id": "e5bf4518f3834c73c3743d4c711a8d1a4ce3b944", "index": 6788, "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 = [('lectures', ...
[ 0, 1, 2, 3, 4 ]
# =================================================================== # Setup # =================================================================== from time import sleep import sys, termios, tty, os, pygame, threading # =================================================================== # Functions # ================...
normal
{ "blob_id": "44274446673225c769f63191d43e4747d8ddfbf7", "index": 6934, "step-1": "<mask token>\n\n\ndef play_emergency_sound():\n print('Playing emergency sound. There are ' + str(threading.\n active_count()) + ' threads active')\n while getattr(emergency_sound_thread, 'do_run', True):\n pyga...
[ 2, 3, 4, 5, 6 ]
import re print("Welcome to the Python Calculator") print("To stop calculator type: quit") previous = 0 run = True def perform_math(): '''(numbers) -> numbers accepts numbers from the user and performs continuous mathematical equations on them. precondition input must be numbers and m...
normal
{ "blob_id": "4122da21abab462a28c925c1afa5792ec729a75a", "index": 5087, "step-1": "<mask token>\n\n\ndef perform_math():\n \"\"\"(numbers) -> numbers\n\n accepts numbers from the user and performs continuous\n mathematical equations on them.\n\n precondition input must be numbers and mathematical sign...
[ 1, 2, 3, 4, 5 ]
from qiskit import QuantumCircuit,execute,Aer from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt qc_ha=QuantumCircuit(4,2) qc_ha.x(0) qc_ha.x(1) qc_ha.barrier() qc_ha.cx(0,2) qc_ha.cx(1,2) qc_ha.ccx(0,1,3) qc_ha.barrier() qc_ha.measure(2,0) qc_ha.measure(3,1) #qc_ha.draw(output='mpl') coun...
normal
{ "blob_id": "02381f28ef20aa0c2c235ef6563e1810a5931e35", "index": 5556, "step-1": "<mask token>\n", "step-2": "<mask token>\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0, 2)\nqc_ha.cx(1, 2)\nqc_ha.ccx(0, 1, 3)\nqc_ha.barrier()\nqc_ha.measure(2, 0)\nqc_ha.measure(3, 1)\n<mask token>\nplot_histogram(counts...
[ 0, 1, 2, 3, 4 ]
import face_recognition from glob import glob import os.path as osp class FaceRecognitionLib(object): """ face_recognition library を利用した顔認証検証 """ # クラス変数設定 __data_set_dir = './../../dataset/japanese' # データ・セットディレクトリ __known_image_idx = (1,) # 既存画像のインデックス ...
normal
{ "blob_id": "2d69a39be3931aa4c62cadff4cdfad76f6b32c59", "index": 6473, "step-1": "<mask token>\n\n\nclass FaceRecognitionLib(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self):\n sub_dirs = glob(FaceRecognitionLib.__data_set_dir + '...
[ 3, 4, 5, 8, 9 ]
from __future__ import print_function import zmq import time import random import numpy as np import msgpack as serializer port = '42000' # let the OS choose the IP and PORT ipc_sub_url = 'tcp://*:*' ipc_push_url = 'tcp://*:*' # starting communication threads zmq_ctx = zmq.Context() pub_socket = zmq_ctx.socket(zmq....
normal
{ "blob_id": "cb469b69bf974d39609f79c4f3be686d8106f971", "index": 1431, "step-1": "<mask token>\n", "step-2": "<mask token>\npub_socket.bind('tcp://*:%s' % port)\nwhile True:\n topic = 'test'\n thisX = np.random.rand()\n thisY = np.random.rand()\n testDict = {'gaze': (thisX, thisY)}\n pub_socket....
[ 0, 1, 2, 3, 4 ]
# -* coding: utf-8 -*- # A headless media player based on gstreamer. from gi.repository import Gst Gst.init(None) class Player: def __init__(self, uri=None): # Creates a playbin (plays media from an uri). self.player = Gst.ElementFactory.make('playbin', 'player') self.uri = uri @pro...
normal
{ "blob_id": "01e9ceb516a323a2017c65e368da419c6570dce2", "index": 7304, "step-1": "<mask token>\n\n\nclass Player:\n <mask token>\n\n @property\n def uri(self):\n return self._uri\n\n @uri.setter\n def uri(self, value):\n self._uri = value\n self.player.set_state(Gst.State.NULL...
[ 3, 6, 8, 9, 10 ]
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # ### Bài tập 1. # - <ins>Yêu cầu</ins>: Ý tưởng cơ bản của thuật toán ``Support Vector Machine`` (``SVM``) là gì? Ý tưởng của thuật toán biên mềm (``soft margin``) ``SVM``. Nêu ý nghĩa của siêu tham số ``C`` trong bà...
normal
{ "blob_id": "1b1b646a75fe2ff8d54e66d025b60bde0c9ed2d6", "index": 9361, "step-1": "<mask token>\n", "step-2": "<mask token>\ndf.pivot_table(index=['classes'], aggfunc='size')\n<mask token>\nfor n in np.arange(0.5, C_parameter, 0.5):\n clf = svm.SVC(C=n).fit(X_train, y_train)\n yhat = clf.predict(X_test)\n...
[ 0, 1, 2, 3, 4 ]
from Bio import SeqIO def flatten(l): return [j for i in l for j in i] def filter_sequences_by_len_from_fasta(file, max_len): with open(file) as handle: return [str(record.seq) for record in SeqIO.parse(handle, 'fasta') if len(record.seq) <= max_len]
normal
{ "blob_id": "1fdb9db4c1c8b83c72eeb34f10ef9d289b43b79f", "index": 3166, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef flatten(l):\n return [j for i in l for j in i]\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef flatten(l):\n return [j for i in l for j in i]\n\n\ndef filter_sequen...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (C) 2011 Lionel Bergeret # # ---------------------------------------------------------------- # The contents of this file are distributed under the CC0 license. # See http://creativecommons.org/publicdomain/zero/1.0/ # ----------------------------------------...
normal
{ "blob_id": "b7aa99e9e4af3bef4b2b3e7d8ab9bf159a093af6", "index": 574, "step-1": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#\n# Copyright (C) 2011 Lionel Bergeret\n#\n# ----------------------------------------------------------------\n# The contents of this file are distributed under the CC0 license.\n# S...
[ 0 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 24 22:05:12 2019 @author: admin """ for index in range(test_set.shape[0]): print(index)
normal
{ "blob_id": "35647ed5e2c128a5bf819a1e47ead7e958172b1c", "index": 9711, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor index in range(test_set.shape[0]):\n print(index)\n", "step-3": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 22:05:12 2019\n\n@author: admin\n\...
[ 0, 1, 2 ]
import time class DISTRICT: def __init__( self, cdcode, county, district, street, city, zipcode, state, mailstreet, mailcity, mailzip, mailstate, phone, extphone, faxnumber, email, admfname, admlname, admemail, lat, long, distrownercode, doctype, statustype, lastup...
normal
{ "blob_id": "462d73195680118d19a3d4e8a855e65aaeecb3c6", "index": 892, "step-1": "<mask token>\n\n\nclass DISTRICT:\n\n def __init__(self, cdcode, county, district, street, city, zipcode,\n state, mailstreet, mailcity, mailzip, mailstate, phone, extphone,\n faxnumber, email, admfname, admlname, a...
[ 5, 9, 10, 12, 13 ]
""" Creating flask server that response with a json """ from flask import Flask from flask import jsonify micro_service = Flask(__name__) @micro_service.route('/') # http://mysite.com/ def home(): return jsonify({'message': 'Hello, world!'}) if __name__ == '__main__': micro_service.run()
normal
{ "blob_id": "4b14dee3625d5d0c703176ed2f0a28b2583fd84d", "index": 6519, "step-1": "<mask token>\n\n\n@micro_service.route('/')\ndef home():\n return jsonify({'message': 'Hello, world!'})\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@micro_service.route('/')\ndef home():\n return jsonify({'message': ...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. from typing import Dict from Tea.core import TeaCore from alibabacloud_tea_openapi.client import Client as OpenApiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util.client import Client as UtilCl...
normal
{ "blob_id": "2e5d66033c2a049ba2423d01792a629bf4b8176d", "index": 8728, "step-1": "<mask token>\n\n\nclass Client(OpenApiClient):\n <mask token>\n <mask token>\n\n def get_endpoint(self, product_id: str, region_id: str, endpoint_rule:\n str, network: str, suffix: str, endpoint_map: Dict[str, str],...
[ 8, 10, 11, 12, 14 ]
# -*- coding:utf-8 -*- import sys import time class ProgressBar: @staticmethod def progress_test(): bar_length = 100 for percent in range(0, 101): hashes = '#' * int(percent / 100.0 * bar_length) spaces = ' ' * (bar_length - len(hashes)) sys.stdout.write("\...
normal
{ "blob_id": "f928eb34155046107c99db8ded11747d5960c767", "index": 2527, "step-1": "<mask token>\n\n\nclass ProgressBar:\n <mask token>\n\n\n class ProgressBar1:\n\n def __init__(self, width=50):\n self.pointer = 0\n self.width = width\n\n def __call__(self, x):\n ...
[ 1, 3, 4, 5, 6 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file entry implementation using pyfshfs.""" import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from dfvfs.vfs import hfs_attribute from dfvfs.vfs import hfs_file_entry f...
normal
{ "blob_id": "520672f8607751b65fe9e4b975a9978ed0ab71b6", "index": 8242, "step-1": "<mask token>\n\n\nclass HFSFileEntryTest(shared_test_lib.BaseTestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def tearDown(self):\n \"\"\"Cleans up...
[ 18, 19, 20, 25, 27 ]
import subprocess as sp from .dummy_qsub import dummy_qsub from os.path import exists from os import makedirs from os import remove from os.path import dirname QUEUE_NAME = 'fact_medium' def qsub(job, exe_path, queue=QUEUE_NAME): o_path = job['o_path'] if job['o_path'] is not None else '/dev/null' e_path = jo...
normal
{ "blob_id": "427d3d386d4b8a998a0b61b8c59984c6003f5d7b", "index": 6975, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef qsub(job, exe_path, queue=QUEUE_NAME):\n o_path = job['o_path'] if job['o_path'] is not None else '/dev/null'\n e_path = job['e_path'] if job['e_path'] is not None else '/de...
[ 0, 1, 2, 3 ]
""" Author : Gülşah Büyük Date : 17.04.2021 """ import numpy as np A = np.array([[22, -41, 2], [61, 17, -18], [-9, 74, -13]]) # For a square matrix A the QR Decomposition converts into the product of an orthogonal matrix Q # (Q.T)Q= I and an upper triangular matrix R. def householder_reflection(A): # A H...
normal
{ "blob_id": "0d1fda864edc73cc6a9853727228c6fa3dfb19a1", "index": 3039, "step-1": "<mask token>\n\n\ndef householder_reflection(A):\n size = len(A)\n Q = np.identity(size)\n R = np.copy(A)\n for i in range(size - 1):\n x = R[i:, i]\n e = np.zeros_like(x)\n e[0] = np.linalg.norm(x)...
[ 1, 2, 3, 4, 5 ]
from convert_data2 import array_rule from convert_data2 import array_packet import tensorflow as tf import numpy as np train_x, train_y = array_packet() x_input, input_ip = array_rule() n_nodes_hl1 = 210 n_nodes_hl2 = 210 n_nodes_hl3 = 210 n_classes = 2 batch_size = 500 hm_epochs = 20 x = tf.placeholder('float') y ...
normal
{ "blob_id": "1446268583bf9fa3375319eae3c21cf47f47faca", "index": 7279, "step-1": "<mask token>\n\n\ndef neural_network_model(data):\n l1 = tf.add(tf.matmul(data, hidden_1_layer['weight']), hidden_1_layer[\n 'bias'])\n l1 = tf.nn.relu(l1)\n l2 = tf.add(tf.matmul(l1, hidden_2_layer['weight']), hidd...
[ 2, 3, 4, 5, 6 ]
from redis_interval.client import RedisInterval class TestRedisIntervalIADD(object): """ Tests the IADD command """ @classmethod def setup_class(cls): cls.redis = RedisInterval(host="localhost") def test_add_simple_text(self): """ Add simple text inside an interval """ value ...
normal
{ "blob_id": "0e7732ffcada864fb83b59625c5b9abb01150aaa", "index": 1702, "step-1": "<mask token>\n\n\nclass TestRedisIntervalIADD(object):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestRedisIntervalIADD(object):\n <mask token>\n\n @classmethod\n def set...
[ 1, 3, 4, 5, 6 ]
from ..scope_manager import ScopeManager from ..span import Span from ..tracer import Tracer from .propagator import Propagator class MockTracer(Tracer): def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ... def register_propagator(self, format: str, propagator: Propagator) -> None: ... ...
normal
{ "blob_id": "76d2c80c673f9a0444e72721909a51479ff35521", "index": 1785, "step-1": "<mask token>\n\n\nclass MockTracer(Tracer):\n\n def __init__(self, scope_manager: (ScopeManager | None)=...) ->None:\n ...\n\n def register_propagator(self, format: str, propagator: Propagator) ->None:\n ...\n ...
[ 3, 4, 5, 6, 7 ]
# -*- coding: utf-8 -*- """microcms package, minimalistic flatpage enhancement. THIS SOFTWARE IS UNDER BSD LICENSE. Copyright (c) 2010-2012 Daniele Tricoli <eriol@mornie.org> Read LICENSE for more informations. """ VERSION = (0, 2, 0)
normal
{ "blob_id": "3e1c2d0c5bb30d093a99f10020af14db5436bf02", "index": 5551, "step-1": "<mask token>\n", "step-2": "<mask token>\nVERSION = 0, 2, 0\n", "step-3": "# -*- coding: utf-8 -*-\n\"\"\"microcms package, minimalistic flatpage enhancement.\n\nTHIS SOFTWARE IS UNDER BSD LICENSE.\nCopyright (c) 2010-2012 Dani...
[ 0, 1, 2 ]
import hashlib def md5_hexdigest(data): return hashlib.md5(data.encode('utf-8')).hexdigest() def sha1_hexdigest(data): return hashlib.sha1(data.encode('utf-8')).hexdigest() def sha224_hexdigest(data): return hashlib.sha224(data.encode('utf-8')).hexdigest() def sha256_hexdigest(data): return hash...
normal
{ "blob_id": "35a95c49c2dc09b528329433a157cf313cf59667", "index": 8955, "step-1": "<mask token>\n\n\ndef md5_hexdigest(data):\n return hashlib.md5(data.encode('utf-8')).hexdigest()\n\n\ndef sha1_hexdigest(data):\n return hashlib.sha1(data.encode('utf-8')).hexdigest()\n\n\ndef sha224_hexdigest(data):\n re...
[ 4, 5, 6, 7 ]
import json import sys from copy import deepcopy from argparse import ArgumentParser # TODO: Ord category's IDs after deletion def return_cat_name(json_coco, category): """Return the category name of a category ID Arguments: json_coco {dict} -- json dict file from coco file category {int} --...
normal
{ "blob_id": "467327b98ab99bdad429943c701c751be4f67940", "index": 9378, "step-1": "<mask token>\n\n\ndef main():\n \"\"\"Remove a category from a coco json file\n \"\"\"\n parser = ArgumentParser(description=\n 'Category Filter: Filter a List of Categories from a JSON')\n parser.add_argument('j...
[ 1, 2, 3, 4, 5 ]
import os import random import cv2 import numpy as np from keras.preprocessing.image import img_to_array import numpy as np import keras from scipy import ndimage, misc def preprocess_image(img): img = img.astype(np.uint8) (channel_b, channel_g, channel_r) = cv2.split(img) result = ndimage.maximum_filter(...
normal
{ "blob_id": "586d39556d2922a288a2bef3bcffbc6f9e3dc39d", "index": 6707, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef preprocess_image(img):\n img = img.astype(np.uint8)\n channel_b, channel_g, channel_r = cv2.split(img)\n result = ndimage.maximum_filter(channel_g, size=5)\n ret, resu...
[ 0, 1, 2, 3, 4 ]
def presses(phrase): keyboard = ['1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#'] amount = 0 for lttr in phrase.upper(): for key in keyboard: try: i = key.index(lttr) i += 1 amount += i ...
normal
{ "blob_id": "c2e9a93861080be616b6d833a9343f1a2f018a0b", "index": 5039, "step-1": "<mask token>\n", "step-2": "def presses(phrase):\n keyboard = ['1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7',\n 'TUV8', 'WXYZ9', '*', ' 0', '#']\n amount = 0\n for lttr in phrase.upper():\n for key i...
[ 0, 1 ]
#THIS BUILD WORKS, BUT IS VERY SLOW. CURRENTLY YIELDS A DECENT SCORE, NOT GREAT alphabet = "abcdefghijklmnopqrstuvwxyz" def author(): return "" def student_id(): return "" def fill_words(pattern,words,scoring_f,minlen,maxlen): foundWords = find_words(pattern,words,scoring_f,minlen,maxlen) f...
normal
{ "blob_id": "9bd659bb3bf812e48710f625bb65a848d3a8d074", "index": 594, "step-1": "<mask token>\n\n\ndef author():\n return ''\n\n\ndef student_id():\n return ''\n\n\n<mask token>\n\n\ndef find_words(pattern, words, scoring_f, minlen, maxlen):\n patternCopy = pattern\n bestWord = '', 0\n bestState =...
[ 5, 7, 8, 9, 10 ]
#coding=utf-8 ''' Created on 2013-3-28 @author: jemmy ''' import telnetlib import getpass import sys import os import time import xlrd from pyExcelerator import * import #define Host = "192.168.0.1" Port = "70001" #Host = raw_iput("IP",) username = "admin" password = "admin" filename = str(time.strftime('%Y%m%d%H%M%S...
normal
{ "blob_id": "153c02585e5d536616ec4b69757328803ac2fb71", "index": 3394, "step-1": "#coding=utf-8\n'''\nCreated on 2013-3-28\n\n@author: jemmy\n'''\nimport telnetlib\nimport getpass\nimport sys\nimport os\nimport time\nimport xlrd\nfrom pyExcelerator import *\nimport\n#define\nHost = \"192.168.0.1\"\nPort = \"7000...
[ 0 ]
from twitter.MyStreamListener import MyStreamListener import tweepy from threading import Thread class TwitterWorker(Thread): def __init__(self): Thread.__init__(self) CONSUMER_KEY = 'IwZZeJHjLXq55ewwQwD0SogHU' CONSUMER_SECRET = '80kELQhDGNvLNFfNZ7qliIbzAoA3tsgQ...
normal
{ "blob_id": "c475e095571b211693e66583637442edbf72c260", "index": 7741, "step-1": "<mask token>\n\n\nclass TwitterWorker(Thread):\n <mask token>\n\n def run(self):\n streamListener = MyStreamListener()\n self.stream = tweepy.Stream(auth=self.api.auth, listener=streamListener\n )\n ...
[ 2, 3, 4, 5, 6 ]
import joblib import os import shutil import re from scipy import stats from functools import partial import pandas as pd from multiprocessing import Process, Pool from nilearn import masking, image import nibabel as nib import numpy as np from tqdm import tqdm import matplotlib matplotlib.use('Agg') import matplotlib...
normal
{ "blob_id": "2e9d71b8055e1bab107cedae69ca3bc4219e7d38", "index": 7460, "step-1": "<mask token>\n\n\ndef get_paths(debug, dataset):\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'o...
[ 16, 17, 18, 21, 23 ]
import os,sys import logging from flask import Flask from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy def create_app(): app = Flask(__name__) Bootstrap(app) return app logging.basicConfig(level=logging.DEBUG) app = create_app() app.config['WTF_CSRF_ENABLED'] = True app.config[...
normal
{ "blob_id": "bd726c86bdecd0b63eb48d056932706d3ecf147d", "index": 7665, "step-1": "<mask token>\n\n\ndef create_app():\n app = Flask(__name__)\n Bootstrap(app)\n return app\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef create_app():\n app = Flask(__name__)\n Bootstrap(app)\n return ap...
[ 1, 2, 3, 4, 5 ]
# created by RomaOkorosso at 21.03.2021 # models.py from datetime import datetime from sqlalchemy import ( Column, Integer, String, Boolean, DateTime, ForeignKey, Date ) from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship from Database.database import Base ...
normal
{ "blob_id": "a288e66e64d386afd13bfc7b5b13d4a47d15cd6d", "index": 1316, "step-1": "<mask token>\n\n\nclass Client(Base):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TakenBook(Base):\n __tablename__ = 'taken_books'\n id = Column(Integ...
[ 3, 7, 8, 10, 12 ]
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdri...
normal
{ "blob_id": "5f490d6a3444b3b782eed5691c82ab7e4b2e55db", "index": 8883, "step-1": "from selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import e...
[ 0 ]
# Imports import os from flask import Flask, redirect, render_template, url_for, request, flash from flask_login import LoginManager, login_user, logout_user, login_required, current_user # Import - Database from flask_sqlalchemy import SQLAlchemy # Import - Models from werkzeug.security import generate_password_hash...
normal
{ "blob_id": "6ff4aff5811d2bd7ad150d7e8f925308d120ef74", "index": 2566, "step-1": "<mask token>\n\n\nclass User(UserMixin, db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(64))\n email = db.Column(db.String(64), unique=True, index=True)\n...
[ 23, 24, 26, 27, 32 ]
#!/usr/bin/env python import argparse import xml.etree.cElementTree as ET from datetime import datetime, timedelta from requests import codes as requests_codes from requests_futures.sessions import FuturesSession from xml.etree import ElementTree as ET parser = argparse.ArgumentParser(description='Fetch dqm images')...
normal
{ "blob_id": "0d18272f8056f37eddabb024dd769a2793f88c24", "index": 6064, "step-1": "#!/usr/bin/env python\n\nimport argparse\nimport xml.etree.cElementTree as ET\n\nfrom datetime import datetime, timedelta\nfrom requests import codes as requests_codes\nfrom requests_futures.sessions import FuturesSession\nfrom xml...
[ 0 ]
def readfasta (fasta): input = open(fasta, 'r') seqs = {} for line in input: if line[0] == '>': name = line[1:].rstrip() seqs[name] = [] else: seqs[name].append(line.rstrip()) for name in seqs: seqs[name] = ''.join(seqs[name]) r...
normal
{ "blob_id": "6072fc22872ee75c9501ac607a86ee9137af6a5d", "index": 4918, "step-1": "def readfasta (fasta):\r\n input = open(fasta, 'r')\r\n seqs = {}\r\n for line in input:\r\n if line[0] == '>':\r\n name = line[1:].rstrip()\r\n seqs[name] = [] \r\n else:\r\n ...
[ 0 ]
""" Read all the images from a directory, resize, rescale and rename them. """
normal
{ "blob_id": "670efbd9879099b24a87e19a531c4e3bbce094c6", "index": 1666, "step-1": "<mask token>\n", "step-2": "\n\n\"\"\"\nRead all the images from a directory,\nresize, rescale and rename them.\n\"\"\"\n\n\n\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# DATA TYPES (DATA TİPLERİ) # STRİNGS (KARAKTER DİZİNLERİ) # Bir karakter dizinini tanımlamak için tırnaklar kullanılır. birkaç satır ka- # rakter dizini yazıyorsak 3 tırnak kullanılır: print("""Üç tırnaklı karakter dizinine örnek""") üç tırnaklı karakter dizinine örnek print('Tek tırnak: Tek satırlık...
normal
{ "blob_id": "61f2fbed184ff6f842ba9527456da453844f8dc6", "index": 1362, "step-1": "# DATA TYPES (DATA TİPLERİ)\r\n\r\n# STRİNGS (KARAKTER DİZİNLERİ)\r\n\r\n# Bir karakter dizinini tanımlamak için tırnaklar kullanılır. birkaç satır ka-\r\n# rakter dizini yazıyorsak 3 tırnak kullanılır:\r\nprint(\"\"\"Üç tırnaklı\r...
[ 0 ]
import math import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_ge...
normal
{ "blob_id": "010a132645883915eff605ae15696a1fac42d570", "index": 8276, "step-1": "<mask token>\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = energy(gen)\n logq_gen = noise.log_prob(gen).unsqueeze(1)\n ll_data = logp_x - torch.log...
[ 7, 8, 9, 11, 12 ]
from random import randint cantidad = int(input("Numero de preguntas: ")) contador_bien = 0 contador_mal = 0 while cantidad <= 0: print ("El numero de preguntas debe ser al menos 1") cantidad = int(input("Numero de preguntas: ")) for i in range(cantidad): numero = randint(2,10) numero2 = randint(2,10) aleatorio ...
normal
{ "blob_id": "48bc5d4b191fa631650b60240560dbece6396312", "index": 655, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile cantidad <= 0:\n print('El numero de preguntas debe ser al menos 1')\n cantidad = int(input('Numero de preguntas: '))\nfor i in range(cantidad):\n numero = randint(2, 10)\n ...
[ 0, 1, 2, 3, 4 ]
#Charlie Quinn if.py #Check < in an 'if' statement #use a 'while' loop to make testing easier def income_input(prompt_message): prompt = prompt_message + ' ' temp = input(prompt) #get input from user return float(temp) do_again = 'y' while do_again =='y': income = income_input("\nHow much did ...
normal
{ "blob_id": "d5acde6c6139833c6631a2d88a181cd019d3d2da", "index": 5747, "step-1": "<mask token>\n", "step-2": "def income_input(prompt_message):\n prompt = prompt_message + ' '\n temp = input(prompt)\n return float(temp)\n\n\n<mask token>\n", "step-3": "def income_input(prompt_message):\n prompt =...
[ 0, 1, 2, 3, 4 ]
import time import random from BlockchainNetwork.MVB import * from threading import Thread coloredlogs.install() logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.getLogger(__name__) class MVBTest: def __init__(self, initialNodeCnt): sel...
normal
{ "blob_id": "8ad9efbbb2d9e2a5f73ebbb999da3ed93e4c1974", "index": 9655, "step-1": "<mask token>\n\n\nclass MVBTest:\n <mask token>\n <mask token>\n\n def doubleSpendTest(self):\n \"\"\"\n txOutputs is the genesis output.\n txOutputs[0] was used twice in this test.\n ...
[ 11, 15, 17, 18, 19 ]
from ccapi.interfaces.bitfinex import Bitfinex from ccapi.interfaces.bittrex import Bittrex from ccapi.interfaces.poloniex import Poloniex from ccapi.interfaces.bithumb import Bithumb from ccapi.interfaces.coinone import Coinone from ccapi.interfaces.korbit import Korbit # from ccapis.interfaces.coinbase import Coinbas...
normal
{ "blob_id": "098c91f4aa367cb389e542c0199b633e7ecd4003", "index": 4369, "step-1": "<mask token>\n", "step-2": "from ccapi.interfaces.bitfinex import Bitfinex\nfrom ccapi.interfaces.bittrex import Bittrex\nfrom ccapi.interfaces.poloniex import Poloniex\nfrom ccapi.interfaces.bithumb import Bithumb\nfrom ccapi.in...
[ 0, 1, 2 ]
import pygame from .Coin import Coin from .Snake import Snake, Block from .Bomb import Bomb from .Rocket import Rocket from pygame.math import Vector2 cell_size = 16 cell_number = 30 sprite_cell = pygame.image.load("Assets/Cell.png") bg = pygame.image.load("Assets/BG.png") bg2 = pygame.image.load("Assets/BG2.png") c...
normal
{ "blob_id": "2b14607aa2527f5da57284917d06ea60e89f784c", "index": 1659, "step-1": "<mask token>\n\n\nclass GAME:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def check_timer(self):\n if self.count >= self.crowd:\n self.game_timer += 1\n if self.game_t...
[ 5, 7, 9, 10, 13 ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mapGraph.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MapGraphTab(object): def setupUi(self, MapGraphTab): MapGra...
normal
{ "blob_id": "03a13037a9a102397c8be4d9f0f4c5e150965808", "index": 8666, "step-1": "<mask token>\n\n\nclass Ui_MapGraphTab(object):\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Ui_MapGraphTab(object):\n\n def setupUi(self, MapGraphTab):\n MapGraphTab.setO...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 17:42:18 2018 @author: Tim """ import music21 as m21 import music21.features.jSymbolic as jsym import scipy.stats from collections import Counter import numpy as np import matplotlib.pyplot as plt from timeit import default_timer as timer # round all duration values t...
normal
{ "blob_id": "eb9135c6bcf89a62534cfc8480e5d44a089fe5a8", "index": 1216, "step-1": "<mask token>\n\n\ndef extractPatternOccurrence(songName, inStart, inEnd, useTies, songs):\n \"\"\"\n given song name, occurrence start, occurrence end, and the database of score files,\n return the notes of the associated ...
[ 3, 8, 9, 10, 11 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sub_adjuster', '0002_parameters'), ] operations = [ migrations.AlterField( model_name='subtitles', n...
normal
{ "blob_id": "156203042ed8a9bde0e9d8587ea3d37de6bcfdf7", "index": 5155, "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 = [('sub_adjuste...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import argparse import requests import sys import os import xml.dom.minidom __author__ = 'Tighe Schlottog || tschlottog@paloaltonetworks.com' ''' wf.py is a script to interact with the WildFire API to upload files or pull back reports on specific hashes. You need to have the argparse a...
normal
{ "blob_id": "e8e78610df4461a96f7d9858870de0e3482801fd", "index": 5083, "step-1": "#!/usr/bin/env python\n\nimport argparse\nimport requests\nimport sys\nimport os\nimport xml.dom.minidom\n\n__author__ = 'Tighe Schlottog || tschlottog@paloaltonetworks.com'\n\n'''\n wf.py is a script to interact with the WildFi...
[ 0 ]
from sympy import * import sys x = Symbol("x") # EOF try: in_str = input() except Exception as e: print("WRONG FORMAT!") # Wrong Format! sys.exit(0) in_str = in_str.replace("^", "**") #change '^'into'**' for recognition # wrong expression try: in_exp = eval(in_str) # turn s...
normal
{ "blob_id": "1634ae0e329b4f277fa96a870fbd19626c0ece81", "index": 6516, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n in_str = input()\nexcept Exception as e:\n print('WRONG FORMAT!')\n sys.exit(0)\n<mask token>\ntry:\n in_exp = eval(in_str)\nexcept Exception as e:\n print('WRONG FO...
[ 0, 1, 2, 3, 4 ]
import collections # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True ...
normal
{ "blob_id": "24a4b9246a9b15334bebc45c532a25bd81266918", "index": 9650, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TreeNode:\n <mask token>\n\n\nclass Solution:\n\n def isSymmetric(self, root: TreeNode) ->bool:\n if not root:\n r...
[ 1, 3, 4, 5, 6 ]
#!/usr/bin/env python #coding:gbk """ Author: pengtao --<pengtao@baidu.com> Purpose: 1. 管理和交互式调用hadoop Job的框架 History: 1. 2013/12/11 created """ import sys import inspect import cmd import readline #import argparse #from optparse import (OptionParser, BadOptionError, AmbiguousOptionError) from job i...
normal
{ "blob_id": "9178d39a44cfb69e74b4d6cd29cbe56aea20f582", "index": 3984, "step-1": "#!/usr/bin/env python\n#coding:gbk\n\n\"\"\"\n Author: pengtao --<pengtao@baidu.com>\n Purpose: \n 1. 管理和交互式调用hadoop Job的框架\n History:\n 1. 2013/12/11 created\n\"\"\"\n\n\n\nimport sys\nimport inspect\nimport cmd\nimport r...
[ 0 ]
# SPDX-License-Identifier: Apache-2.0 """ .. _example-lightgbm-pipe: Convert a pipeline with a LightGbm model ======================================== .. index:: LightGbm *sklearn-onnx* only converts *scikit-learn* models into *ONNX* but many libraries implement *scikit-learn* API so that their models can be inclu...
normal
{ "blob_id": "32227029cb4e852536611f7ae5dec5118bd5e195", "index": 8324, "step-1": "<mask token>\n", "step-2": "<mask token>\nnumpy.random.shuffle(ind)\n<mask token>\npipe.fit(X, y)\nupdate_registered_converter(LGBMClassifier, 'LightGbmLGBMClassifier',\n calculate_linear_classifier_output_shapes, convert_ligh...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- import numpy as np from . import BOID_NOSE_LEN from .utils import normalize_angle, unit_vector class Individual: def __init__(self, color, pos, ror, roo, roa, angle=0, speed=1.0, turning_rate=0.2): """Constructor of Individual. Args: color (Color): color for ...
normal
{ "blob_id": "386e491f6b10ca27f513d678c632571c29093ad2", "index": 5825, "step-1": "<mask token>\n\n\nclass Individual:\n <mask token>\n\n @property\n def dir(self):\n \"\"\"Get the unitary vector of direction.\n\n Returns:\n numpy.ndarray: The unitary vector of direction.\n\n ...
[ 5, 6, 7, 8, 9 ]
# Chris DeBoever # cdeboeve@ucsd.edu import sys, argparse, pdb, glob, os, re import numpy as np from bisect import bisect_left from scipy.stats import binom ### helper functions ### def find_lt(a,x): """ Find rightmost value less than x in list a Input: list a and value x Output: rightmost value les...
normal
{ "blob_id": "da751e96c225ebc2d30f3cce01ba2f64d0a29257", "index": 3763, "step-1": "<mask token>\n\n\ndef find_lt(a, x):\n \"\"\"\n Find rightmost value less than x in list a\n Input: list a and value x\n Output: rightmost value less than x in a\n \"\"\"\n i = bisect_left(a, x)\n if i:\n ...
[ 7, 8, 9, 11, 12 ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/cypher/.eric6/eric6plugins/vcsGit/ConfigurationPage/GitPage.ui' # # Created by: PyQt5 UI code generator 5.8 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_GitPage(object):...
normal
{ "blob_id": "80891a4c9703f91509d2c1b22304f33426dfb962", "index": 4419, "step-1": "<mask token>\n\n\nclass Ui_GitPage(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Ui_GitPage(object):\n\n def setupUi(self, GitPage):\n GitPage.setObjectName('GitPage')\n GitP...
[ 1, 2, 3, 4, 5 ]
class Solution: def countLetters(self, S: str) ->int: ans = 0 for _, g in itertools.groupby(S): cnt = len(list(g)) ans += (1 + cnt) * cnt // 2 return ans
normal
{ "blob_id": "f9cee552dde5ecf229fda559122b4b0e780c3b88", "index": 7350, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def countLetters(self, S: str) ->int:\n ans = 0\n for _, g in itertools.groupby(S):\n cnt = len(list(g...
[ 0, 1, 2 ]
# import adafruit_ads1x15 as adс # from adafruit_ads1x15 import ads1x15 as adc # from adafruit_ads1x15 import analog_in import time import busio import board from adafruit_ads1x15 import ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1015(i2c...
normal
{ "blob_id": "388904b6b826a1c718b85f2951a3189bb5abea2a", "index": 9755, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('{:>5}\\t{:>5}'.format('raw', 'v'))\nwhile True:\n print('{:>5}\\t{:>5.3f}'.format(chan.value, chan.voltage))\n time.sleep(0.5)\n", "step-3": "<mask token>\ni2c = busio.I2C(...
[ 0, 1, 2, 3, 4 ]
from .net import *
normal
{ "blob_id": "73337246bd54df53842360510148f3a6f4763ace", "index": 6251, "step-1": "<mask token>\n", "step-2": "from .net import *\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
#!/usr/bin/env python from setuptools import setup import NagAconda setup(name=NagAconda.__name__, version=NagAconda.__version__, description="NagAconda is a Python Nagios wrapper.", long_description=open('README').read(), author='Steven Schlegel', author_email='steven@schlegel.tech', ...
normal
{ "blob_id": "c3719f30bcf13061134b34b0925dfa2af4535f14", "index": 7854, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name=NagAconda.__name__, version=NagAconda.__version__, description=\n 'NagAconda is a Python Nagios wrapper.', long_description=open('README'\n ).read(), author='Steven Schle...
[ 0, 1, 2, 3 ]