code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
# coding: utf-8
"""
Provides test-related code that can be used by all tests.
"""
import os
DATA_DIR = 'tests/data'
def get_data_path(file_name):
return os.path.join(DATA_DIR, file_name)
def assert_strings(test_case, actual, expected):
# Show both friendly and literal versions.
message = """\
... | normal | {
"blob_id": "83d35c413af0cefb71964671b43df1e815aa2115",
"index": 3945,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_data_path(file_name):\n return os.path.join(DATA_DIR, file_name)\n\n\ndef assert_strings(test_case, actual, expected):\n message = (\n \"\"\"\n\n Expected: \"\... | [
0,
2,
3,
4,
5
] |
# from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools
# and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6
import tensorflow as tf
from object_detection.utils import dataset_util
import os
import io
import hashlib
import xml.etree.ElementTree as ET
imp... | normal | {
"blob_id": "8142585827590f6d951f0fcc375e8511aa75e9c8",
"index": 7320,
"step-1": "<mask token>\n\n\ndef main(_):\n writer_train = tf.python_io.TFRecordWriter('./data/train.record')\n writer_test = tf.python_io.TFRecordWriter('./data/test.record')\n filename_list = tf.train.match_filenames_once('./data/a... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/env python
# coding: utf-8
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host = '192.168.10.28'
))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='... | normal | {
"blob_id": "a9a60d4bee45a4012d004bacac7812160ed4241c",
"index": 4012,
"step-1": "#!/usr/bin/env python\n# coding: utf-8\n\nimport pika\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\n host = '192.168.10.28'\n))\nchannel = connection.channel()\nchannel.queue_declare(queue='hello')\nchannel... | [
0
] |
#! /usr/bin/env python
# coding: utf-8
'''
Author: xiezhw3@163.com
@contact: xiezhw3@163.com
@version: $Id$
Last modified: 2016-01-17
FileName: consumer.py
Description: 从 rabbitmq 拿到消息并存储到数据库
'''
import pika
import json
import logging
import pymongo
import traceback
from conf import config
from code.modules.db_proce... | normal | {
"blob_id": "ff26a2c2d8427f1ad4617669e701ea88b34616cd",
"index": 9152,
"step-1": "<mask token>\n\n\nclass Consumer(object):\n <mask token>\n\n def __init__(self):\n self.db_processor = DbProcessor()\n credentials = pika.PlainCredentials(config.RABBITMQ_USER, config.\n RABBITMQ_PASS... | [
3,
5,
6,
7,
9
] |
#!/usr/bin/env python3
import sys
import csv
import math
import collections
import argparse
import fileinput
import lp
parser = argparse.ArgumentParser(description="Takes an input of *.lp format and sets all radii to the same value")
parser.add_argument("inputfile", help="if specified reads a *.lp formatted file oth... | normal | {
"blob_id": "00f62fec7f5372c5798b0ebf3f3783233360581e",
"index": 2987,
"step-1": "<mask token>\n\n\ndef main():\n reader = csv.reader(row for row in fileinput.input() if not row.\n startswith('#'))\n circles = lps.parse_lps(reader)\n for circle in circles:\n circle.r = R\n print(cir... | [
1,
2,
3,
4,
5
] |
import math
import pygame
import numpy as np
from main import Snake, SCREEN_WIDTH, SCREEN_HEIGHT, drawGrid, GRIDSIZE
from random import randint
FOOD_REWARD = 5
DEATH_PENALTY = 10
MOVE_PENALTY = 0.1
LIVES = 5
SQUARE_COLOR = (80,80,80)
SNAKE_HEAD_COLOR = ((0,51,0), (0,0,153), (102,0,102))
SNAKE_COLOR = ((154,205,50), ... | normal | {
"blob_id": "3bb408f2b2ac63a2555258c05844881ccdfc5057",
"index": 5428,
"step-1": "<mask token>\n\n\nclass SnakeGame:\n\n def __init__(self, board_width=10, board_height=10, gui=False,\n enemy_epsilon=0.1):\n self.score = 0\n self.board = {'width': board_width, 'height': board_height}\n ... | [
12,
14,
18,
22,
24
] |
import json
import requests
class Bitcoin:
coindesk = 'https://api.coindesk.com/v1/bpi/currentprice.json'
def __init__(self):
pass
def get_current_price(self, url=coindesk):
self.resp = requests.get(url)
if self.resp.status_code == 200:
return json.loads(self.resp.con... | normal | {
"blob_id": "3bfe4021d5cf9bd24c0fb778b252bc04c6ac47ed",
"index": 1847,
"step-1": "<mask token>\n\n\nclass Bitcoin:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Bitcoin:\n <mask token>\n\n def __init__(self):\n pass\n <mask token>... | [
1,
2,
4,
5,
6
] |
from requests import get
from bs4 import BeautifulSoup, SoupStrainer
import httplib2
import re
from win32printing import Printer
def getLinks(url):
links = []
document = BeautifulSoup(response, "html.parser")
for element in document.findAll('a', href=re.compile(".pdf$")):
links.append(element.get(... | normal | {
"blob_id": "dbb007af79b2da2b5474281759c2bcce2a836fb5",
"index": 1254,
"step-1": "<mask token>\n\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, 'html.parser')\n for element in document.findAll('a', href=re.compile('.pdf$')):\n links.append(element.get('href'))\n return... | [
1,
2,
3,
4,
5
] |
from models import Session, FacebookUser, FacebookPage, FacebookGroup
from lib import get_scraper, save_user, save_page
import logging
logging.basicConfig(level=logging.DEBUG)
session = Session()
scraper = get_scraper(True)
for user in session.query(FacebookUser).filter(FacebookUser.data=="todo").filter("username ~ '... | normal | {
"blob_id": "77ae3ef1f6f267972a21f505caa7be29c19a6663",
"index": 8369,
"step-1": "from models import Session, FacebookUser, FacebookPage, FacebookGroup\nfrom lib import get_scraper, save_user, save_page\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nsession = Session()\nscraper = get_scraper(True)\... | [
0
] |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
"""
Using the django shell:
$ python manage.py shell
from django.contrib.auth.models import User
from accounts.models import Profile
from papers.models import Paper, Comment, Rating, UserSavedPaper
users = User... | normal | {
"blob_id": "052574be3f4a46bceefc0a54b1fe268a7cef18a9",
"index": 3061,
"step-1": "<mask token>\n\n\nclass Comment(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.text\n\n\nclass Rating(models.Model):\n rating = models.Positi... | [
8,
9,
10,
13,
14
] |
#Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence.
# Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode.
# Output: All substrings of Text encoding Peptide (if any such substrings exist).
def reverse_string(seq):
return seq[::-1]
def compl... | normal | {
"blob_id": "0f2d215a34758f85a29ef7ed8264fccd5e85b66f",
"index": 3017,
"step-1": "def reverse_string(seq):\n return seq[::-1]\n\n\ndef complement(seq):\n seq = seq.upper()\n basecomplement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}\n letters = list(seq)\n letters = [basecomplement[base] ... | [
4,
5,
6,
7,
8
] |
import pytest
from flaat.issuers import IssuerConfig, is_url
from flaat.test_env import FLAAT_AT, FLAAT_ISS, environment
class TestURLs:
def test_url_1(self):
assert is_url("http://heise.de")
def test_valid_url_http(self):
assert is_url("http://heise.de")
def test_valid_url_https(self):... | normal | {
"blob_id": "021f224d031477bd305644261ad4d79d9eca98b3",
"index": 5474,
"step-1": "<mask token>\n\n\nclass TestURLs:\n\n def test_url_1(self):\n assert is_url('http://heise.de')\n <mask token>\n <mask token>\n <mask token>\n\n def test_valid_url_https_path(self):\n assert is_url('http... | [
3,
4,
7,
8,
10
] |
def guguPrint(n):
print('*' * 30)
for i in range(1, 10):
print('{} X {} = {}'.format(n, i, n * i))
if __name__ =="__main__":
print('Main으로 실행되었음') | normal | {
"blob_id": "aa2e24d80789f2a6ebd63ec42a17499f1e79ca49",
"index": 5237,
"step-1": "<mask token>\n",
"step-2": "def guguPrint(n):\n print('*' * 30)\n for i in range(1, 10):\n print('{} X {} = {}'.format(n, i, n * i))\n\n\n<mask token>\n",
"step-3": "def guguPrint(n):\n print('*' * 30)\n for ... | [
0,
1,
2,
3
] |
#!/usr/bin/python
# This IDAPython code can be used to de-obfuscate strings generated by
# CryptoWall version 3, as well as any other malware samples that make use of
# this technique.
'''
Example disassembly:
.text:00403EC8 mov ecx, 'V'
.text:00403ECD mov [ebp+var_1C], cx
... | normal | {
"blob_id": "e38149f0d421a43f6aa34a977eee89fe29021b85",
"index": 7451,
"step-1": "#!/usr/bin/python\n# This IDAPython code can be used to de-obfuscate strings generated by\n# CryptoWall version 3, as well as any other malware samples that make use of\n# this technique. \n\n'''\nExample disassembly:\n\n\t.text:00... | [
0
] |
# cor = input('Escolha uma cor: ')
# print(f"Cor escolhida {cor:=^10}\n"
# f"Cor escolhida {cor:>10}\n"
# f"Cor escolhida {cor:<10}\n")
n1 = 7
n2 = 3
#print(f'Soma {n1+n2}')
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print(f's = {s}\n m = {m}\n d = {d:.2f}\n di = {di}\n e = {e}', end=... | normal | {
"blob_id": "34b23e80b3c4aaf62f31c19fee0b47ace1561a8c",
"index": 560,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(f\"\"\"s = {s}\n m = {m}\n d = {d:.2f}\n di = {di}\n e = {e}\"\"\", end='')\n",
"step-3": "n1 = 7\nn2 = 3\ns = n1 + n2\nm = n1 * n2\nd = n1 / n2\ndi = n1 // n2\ne = n1 ** n2\nprint... | [
0,
1,
2,
3
] |
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Group,SQLlist
from .forms import GroupForm
from .oraConnect import *
from .utils import IfNoneThenNull
########################### Группы ############################
def group_list(request):
grou... | normal | {
"blob_id": "b9fe758d5fe12b5a15097c0e5a33cb2d57edfdd2",
"index": 7484,
"step-1": "<mask token>\n\n\ndef group_list(request):\n groups = Group.objects.all()\n return render(request, 'group_list.html', {'groups': groups})\n\n\n<mask token>\n\n\ndef group_add(request):\n if request.method == 'POST':\n ... | [
4,
6,
8,
10,
11
] |
import asyncio
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from datetime import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.combining import OrTrigger
from apschedu... | normal | {
"blob_id": "f5a953d91e95d82e84e3e6d18ee89d28ba1b1515",
"index": 6022,
"step-1": "import asyncio\nimport multiprocessing\nfrom concurrent.futures import ProcessPoolExecutor\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom datetime import datetime\nimport time\n\nfrom apscheduler.schedulers.bloc... | [
0
] |
# Copyright 2018-present Kensho Technologies, LLC.
from .utils import create_vertex_statement, get_random_date, get_uuid
EVENT_NAMES_LIST = (
"Birthday",
"Bar Mitzvah",
"Coronation",
"Re-awakening",
)
def _create_event_statement(event_name):
"""Return a SQL statement to create a Event vertex."""... | normal | {
"blob_id": "a521befba58aa85c2fcfe6006db4b161123585f1",
"index": 5341,
"step-1": "<mask token>\n\n\ndef _create_event_statement(event_name):\n \"\"\"Return a SQL statement to create a Event vertex.\"\"\"\n field_name_to_value = {'name': event_name, 'event_date':\n get_random_date(), 'uuid': get_uuid... | [
1,
2,
3,
4,
5
] |
from mysql import connector
def get_db_connection():
try:
return connector.connect(host="server_database_1", user="root", password="password1234", database="SMARTHOUSE")
except connector.errors.DatabaseError:
connection = connector.connect(host="server_database_1", user="root", password="pass... | normal | {
"blob_id": "6cb97e6f3c7ba312ec1458fd51635508a16f70dd",
"index": 2957,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_db_connection():\n try:\n return connector.connect(host='server_database_1', user='root',\n password='password1234', database='SMARTHOUSE')\n except co... | [
0,
1,
2,
3
] |
import random
prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
t=100
print(t)
n=25
for _ in range(t):
a=random.randint(1,n)
b=random.choice(prime)
print(a,b)
for _ in range(a):
print(random.randint(1,n),end=" ")
print("")
| normal | {
"blob_id": "16738e7d89bee8074f39d0b3abc3fa786faf081f",
"index": 2370,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(t)\n<mask token>\nfor _ in range(t):\n a = random.randint(1, n)\n b = random.choice(prime)\n print(a, b)\n for _ in range(a):\n print(random.randint(1, n), end=' ... | [
0,
1,
2,
3,
4
] |
#train a neural network from input video feed
import numpy as np
import cv2
vid = cv2.VideoCapture('trackmania_test_vid.mp4')
w = 1280//2
h = 720//2
vid_data = np.empty((360, 640, 3))
#print(vid_data.shape)
def process_frame(img):
global vid_data
img = cv2.resize(img, (w, h))
cv2.imshow('Frame', img)
... | normal | {
"blob_id": "eb81b0e41743e1785b82e88f6a618dc91eba73e5",
"index": 1389,
"step-1": "<mask token>\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n\n\n<mask token>\n",
"step-2": ... | [
1,
2,
3,
4,
5
] |
from django.utils.html import strip_tags
from rest_framework import serializers
from home.models import *
class SliderSerializer(serializers.ModelSerializer):
class Meta:
model = Slider
fields = "__all__"
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Cate... | normal | {
"blob_id": "b8fa36ed3587511e0c64f0ffc87ea6e7857725d7",
"index": 4595,
"step-1": "<mask token>\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Product\n fields = '__all__'\n\n def to_representation(self, instance):\n data = super().to_representati... | [
5,
6,
8,
9,
10
] |
from javascript import JSConstructor
from javascript import JSObject
cango = JSConstructor(Cango2D)
shapes2d = JSObject(shapes2D)
tweener = JSConstructor(Tweener)
drag2d = JSConstructor(Drag2D)
svgtocgo2d = JSConstructor(svgToCgo2D)
cgo = cango("plotarea")
x1, y1 = 40, 20
cx1, cy1 = 90, 120
x2, y2 = 120, 100
cx2, cy2... | normal | {
"blob_id": "3b19ee0bbd24b76dd8b933859f6a56c459926861",
"index": 5615,
"step-1": "<mask token>\n\n\ndef dragC2(mousePos):\n global cx2, cy2\n cx2 = mousePos.x\n cy2 = mousePos.y\n drawCurve()\n\n\ndef dragC3(mousePos):\n global cx3, cy3\n cx3 = mousePos.x\n cy3 = mousePos.y\n drawCurve()\... | [
3,
5,
6,
7,
8
] |
#!/usr/bin/python3
from datetime import datetime
import time
import smbus
SENSOR_DATA_FORMAT = "Speed: {} km/h\nSteering: {}\nThrottle: {}\nTemperature: {} C"
class SensorDataFrame:
def __init__(self, data):
self.speed, self.steering, self.throttle, self.temp = data
self.timestamp = datetime.now... | normal | {
"blob_id": "cf4170760fe6210d8b06f179484258f4ae3f8796",
"index": 7284,
"step-1": "<mask token>\n\n\nclass SensorDataFrame:\n\n def __init__(self, data):\n self.speed, self.steering, self.throttle, self.temp = data\n self.timestamp = datetime.now()\n\n def __str__(self):\n return SENSOR... | [
4,
6,
7,
8,
9
] |
rom diseas import Disease
from parse import analyzing
from config import FILE_NAME
from random import randint
if __name__ == '__main__':
"""
Main module that runs the program.
"""
def working_with_user(disea):
print('Choose what you want to know about that disease:\naverage_value(will return th... | normal | {
"blob_id": "b33af7aff0f3fde6499d5e24fc036d5bd74b6e47",
"index": 3550,
"step-1": "rom diseas import Disease\nfrom parse import analyzing\nfrom config import FILE_NAME\nfrom random import randint\n\nif __name__ == '__main__':\n \"\"\"\n Main module that runs the program.\n \"\"\"\n def working_with_us... | [
0
] |
"""#########################################################################
Author: Yingru Liu
Institute: Stony Brook University
Descriptions: transer the numpy files of the midi songs into midi files.
(Cause the code privided by RNN-RBM tutorial to save midi
runs in python 2.7 but my ... | normal | {
"blob_id": "af152e0b739305866902ee141f94641b17ff03ea",
"index": 6496,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(20):\n print('The ' + str(i) + '-th graph.')\n Ground_sample = np.load(Ground_FOLDER + 'Ground-True-' + str(i) + '.npy')\n CGRNN_sample = np.load(CGRNN_FOLDER + 'C... | [
0,
1,
2,
3,
4
] |
# -*-coding:utf-8-*-
import os
import time
import shutil
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args... | normal | {
"blob_id": "dc3a3f5675860792ecfa7dcd5180402d89b669b1",
"index": 8254,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', type=str, required=True)\n parser.add_argument('--task', type=str, required=True)\n... | [
0,
1,
2,
3
] |
import unittest
import sys
import matplotlib.pyplot as plotter
import numpy
sys.path.append("/home/adityas/UGA/SensorWeb/scripts/Summer2018/code")
from simulator.component import CPU, DiskIO, Network
class TestComponents(unittest.TestCase):
def setUp(self):
self.cpu = CPU(cycles=5)
self.disk = ... | normal | {
"blob_id": "4f54f3e306df3b861124adb4fe544089446e8021",
"index": 3453,
"step-1": "<mask token>\n\n\nclass TestComponents(unittest.TestCase):\n\n def setUp(self):\n self.cpu = CPU(cycles=5)\n self.disk = DiskIO(cycles=5)\n self.network = Network(cycles=5)\n\n def test_cpu_length(self):\... | [
4,
5,
7,
8,
9
] |
#!/user/bin/env python3 -tt
"""
https://adventofcode.com/2017/day/7
"""
import sys
import re
# Global variables
task="d-7"
infile=task + ".input"
with open('input/' + infile) as file:
input = file.read()
file.close()
class Node:
parent = None
children = None
weight_sum = 0
def __init__(self, na... | normal | {
"blob_id": "679ca76212b90261683d59899c1189280b6b6e8c",
"index": 5953,
"step-1": "<mask token>\n\n\nclass Node:\n parent = None\n children = None\n weight_sum = 0\n\n def __init__(self, name, weight, linked):\n self.name = name\n self.weight = int(weight)\n self.weight_sum += sel... | [
6,
8,
10,
12,
13
] |
""" quiz materials for feature scaling clustering """
# FYI, the most straightforward implementation might
# throw a divide-by-zero error, if the min and max
# values are the same
# but think about this for a second--that means that every
# data point has the same value for that feature!
# why would you rescale it? O... | normal | {
"blob_id": "6a6a7cc6d4f601f4461488d02e03e832bc7ab634",
"index": 2928,
"step-1": "\"\"\" quiz materials for feature scaling clustering \"\"\"\n\n# FYI, the most straightforward implementation might\n# throw a divide-by-zero error, if the min and max\n# values are the same\n# but think about this for a second--th... | [
0
] |
# -*- coding: utf-8 -*-
from sqlalchemy import or_
from ..extensions import db
from .models import User
def create_user(username):
user = User(username)
db.session.add(user)
return user
def get_user(user_id=None, **kwargs):
if user_id is not None:
return User.query.get(user_id)
username ... | normal | {
"blob_id": "49c15f89225bb1dd1010510fe28dba34f6a8d085",
"index": 4866,
"step-1": "<mask token>\n\n\ndef get_user(user_id=None, **kwargs):\n if user_id is not None:\n return User.query.get(user_id)\n username = kwargs.pop('username')\n if username is not None:\n return User.query.filter_by(... | [
1,
2,
3,
4,
5
] |
import copy
from basics.binary_tree.binary_tree import TreeNode
from basics.binary_tree.traversals import level_order_traversal
def max_depth_bottom_up(root):
if not root:
return 0
max_so_far = 0
def max_depth(node, depth):
nonlocal max_so_far
if not node.left and not node.right... | normal | {
"blob_id": "555646a5d57152034b467cbce16b6c183bcfbb37",
"index": 6658,
"step-1": "<mask token>\n\n\ndef max_depth_bottom_up(root):\n if not root:\n return 0\n max_so_far = 0\n\n def max_depth(node, depth):\n nonlocal max_so_far\n if not node.left and not node.right:\n max... | [
8,
9,
12,
14,
15
] |
n = int(input())
p = [220000] + list(map(int, input().split()))
cnt = 0
m = 220000
for i in range(1, n + 1):
now = p[i]
m = min(m, now)
if now == m:
cnt += 1
print(cnt)
| normal | {
"blob_id": "2a500968cf6786440c0d4240430433db90d1fc2f",
"index": 5941,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(1, n + 1):\n now = p[i]\n m = min(m, now)\n if now == m:\n cnt += 1\nprint(cnt)\n",
"step-3": "n = int(input())\np = [220000] + list(map(int, input().spli... | [
0,
1,
2
] |
import csv
import datetime
import json
import re
import requests
import os
r = requests.get("https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids")
path = os.path.dirname(os.path.realpath(__file__)) + "/"
if r.status_code == 200:
text = r.text
pattern = 'Přispěvatel'
m = re.search(patter... | normal | {
"blob_id": "f3329962004a4454c04327da56d8dd1d0f1d45e7",
"index": 763,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start(... | [
0,
1,
2,
3,
4
] |
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import time
import sys
class ConsensusSimulation:
"""Class to model a general consensus problem
see DOI: 10.1109/JPROC.2006.887293"""
def __init__(self,
topology,
dynamics,
dynami... | normal | {
"blob_id": "3164eab8dc221149c9f865645edf9991d810d2ac",
"index": 8698,
"step-1": "<mask token>\n\n\nclass ConsensusSimulation:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def run_sim(self, record_all=False, update_every=1.0):\n \"\"\"run the core simulation\"\"\"\n ... | [
3,
8,
9,
11,
12
] |
#!/usr/bin/python2.7
'''USAGE: completeness.py BLAST_output (tab formatted)
Prints % completeness based on marker gene BLAST of caled genes from a genome
Markers from Lan et al. (2016)
'''
import sys
with open(sys.argv[1],'r') as blastOut:
geneHits = []
orgHits = []
hits = 0.0
for line in blastOut:
hits += 1.0
... | normal | {
"blob_id": "a8659ca7d7a5870fc6f62b3dfee1779e33373e7b",
"index": 8388,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(sys.argv[1], 'r') as blastOut:\n geneHits = []\n orgHits = []\n hits = 0.0\n for line in blastOut:\n hits += 1.0\n currHit = line.split()[1]\n c... | [
0,
1,
2,
3,
4
] |
# 約分して、互いに素な(1,3) (3,1)のようなペアを作りカウントする
# 正のグループと負のグループを別々に管理
# 正のグループの相手が負のグループに存在した場合、
# どちらかのグループから好きなだけ選ぶか、どちらも選ばないかしかない
# 誰ともペアにならなかったグループの個数を全て足してP個だとして、2^P通りを掛ける
# (0,0)については、その中から1つ選ぶか、選ばないかしかない
import sys
readline = sys.stdin.readline
N = int(readline())
import math
zeropair = 0
zeroa = 0
zerob = 0
from coll... | normal | {
"blob_id": "098488fd10bcf81c4efa198a44d2ff87e4f8c130",
"index": 3225,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(N):\n a, b = map(int, readline().split())\n if a == 0 and b == 0:\n zeropair += 1\n continue\n if a == 0:\n zeroa += 1\n continue\n ... | [
0,
1,
2,
3,
4
] |
def getArticle():
text = []
idx = 1
with open('article.txt','r') as f:
data = f.readlines()
for i in data:
if i != '\n':
s = "{ 'id':" + str(idx) + "," + "'text':" + i.rstrip() + " }"
text.append(s)
idx+=1
return text
a = getArticle()
print a
'''
create a list of 100 words article
use javascri... | normal | {
"blob_id": "6591ad20d4a07f29f22b50b6e8998c51e53600d6",
"index": 5686,
"step-1": "def getArticle():\n\ttext = []\n\tidx = 1\n\twith open('article.txt','r') as f:\n\t\tdata = f.readlines()\n\t\tfor i in data:\n\t\t\tif i != '\\n':\n\t\t\t\ts = \"{ 'id':\" + str(idx) + \",\" + \"'text':\" + i.rstrip() + \" }\" \n... | [
0
] |
a = []
for i in range((2 * int(input()))):
a.append(int(input()))
if 1 in a:
c = a.index(max(a))
if a[c + 1] == 1:
print(c)
else:
del a[c]
s = a.index(max(a))
if a[s + 1] == 1:
print(s)
else:
print('-1')
| normal | {
"blob_id": "e3e50df47ef074f13382e249832c065ebdce18a6",
"index": 8406,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(2 * int(input())):\n a.append(int(input()))\nif 1 in a:\n c = a.index(max(a))\n if a[c + 1] == 1:\n print(c)\n else:\n del a[c]\n s = a.ind... | [
0,
1,
2,
3
] |
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from crud.serializers import TodoListSerializer
from crud.models import TodoList
# Create your views here.
class TodoListViewSet(viewsets.ModelViewSet):
queryset = TodoList.objects.all()
seri... | normal | {
"blob_id": "2d4680b63cdd05e89673c4bd6babda7ac6ebb588",
"index": 8895,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass TodoListViewSet(viewsets.ModelViewSet):\n <mask token>\n <mask token>\n\n def delete(self, request, pk=None):\n instance = TodoList.objects.get(id=pk)\n i... | [
0,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 21:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cms', '0020_old_tree_cleanup'),
('styleguide', '00... | normal | {
"blob_id": "85c2a4163a3132794186b95b4068f6c6e1104828",
"index": 1306,
"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 = [('cms', '0020... | [
0,
1,
2,
3,
4
] |
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
if __name__ == "__main__":
dataset = pd.read_csv('./dataset.... | normal | {
"blob_id": "f82c961fc1accd362b34a685bac4cc35d98f44ef",
"index": 6371,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n dataset = pd.read_csv('./dataset.csv')\n X_train, X_test, y_train, y_test = train_test_split(dataset['text'],\n dataset['label'], test_size=0.2, ... | [
0,
1,
2,
3
] |
#define the simple_divide function here
def simple_divide(item, denom):
# start a try-except block
try:
return item/denom
except ZeroDivisionError:
return 0
def fancy_divide(list_of_numbers, index):
denom = list_of_numbers[index]
return [simple_divide(item, denom) for item in lis... | normal | {
"blob_id": "1fbdb0b40f0d65fffec482b63aa2192968b01d4b",
"index": 9766,
"step-1": "def simple_divide(item, denom):\n try:\n return item / denom\n except ZeroDivisionError:\n return 0\n\n\n<mask token>\n",
"step-2": "def simple_divide(item, denom):\n try:\n return item / denom\n ... | [
1,
2,
3,
4,
5
] |
from django.contrib.postgres.fields import JSONField
from django.db import models
from service.models import TimeStampedModel
class Praise(TimeStampedModel):
class Meta:
verbose_name = '칭찬'
verbose_name_plural = verbose_name
content = models.CharField(verbose_name='내용', unique=True, max_leng... | normal | {
"blob_id": "a4db12fee72989f983c1069839dc0a5ede4561a3",
"index": 686,
"step-1": "<mask token>\n\n\nclass PraiseHistory(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬 내역'\n verbose_name_plural = verbose_name\n praise = models.ForeignKey(Praise, verbose_name='칭찬')\n choices = JSON... | [
2,
3,
4,
5
] |
import pytest
from ethereum.tools.tester import TransactionFailed
def test_cant_ever_init_twice(ethtester, root_chain):
ethtester.chain.mine()
with pytest.raises(TransactionFailed):
root_chain.init(sender=ethtester.k0)
with pytest.raises(TransactionFailed):
root_chain.init(sender=ethtester... | normal | {
"blob_id": "8417b63e2b7b16d3d58175022662c5b3e59e4aaf",
"index": 4640,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_cant_ever_init_twice(ethtester, root_chain):\n ethtester.chain.mine()\n with pytest.raises(TransactionFailed):\n root_chain.init(sender=ethtester.k0)\n with p... | [
0,
1,
2
] |
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
result_set = []
letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6':
'mno', '7': 'pqrs', '8': 'tuv', ... | normal | {
"blob_id": "aec311cae7cb6cbe3e3a927a133ec20a2d2afbf5",
"index": 1312,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n ... | [
0,
1,
2
] |
#!/user/bin/env python
# -*- coding: utf-8 -*-
# @Author : XordenLee
# @Time : 2019/2/1 18:51
import itchat
import requests
import sys
default_api_key = 'bb495c529b0e4efebd5d2632ecac5fb8'
def send(user_id, input_text, api_key=None):
if not api_key:
api_key = default_api_key
msg = {
... | normal | {
"blob_id": "15539d824490b7ae4724e7c11949aa1db25ecab2",
"index": 5112,
"step-1": "<mask token>\n\n\ndef send(user_id, input_text, api_key=None):\n if not api_key:\n api_key = default_api_key\n msg = {'reqType': 0, 'perception': {'inputText': {'text': input_text},\n 'selfInfo': {'location': {'... | [
2,
3,
4,
5,
6
] |
#CALCULATE NUMBER OF UPPER AND LOWER CASES
def cnt():
s1=input("enter a string :").strip()
count=0
countu=0
for i in s1:
if(i.islower()):
count+=1
elif(i.isupper()):
countu+=1
else:
pass
print("... | normal | {
"blob_id": "6cfda09f360aaa560011b91db8316e5e3889eea1",
"index": 2017,
"step-1": "<mask token>\n",
"step-2": "def cnt():\n s1 = input('enter a string :').strip()\n count = 0\n countu = 0\n for i in s1:\n if i.islower():\n count += 1\n elif i.isupper():\n countu +... | [
0,
1,
2
] |
import iris
import numpy as np
import matplotlib.pyplot as plt
import glob
import iris.analysis.cartography
import iris.coord_categorisation
import iris.analysis
import time
def my_callback(cube, field, filename):
cube.remove_coord('forecast_reference_time')
cube.remove_coord('forecast_period')
... | normal | {
"blob_id": "6ea651e27620d0f26f7364e6d9d57e733b158d77",
"index": 6466,
"step-1": "import iris\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport iris.analysis.cartography\nimport iris.coord_categorisation\nimport iris.analysis\nimport time\n\ndef my_callback(cube, field, filename):\n ... | [
0
] |
# -*- coding: utf-8 -*-
"""
Created on Mon May 2 17:24:00 2016
@author: pasca
"""
# -*- coding: utf-8 -*-
import os.path as op
from nipype.utils.filemanip import split_filename as split_f
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec
from nipype.interfaces.base import traits, File, Trait... | normal | {
"blob_id": "d9cdcf64042c3c6c4b45ec0e3334ba756dd43fcd",
"index": 5066,
"step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 2 17:24:00 2016\n\n@author: pasca\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport os.path as op\n\nfrom nipype.utils.filemanip import split_filename as split_f\n\nfrom nipype.interfac... | [
0
] |
from . import find_resault
from . import sql
| normal | {
"blob_id": "6f05d1915cd2e123dd72233b59d4de43fd724035",
"index": 7743,
"step-1": "<mask token>\n",
"step-2": "from . import find_resault\nfrom . import sql\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
"""
\tSeja bem-vindo ao Admirável Mundo Novo!
\tO objetivo do jogo é dar suporte ao desenvolvimento de Agentes Inteligentes que utilizam Deep Reinforcement Learning
\tpara tarefas de Processamento de Linguagem Natural em língua portuguesa.
\tAutor: Gabriel Pontes (@ograndoptimist)
"""
import random
fr... | normal | {
"blob_id": "38ffbb6a66837e975a611a57579bb365ab69a32c",
"index": 9504,
"step-1": "<mask token>\n\n\nclass AdmiravelMundoNovo(object):\n <mask token>\n <mask token>\n\n def transicao_estado(self, acao):\n if self._valor_estado == 2 and acao == 0:\n self._estado_6()\n elif self._v... | [
18,
21,
23,
25,
28
] |
import tensorflow as tf
import numpy as np
from datetime import datetime
import os
from CNN import CNN
from LSTM import LSTM
from BiLSTM import BiLSTM
from SLAN import Attention
from HAN2 import HierarchicalAttention
import sklearn.metrics as metrics
import DataProcessor as dp
import matplotlib.pyplot as plt
import num... | normal | {
"blob_id": "3aff6bdfd7c2ffd57af7bb5d0079a8a428e02331",
"index": 1284,
"step-1": "<mask token>\n\n\ndef evaluate(sess, data, embds, model, logdir):\n checkpoint_dir = '{}checkpoints'.format(logdir)\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n sess.run(model.embedding_ini... | [
5,
6,
8,
9,
10
] |
"""
Script: coverage.py
Identifies domains that only occur in multi-domain proteins. The main
script is master.
--------------------
Felix A Kruger
momo.sander@ebi.ac.uk
"""
####
#### import modules.
####
import queryDevice
import operator
import yaml
import time
####
#### Load parameters.
####... | normal | {
"blob_id": "2467825d2cb01c86d3ba27562decc12551877af1",
"index": 457,
"step-1": "\"\"\"\n Script: coverage.py\n Identifies domains that only occur in multi-domain proteins. The main\n script is master.\n --------------------\n Felix A Kruger\n momo.sander@ebi.ac.uk\n\"\"\"\n####\n#### import m... | [
0
] |
from flask_restful import Resource, reqparse
from db import query
import pymysql
from flask_jwt_extended import jwt_required
"""
This module is used to retrieve the data
for all the request_no's which have a false or a 0 select_status.
This is done by selecting distinct request_no's from requests table
for ... | normal | {
"blob_id": "d436362468b847e427bc14ca221cf0fe4b2623e3",
"index": 4408,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass AdminReqNoDetails(Resource):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass AdminReqNoDetails(Resource):\n\n @jwt_required\n def get(self):\n parser = r... | [
0,
1,
2,
3,
4
] |
from connect.client import ClientError, ConnectClient, R
def test_import_client():
from cnct import ConnectClient as MovedConnectClient
assert MovedConnectClient == ConnectClient
def test_import_error():
from cnct import ClientError as MovedClientError
assert MovedClientError == ClientError
def te... | normal | {
"blob_id": "e5a71250ca9f17798011d8fbfaee6a3d55446598",
"index": 6145,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_import_error():\n from cnct import ClientError as MovedClientError\n assert MovedClientError == ClientError\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef tes... | [
0,
1,
2,
3,
4
] |
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_f... | normal | {
"blob_id": "4d059d1ca407ef60f1fbf9d8bead1cf45c90c28a",
"index": 8227,
"step-1": "<mask token>\n\n\nclass RegisterViewSet(viewsets.ModelViewSet):\n queryset = models.Register.objects.all()\n serializer_class = serializers.RegisterSerializer\n permission_classes = IsAuthenticatedOrReadOnly, ForumPermissi... | [
10,
17,
18,
20,
22
] |
with open("input_trees.txt") as file:
map = file.readlines()
map = [ line.strip() for line in map ]
slopes = [(1,1), (3,1), (5,1), (7,1),(1,2)]
total = 1
for slope in slopes:
treeCount = 0
row, column = 0, 0
while row + 1 < len(map):
row += slope[1]
column += slope[0]
sp... | normal | {
"blob_id": "685fa78b9c3ec141ce1e9ab568e4ad8a0565d596",
"index": 4285,
"step-1": "<mask token>\n",
"step-2": "with open('input_trees.txt') as file:\n map = file.readlines()\n map = [line.strip() for line in map]\n<mask token>\nfor slope in slopes:\n treeCount = 0\n row, column = 0, 0\n while row... | [
0,
1,
2,
3
] |
class Meta(type):
def __new__(meta, name, bases, class_dict):
print(f'* Running {meta}.__new__ for {name}')
print("Bases:", bases)
print(class_dict)
return type.__new__(meta, name, bases, class_dict)
class MyClass(metaclass=Meta):
stuff = 123
def foo(self):
pass
cl... | normal | {
"blob_id": "8f3abc5beaded94b6d7b93ac2cfcd12145d75fe8",
"index": 522,
"step-1": "<mask token>\n\n\nclass MySubClass(MyClass):\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass MyClass2:\n stuff = 123\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n print(f'* Runn... | [
8,
12,
14,
15,
17
] |
"""
采集端任务状态统计
直接在数据库查找数据
create by judy 2018/10/22
update by judy 2019/03/05
更改统一输出为output
"""
from datetime import datetime
import time
import traceback
import pytz
from datacontract import ETaskStatus
from datacontract.clientstatus.statustask import StatusTask
from idownclient.clientdbmanager import DbManager
from... | normal | {
"blob_id": "de0d0588106ab651a8d6141a44cd9e286b0ad3a5",
"index": 1299,
"step-1": "<mask token>\n\n\nclass ClientTaskStatus(object):\n <mask token>\n <mask token>\n\n def start(self):\n while True:\n try:\n self.get_task_status_info()\n lines = StatusTask(s... | [
2,
3,
4,
5,
6
] |
from tkinter import *
from tkinter import filedialog
from tkinter import scrolledtext
import tkinter as tk
import os
import sys
import subprocess
import shlex
from subprocess import check_output
import pathlib
| normal | {
"blob_id": "11576597429e119cf4887a88139df4a9e6d7eb66",
"index": 1409,
"step-1": "<mask token>\n",
"step-2": "from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import scrolledtext\nimport tkinter as tk\nimport os\nimport sys\nimport subprocess\nimport shlex\nfrom subprocess import check_outpu... | [
0,
1
] |
#!/usr/bin/env python
from program_class import Program
import tmdata
import os
def main():
""""""
args1 = {"progname" : "whoami",
"command" : "/usr/bin/whoami",
"procnum" : 1,
"autolaunch" : True,
"starttime" : 5,
"restart" : "never",
"retries" : 2,
"stopsig" : "SSIG",
"stoptime" : 10,
"e... | normal | {
"blob_id": "c58f40d369388b94778e8583176f1ba8b81d0c5e",
"index": 4083,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n \"\"\"\"\"\"\n args1 = {'progname': 'whoami', 'command': '/usr/bin/whoami', 'procnum':\n 1, 'autolaunch': True, 'starttime': 5, 'restart': 'never',\n ... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
"""
mahjong.playerhand
"""
from collections import Counter
from melds import (DiscardedBy, Chow, Pung, Kong)
from shanten import (
count_shanten_13_orphans,
count_shanten_seven_pairs,
count_shanten_std)
import tiles
from walls import TileWallAgent
class PlayerHand:
"""Player's... | normal | {
"blob_id": "5b860144a592505fea3a8849f5f5429a39ab9053",
"index": 7299,
"step-1": "<mask token>\n\n\nclass PlayerHand:\n <mask token>\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n if isin... | [
18,
19,
21,
23,
25
] |
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['savefig.dpi'] = 300 #图片像素
plt.rcParams['figure.dpi'] = 300 #分辨率
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x_axis = [20,40,60,80,100]
rf = [184,174,166,159,157.5]
anns = [186,179,170,164,161]
adaboost = [187.5,1... | normal | {
"blob_id": "13342922022f0a0e8928c81c1c4716125af0b2c4",
"index": 418,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nax.set_xticks(x + width / 2)\nax.set_xticklabels(x_axis)\nplt.legend((p_rf[0], p_anns[0], p_adaboost[0]), ('RF', 'ANNs', 'AdaBoost'),\n loc='best', fontsize=20)\nplt.xticks(fontsize=18)... | [
0,
1,
2,
3,
4
] |
from collections import Counter
class Solution:
def countStudents(self, students, sandwiches) ->int:
if not students or not sandwiches:
return 0
while students:
top_san = sandwiches[0]
if top_san == students[0]:
students = students[1:]
... | normal | {
"blob_id": "235fce2615e2a5879f455aac9bcecbc2d152679b",
"index": 4548,
"step-1": "<mask token>\n\n\nclass Solution:\n\n def countStudents(self, students, sandwiches) ->int:\n if not students or not sandwiches:\n return 0\n while students:\n top_san = sandwiches[0]\n ... | [
2,
3,
5,
6
] |
import os
import numpy as np
import warnings
import soundfile as sf
def load_path():
path = os.path.join(os.path.dirname(__file__))
if path == "":
path = "."
return path
def create_folder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except... | normal | {
"blob_id": "cab233976653b8135276ff849955f32766833354",
"index": 7555,
"step-1": "<mask token>\n\n\ndef load_path():\n path = os.path.join(os.path.dirname(__file__))\n if path == '':\n path = '.'\n return path\n\n\ndef create_folder(directory):\n try:\n if not os.path.exists(directory):... | [
3,
4,
6,
7,
8
] |
# Converts text to speech in different accents. Requires pip3 install gTTS
from gtts import gTTS
import os
language_code = """
Language Code
-------- ----
Afrikaans af
Albanian sq
Arabic ar
Belarusian be
Bulgarian bg
Catalan ca
Chinese Simplified zh-CN
Chinese Traditional zh-T... | normal | {
"blob_id": "545053bc2b7c8687622d747673f2ad37b978014c",
"index": 3403,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\"We're going to speak anything you type in a different accent\")\n<mask token>\nprint(language_code)\n<mask token>\nmyobj.save('texty.mp3')\nos.system('mpg321 texty.mp3')\n",
"st... | [
0,
1,
2,
3,
4
] |
# Python : Correct way to strip <p> and </p> from string?
s = s.replace('<p>', '').replace('</p>', '')
| normal | {
"blob_id": "7b6e73744d711188ab1a622c309b8ee55f3eb471",
"index": 7427,
"step-1": "<mask token>\n",
"step-2": "s = s.replace('<p>', '').replace('</p>', '')\n",
"step-3": "# Python : Correct way to strip <p> and </p> from string?\ns = s.replace('<p>', '').replace('</p>', '')\n",
"step... | [
0,
1,
2
] |
import math
import numpy as np
from statistics import median
from src.filter.median import quickselect_median
def bilateral_median_filter(flow, log_occlusen, auxiliary_field, image, weigth_auxiliary, weigth_filter,
sigma_distance = 7, sigma_color =7 / 200, filter_size=5):
"""
:par... | normal | {
"blob_id": "1748c8dfcc3974b577d7bfacb5cabe4404b696bc",
"index": 612,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef bilateral_median_filter(flow, log_occlusen, auxiliary_field, image,\n weigth_auxiliary, weigth_filter, sigma_distance=7, sigma_color=7 / 200,\n filter_size=5):\n \"\"\"\n\... | [
0,
1,
2,
3
] |
from flask import Flask
from flask_mongoengine import MongoEngine
db = MongoEngine()
def create_app(**config_overrides):
app = Flask(__name__)
app.config.from_pyfile('settings.py')
app.config.update(config_overrides)
db.init_app(app)
from user.views import user_app
app.register_blueprint(user_... | normal | {
"blob_id": "8b7fb0789d197e50d7bdde2791b6fac964782469",
"index": 4001,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef create_app(**config_overrides):\n app = Flask(__name__)\n app.config.from_pyfile('settings.py')\n app.config.update(config_overrides)\n db.init_app(app)\n from user... | [
0,
1,
2,
3
] |
#!/usr/bin/python
# encoding: utf-8
#
# In case of reuse of this source code please do not remove this copyright.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | normal | {
"blob_id": "a7218971b831e2cfda9a035eddb350ecf1cdf938",
"index": 17,
"step-1": "#!/usr/bin/python\n# encoding: utf-8\n#\n# In case of reuse of this source code please do not remove this copyright.\n#\n#\tThis program is free software: you can redistribute it and/or modify\n#\tit under the terms of the GNU Gener... | [
0
] |
def calcula_norma(x):
lista=[]
for e in x:
lista.append(e**2)
v=(sum(lista)**(1/2))
return v | normal | {
"blob_id": "7346992d69250240207a0fc981d0adc245e69f87",
"index": 5206,
"step-1": "<mask token>\n",
"step-2": "def calcula_norma(x):\n lista = []\n for e in x:\n lista.append(e ** 2)\n v = sum(lista) ** (1 / 2)\n return v\n",
"step-3": "def calcula_norma(x):\n lista=[]\n for e in x:\n... | [
0,
1,
2
] |
#!/usr/bin/env python
# Title : STACK_BostonHousing.py
# Description : Stacking was the natural progression of our algorithms trial.
# In here, we'll use prediction from a number of models in order
# to improve accuracy as it add linearly independent data to our
# ... | normal | {
"blob_id": "21c581131cff8cf2f4aa407055184d56865a6335",
"index": 9783,
"step-1": "<mask token>\n\n\nclass Ensemble(object):\n \"\"\"Ensemble base_models on train data than fit/predict\n\n The object input is composed of 'n_splits', 'stacker' and list of\n 'base_models'.\n\n The __init__ method self-a... | [
4,
5,
6,
7,
8
] |
import tkinter
from tkinter import messagebox
from random import randint
tplyer = 0
tcomp = 0
player = 0
comp = 0
top = tkinter.Tk()
top.resizable(width = False, height =False)
top.geometry("200x100")
def Yes():
global player
global comp
tplayer = randint(1,6)
tcomp = randint(1,6)
message =""
if tplay... | normal | {
"blob_id": "0a5baacf17d33dbf6ea69114a8632f7fcef52c3c",
"index": 9419,
"step-1": "<mask token>\n\n\ndef Yes():\n global player\n global comp\n tplayer = randint(1, 6)\n tcomp = randint(1, 6)\n message = ''\n if tplayer > tcomp:\n message = 'Wygrales!'\n player += 1\n elif tplay... | [
2,
3,
4,
5,
6
] |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from glob import glob
from moviepy.editor import VideoFileClip
output_images_dir = './output_images/'
test_images_dir = './test_images/'
output_video_file = 'output.mp4'
mtx = None
dist = None
def load_image(filename):
... | normal | {
"blob_id": "3ac30240577eda08343796abbd051d5d3b45beaf",
"index": 3416,
"step-1": "<mask token>\n\n\ndef load_image(filename):\n return mpimg.imread(filename)\n\n\ndef calibrate_camera(rows=6, cols=9):\n mtx = None\n dist = None\n save_file = 'calibration.npz'\n try:\n data = np.load(save_fi... | [
14,
17,
18,
19,
20
] |
#!/usr/bin/env python3
"""
Main chat API module
"""
import json
import os
import signal
import traceback
import tornado.escape
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.locks
import tornado.web
from jsonschema.exceptions import ValidationError
from db import DB, DatabaseError
... | normal | {
"blob_id": "9f8d79d141d414c1256e39f58e59f97711acfee4",
"index": 4915,
"step-1": "<mask token>\n\n\nclass MainHandler(BaseHandler):\n <mask token>\n\n def get(self):\n \"\"\"Returns the root endpoint of the API.\"\"\"\n self.write(\n '{\"error\": \"cryptochat-server main page, plea... | [
17,
19,
22,
25,
31
] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .BLWecc import (
curve,
setCurve,
getPublicKey,
getPrivateKey,
getAddress as getAddressByCode,
pub2add as getAddressByPublicKey,
sign,
verifyTx as verify,
)
| normal | {
"blob_id": "25ee13314c7cf828b8805d9f483bd5ee12073228",
"index": 8004,
"step-1": "<mask token>\n",
"step-2": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom .BLWecc import curve, setCurve, getPublicKey, getPrivateKey, getAddress as getAddres... | [
0,
1,
2
] |
# Generated by Django 3.1 on 2020-09-26 03:46
import datetime
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('bcs', '0002_auto_20200915_2245'),
]
operations = [
migrations.AddField(
model_name='s... | normal | {
"blob_id": "61484d9a08f2e3fcd15573ce89be4118a442dc2e",
"index": 6062,
"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 = [('bcs', '0002... | [
0,
1,
2,
3,
4
] |
#! /usr/bin/env python
from thor.tree import TreeNode
class Solution(object):
def postorder_traversal(self, root: TreeNode):
if not root:
return []
else:
return self.postorder_traversal(root.left) + self.postorder_traversal(root.right) + [root.val]
| normal | {
"blob_id": "1d314a04625cfadf574f122b95577c1e677a8b35",
"index": 3247,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution(object):\n\n def postorder_traversal(self, root: TreeNode):\n if not root:\n ... | [
0,
1,
2,
3,
4
] |
from marko.parser import Parser # type: ignore
from marko.block import Heading, Paragraph, CodeBlock, List # type: ignore
from marko.inline import CodeSpan # type: ignore
from langcreator.common import Generators, InputOutputGenerator, tag_regex, get_tags, builtin_generators
import collections
import re
def parse(... | normal | {
"blob_id": "0bbc8aa77436193ab47c0fe8cf0d7c6dffcfe097",
"index": 8066,
"step-1": "<mask token>\n\n\ndef _check_tags(generator: InputOutputGenerator, name: str):\n for output, inputs in generator.items():\n necessary_tags = dict(collections.Counter(get_tags(output)))\n for index, input in enumera... | [
4,
5,
6,
7,
8
] |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv('regression.csv')
print(data)
x=data.iloc[:,0]
y=data.iloc[:,1]
mx=data['X1'].mean()
my=data['Y'].mean()
print(mx,my)
num, den = 0,0
for i in range(len(x)):
num += (x[i] - mx)*(y[i]-my)
den += (x[i]-mx)**2
be... | normal | {
"blob_id": "ca6b064dbd8200c49665eaa944fdf1fc80c25726",
"index": 1047,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(data)\n<mask token>\nprint(mx, my)\n<mask token>\nfor i in range(len(x)):\n num += (x[i] - mx) * (y[i] - my)\n den += (x[i] - mx) ** 2\n<mask token>\nprint(beta1, beta0)\n<mas... | [
0,
1,
2,
3,
4
] |
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | normal | {
"blob_id": "13c0af340c4fff815919d7cbb1cfd3116be13771",
"index": 7907,
"step-1": "<mask token>\n\n\nclass PyHookableTests(PyHookableMixin, unittest.TestCase):\n\n def test_pure_python(self):\n from zope.hookable import _PURE_PYTHON\n from zope.hookable import _c_hookable\n from zope.hooka... | [
20,
24,
28,
30,
35
] |
import json
import pandas as pd
import matplotlib.pyplot as plt
f = open('Maradona-goals.json')
jsonObject = json.load(f)
f.close()
l = []
for c, cl in jsonObject.items():
for d in cl:
d.update({'player' : c})
l.append(d)
df = pd.DataFrame(l)
labels = df["year"]
width = 0.75
fig = plt.figure(f... | normal | {
"blob_id": "33e9e45fbe0e3143d75d34c1db283c01e2693f68",
"index": 4967,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nf.close()\n<mask token>\nfor c, cl in jsonObject.items():\n for d in cl:\n d.update({'player': c})\n l.append(d)\n<mask token>\nax.set_xticks(labels)\nax.set_xticklabels(... | [
0,
1,
2,
3,
4
] |
from console import Display
import time
images = ["/img/erni_l.txt", "/img/erni_s.txt", "/img/erni_logo.txt", "/img/github_logo.txt",
"/img/upython_logo.txt", "/img/python_logo.txt", "/img/upython_logo_s.txt",
"/img/MSC_logo.txt"]
def show():
oled = Display()
for image in images:
... | normal | {
"blob_id": "1930aa258ac4fbcdb2972e19bdb2625d2dae4114",
"index": 9403,
"step-1": "<mask token>\n\n\ndef show():\n oled = Display()\n for image in images:\n oled.clear(0, 1)\n oled.draw_graphic(image, 35, 2)\n time.sleep(5)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef show()... | [
1,
2,
3,
4,
5
] |
input("")
things = []
class thing():
def __init__(self, loc, mass = 1, xrad = 1, yrad = 1):
global things
things += [self]
self.location = loc
self.gravity = [0, -0.5]
self.__velocity = [0, 0]
self.mass = mass
self.xrad = xrad
self.yrad = yrad
self.immobile = False
self.collidab... | normal | {
"blob_id": "0afb07d9b48ec91909aac6782dd3cf2fbe388fb4",
"index": 2834,
"step-1": "input(\"\")\r\nthings = []\r\n\r\nclass thing():\r\n\tdef __init__(self, loc, mass = 1, xrad = 1, yrad = 1):\r\n\t\tglobal things\r\n\t\tthings += [self]\r\n\t\t\r\n\t\tself.location = loc\r\n\t\tself.gravity = [0, -0.5]\r\n\t\tse... | [
0
] |
from settings import *
helpMessage = '''
**Vocal / Musique**
`{0}join`
Va rejoindre le salon vocale dans laquelle vous êtes.
`{0}leave`
Va partir du salon vocale dans laquelle vous êtes.
`{0}play [YouTube Url]` *ou* `{0}play [musique ou video à rechercher]`
Commencera à jouer l'audio de la vidéo / chans... | normal | {
"blob_id": "f7283750923e1e430ff1f648878bbb9a0c73d2c4",
"index": 7880,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nhelpMessage = (\n \"\"\"\n**Vocal / Musique**\n\n`{0}join`\nVa rejoindre le salon vocale dans laquelle vous êtes.\n\n`{0}leave`\nVa partir du salon vocale dans laquelle vous êtes.\n\n`... | [
0,
1,
2,
3
] |
from flask import Flask, render_template, url_for, request, redirect, session, flash
import os, json
from usuarios import crearUsuario, comprobarUsuario
from busqueda import filtrado
from compra import procesarCompra, Dinero
app = Flask(__name__)
catalogo_data = json.loads(open(os.path.join(app.root_path,'json/catalo... | normal | {
"blob_id": "ebb4cf1ec2baa7bd0d29e3ae88b16e65cf76a88a",
"index": 3679,
"step-1": "<mask token>\n\n\n@app.route('/info/<pelicula>', methods=['GET', 'POST'])\ndef informacionPelicula(pelicula):\n peliculas = catalogo_data['peliculas']\n if request.method == 'POST':\n return redirect(url_for('index'), ... | [
9,
12,
13,
15,
16
] |
# -*- coding: utf-8 -*-
# @time : 2021/1/10 10:25
# @Author : Owen
# @File : mainpage.py
from selenium.webdriver.common.by import By
from homework.weixin.core.base import Base
from homework.weixin.core.contact import Contact
'''
企业微信首页
'''
class MainPage(Base):
#跳转到联系人页面
def goto_contact(self):
... | normal | {
"blob_id": "7775d260f0db06fad374d9f900b03d8dbcc00762",
"index": 6504,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass MainPage(Base):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass MainPage(Base):\n\n def goto_contact(self):\n self.find(By.CSS_SELECTOR, '#menu_contacts').c... | [
0,
1,
2,
3,
4
] |
import os
from os import listdir
from openpyxl import load_workbook, Workbook
ROOT_PATH = os.getcwd()
# print(f'ROOT_PATH : {ROOT_PATH}')
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
# print(f'CUR_PATH : {CUR_PATH}')
path = f'{ROOT_PATH}/xlsx_files'
files = listdir(path)
result_xlsx = Workbook()
result_sheet... | normal | {
"blob_id": "d23700f03e8498a5ff3d1d03d8808048ba79a56b",
"index": 9381,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor myfile in files:\n if myfile[-4:] != 'xlsx':\n continue\n tg_xlsx = load_workbook(os.path.join(path, myfile), read_only=True)\n tg_sheet = tg_xlsx.active\n for row ... | [
0,
1,
2,
3,
4
] |
from pydub import AudioSegment
import sys
import tensorflow as tf
import numpy as np
from adwtmk.audio import Audio
from adwtmk.encoder import *
from adwtmk.decoder import *
class DAE(object):
def __init__(self,model_name):
self.model_name = model_name
self.process = 0
self.loss = 0
... | normal | {
"blob_id": "6f53702d9265a7fc57d2ec2e47dc35a0bc7a9f87",
"index": 9012,
"step-1": "<mask token>\n\n\nclass DAE(object):\n <mask token>\n <mask token>\n\n def fast_training(self, sound):\n self.core_size = 100\n self.batch_size = 1000\n self.Epoches = 50\n self._main(sound, 100... | [
4,
6,
9,
10,
12
] |
##armstrong number##
##n= int(input('enter a number '))
##a=n
##s=0
##
##while n>0:
## rem= n%10
## s= s+rem*rem*rem
## n= n//10
##if a==s:
## print(a,' is an armstrong number')
##else:
## print(a,' is not an armstrong number')
##palindrome or not##
##n= int(input('enter a number ... | normal | {
"blob_id": "6be285f9c48a20934c1846785232a73373c7d547",
"index": 1043,
"step-1": "##armstrong number##\r\n##n= int(input('enter a number '))\r\n##a=n\r\n##s=0\r\n##\r\n##while n>0:\r\n## rem= n%10\r\n## s= s+rem*rem*rem\r\n## n= n//10\r\n##if a==s:\r\n## print(a,' is an armstrong number')\r\n##else:\... | [
1
] |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.lines import Line2D
np.random.seed(42)
n_samples = 5000
MU = np.array([0.5, 1.5])
COV = np.array([[1., 0.7], [0.7, 2.]])
def get_samples(n):
return np.random.multivariate_normal(me... | normal | {
"blob_id": "d61b04539295f6b25e7f6589d32f313e3c6df82f",
"index": 1180,
"step-1": "<mask token>\n\n\nclass BackgroundCheck(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def predict_proba(self, x):\n return self.prob_background(x)\n\n\nclass GaussianEstimation(objec... | [
8,
10,
12,
13,
17
] |
#!/usr/bin/env python
# encoding: UTF-8
'''
Script to select current version for a given soft (python, ruby or java).
'''
import os
import re
import sys
import glob
import getopt
# fix input in Python 2 and 3
try:
input = raw_input # pylint: disable=redefined-builtin,invalid-name
except NameError:
pass
cl... | normal | {
"blob_id": "93e8e9fc4f0503dfc3243bef5ab8261a4cdfc296",
"index": 1009,
"step-1": "<mask token>\n\n\nclass Version(object):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, soft):\n \"\"\"\n Constructor that takes software name\n \"\"\"\n self.soft = soft... | [
5,
6,
7,
8,
10
] |
import argparse
import sys
def get_precision_values(input_file):
prec_values = []
all_precs = []
means = []
medians = []
methods = []
with open(input_file) as lines:
for line in lines:
if "RESULTS_AGGREGATION" in line:
tokens = line.strip().split(',')
... | normal | {
"blob_id": "9976eb2dd84448b37b81629d352f4a7490ab2316",
"index": 2546,
"step-1": "import argparse\nimport sys\n\ndef get_precision_values(input_file):\n prec_values = []\n all_precs = []\n means = []\n medians = []\n methods = []\n with open(input_file) as lines:\n for line in lines:\n ... | [
0
] |
import numpy as np
import pickle
import preprocessor
import pandas as pd
import sys
from scipy import spatial
class Predict:
def __init__(self, text):
"""
taking the user input string
loading trained feature numpy array
loading the output for the numpy array
loading the ve... | normal | {
"blob_id": "26df6ddf3533a8648b59f0fa2b03f89c93af7491",
"index": 8154,
"step-1": "<mask token>\n\n\nclass Predict:\n\n def __init__(self, text):\n \"\"\"\n taking the user input string\n loading trained feature numpy array\n loading the output for the numpy array\n loading t... | [
3,
4,
5,
6
] |
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# Version: major.minor.patch
VERSION = "1.0.1"
REQUIREMENTS = (HERE / "requirements.txt").read_text()
REQUIREMENTS = REQUIREME... | normal | {
"blob_id": "f563bb5bb32d3653d8a4115c75eda80b676ae3c6",
"index": 5759,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='Antennass', version=VERSION, description=\n 'A class project that plots far field antenna array patterns',\n long_description=README, long_description_content_type='text... | [
0,
1,
2,
3,
4
] |
from pytube import YouTube, Playlist
import json
import sys
import os
import urllib.request
p = os.path.abspath('appdata')
def collect(yt, dir):
code = yt.thumbnail_url
urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))
out = yt.streams.filter(only_audio=True, file_extension='mp4').ord... | normal | {
"blob_id": "06dd963b62c0a746438dcf01c67ef5de1a4c5e8f",
"index": 1558,
"step-1": "<mask token>\n\n\ndef collect(yt, dir):\n code = yt.thumbnail_url\n urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))\n out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(\n ... | [
3,
4,
5,
6
] |
#--------------------------------------------------------------------------------
# G e n e r a l I n f o r m a t i o n
#--------------------------------------------------------------------------------
# Name: Exercise 2.6 - Planetary Orbits
#
# Usage: Calculate information for planetary orbits
#
# Description: ... | normal | {
"blob_id": "83b65b951b06b117c2e85ba348e9b591865c1c2e",
"index": 3145,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('v2: {0}\\tL2: {1}'.format(v2, L2))\n<mask token>\nprint('T: {0}\\te:{1}'.format(T, e))\n",
"step-3": "L1 = float(input('Enter distance to the sun: '))\nv1 = float(input('Enter ve... | [
0,
1,
2,
3
] |
TOTAL = 1306336
ONE = {
'0': 1473,
'1': 5936,
'2': 3681,
'3': 2996,
'4': 2480,
'5': 2494,
'6': 1324,
'7': 1474,
'8': 1754,
'9': 1740,
'a': 79714,
'b': 83472,
'c': 78015,
'd': 61702,
'e': 42190,
'f': 68530,
'g': 48942,
'h': 63661,
'i': 34947,
'j': 24312,
'k': 26724,
'l': 66351,
'm': 77245,
'n': 36942,
'o': 40744,
'p': ... | normal | {
"blob_id": "f254f93193a7cb7ed2e55e4481ed85821cafcd7b",
"index": 4339,
"step-1": "<mask token>\n",
"step-2": "TOTAL = 1306336\nONE = {'0': 1473, '1': 5936, '2': 3681, '3': 2996, '4': 2480, '5': 2494,\n '6': 1324, '7': 1474, '8': 1754, '9': 1740, 'a': 79714, 'b': 83472, 'c':\n 78015, 'd': 61702, 'e': 4219... | [
0,
1,
2
] |
from otree.api import Currency as c, currency_range
from . import models
from ._builtin import Page, WaitPage
from .models import Constants
class Introduction(Page):
timeout_seconds = 60
class Welcome(Page):
timeout_seconds = 60
class Priming(Page):
form_model = models.Player
form_fields = ['text'... | normal | {
"blob_id": "8fecfdf4b3772e5304f0b146317f94cdbd7fbd53",
"index": 5791,
"step-1": "<mask token>\n\n\nclass Eye11(Page):\n form_model = models.Player\n form_fields = ['option_11']\n timeout_seconds = 10\n\n\nclass Eye12(Page):\n form_model = models.Player\n form_fields = ['option_12']\n timeout_s... | [
76,
81,
85,
100,
105
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.