code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
# hi :)
import numpy as np
import random
from copy import deepcopy
# initialization....
# see also prepare.sh
header = np.loadtxt("header.txt", dtype=int)
TIME = header[2]
CARS = header[3]
STARTPOINT = header[4]
GRAPH = np.loadtxt("links.txt",dtype=int)
number_of_links = GRAPH.shape[0]
N = len(GRAPH[:,1])
VOI... | normal | {
"blob_id": "9a9fdf0f3cfb876a384059f3dcf2508f960168c2",
"index": 2167,
"step-1": "# hi :)\nimport numpy as np\nimport random\nfrom copy import deepcopy\n\n\n# initialization....\n# see also prepare.sh\n\nheader = np.loadtxt(\"header.txt\", dtype=int)\nTIME = header[2]\nCARS = header[3]\nSTARTPOINT = header[... | [
0
] |
from sys import stdin
def IsPrime(x):
for i in range(2, int(x ** 0.5) + 1):
if not x % i:
return False
return True
for x in stdin:
x = x[:-1]
y = x[::-1]
a = IsPrime(int(x))
b = IsPrime(int(y))
if not a:
print("%s is not prime." %x)
elif (a and not ... | normal | {
"blob_id": "fcfec521e071aa586febc74efb2deb0e9d0a331e",
"index": 3358,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef IsPrime(x):\n for i in range(2, int(x ** 0.5) + 1):\n if not x % i:\n return False\n return True\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef I... | [
0,
1,
2,
3,
4
] |
from pirates.teleport.AreaTeleportActor import AreaTeleportActor
class DoorTeleportActor(AreaTeleportActor):
pass
| normal | {
"blob_id": "b679444fde7cd8eb819443922f37ee54c0f29de4",
"index": 424,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass DoorTeleportActor(AreaTeleportActor):\n pass\n",
"step-3": "from pirates.teleport.AreaTeleportActor import AreaTeleportActor\n\n\nclass DoorTeleportActor(AreaTeleportActor):... | [
0,
1,
2
] |
#-*- coding:UTF-8 -*-
year = int(input('请输入一个年份:'))
"""
if(year % 4) == 0:
if(year % 100) == 0:
if(year % 400) == 0:
print('{0}是润年'.format(year))
else:
print('{0}不是润年'.format(year))
else:
print('{0}是润年'.format(year))
else:
print('{0}不是润年'.format(year)) ... | normal | {
"blob_id": "78178ec8474a3deb876ab7d3950cd427d7a795d5",
"index": 2218,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n print('{0}是润年'.format(year))\nelse:\n print('{0}不是润年'.format(year))\n",
"step-3": "year = int(input('请输入一个年份:'))\n<mask ... | [
0,
1,
2,
3
] |
from django.urls import path
from redjit.post.views import MyPost, PostView
urlpatterns = [
path('newpost/', MyPost.as_view(), name='newpost')
path('subredjit/<subredjit>/<post_id>/', PostView.as_view(), name='post')
] | normal | {
"blob_id": "e0fc7e5771f6cb8e0638bc8c9549cfe1a92d3d82",
"index": 8719,
"step-1": "from django.urls import path\nfrom redjit.post.views import MyPost, PostView\n\n\n\nurlpatterns = [\n path('newpost/', MyPost.as_view(), name='newpost')\n path('subredjit/<subredjit>/<post_id>/', PostView.as_view(), name='pos... | [
0
] |
# For better usage on ddp
import torch
from pytorch_lightning.metrics import Metric
import cv2
import numpy as np
import skimage
import torch.tensor as Tensor
class SegMetric(Metric):
def __init__(self, iou_thr, prob_thr, img_size, dist_sync_on_step=False):
super().__init__(dist_sync_on_step=dist_sync_on... | normal | {
"blob_id": "8d3f8872a3d5c4351551dc2d46839763d28ebd70",
"index": 3586,
"step-1": "<mask token>\n\n\nclass SegMetric(Metric):\n\n def __init__(self, iou_thr, prob_thr, img_size, dist_sync_on_step=False):\n super().__init__(dist_sync_on_step=dist_sync_on_step)\n self.iou_thr = iou_thr\n sel... | [
5,
6,
7,
8,
10
] |
import sys
import os
import csv
import urllib2, socket, time
import gzip, StringIO
import re, random, types
from bs4 import BeautifulSoup
from datetime import datetime
import json
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def ... | normal | {
"blob_id": "2d444c00e4dbdcb143d19752cd1a751169de73d3",
"index": 5746,
"step-1": "import sys\nimport os\nimport csv\nimport urllib2, socket, time\nimport gzip, StringIO\nimport re, random, types\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport json\nfrom HTMLParser import HTMLParser\n\nclass... | [
0
] |
# -*- coding:utf-8 -*-
from common import *
import itertools
def iteration_spider():
max_errors = 5
num_errors = 0
for page in itertools.count(1):
url = 'http://example.webscraping.com/view/-{}'.format(page)
html = download(url)
if html is None:
num_errors += 1
if num_errors == max_errors:
break
... | normal | {
"blob_id": "0eaba8f570772de864f52168a597b47a4150d015",
"index": 5924,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef iteration_spider():\n max_errors = 5\n num_errors = 0\n for page in itertools.count(1):\n url = 'http://example.webscraping.com/view/-{}'.format(page)\n htm... | [
0,
1,
2,
3,
4
] |
import os
import random
readpath = './DBLP/'
writepath = './DBLP/'
dataname = 'dblp.txt'
labelname = 'node2label.txt'
testsetname = writepath + 'dblp_testset.txt'
def run(save_rate):
rdataname = readpath + dataname
rlabelname = readpath + labelname
wdataname = writepath + dataname
wlabelname = writepath + labelna... | normal | {
"blob_id": "4bd6a7c7fc6a788b2cb010f6513872bd3e0d396c",
"index": 5011,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run(save_rate):\n rdataname = readpath + dataname\n rlabelname = readpath + labelname\n wdataname = writepath + dataname\n wlabelname = writepath + labelname\n orda... | [
0,
2,
3,
4,
5
] |
from .embedpeek import EmbedPeek
__red_end_user_data_statement__ = "This cog does not persistently store data or metadata about users."
def setup(bot):
bot.add_cog(EmbedPeek(bot))
| normal | {
"blob_id": "b66142e0b674d3920b8e3ad74e0d0b753f0a78c3",
"index": 3471,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef setup(bot):\n bot.add_cog(EmbedPeek(bot))\n",
"step-3": "<mask token>\n__red_end_user_data_statement__ = (\n 'This cog does not persistently store data or metadata about u... | [
0,
1,
2,
3,
4
] |
"""
Question:
You are given a string s consisting only of digits 0-9, commas ,, and dots .
Your task is to complete the regex_pattern defined below, which will be used to
re.split() all of the , and . symbols in s.
It’s guaranteed that every comma and every dot in s is preceded and followed
by a digit.
Sample Input... | normal | {
"blob_id": "020691fe2c7e7092d45415b72ce1804618421a2a",
"index": 9519,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('\\n'.join(re.split(regex_pattern, input())))\n",
"step-3": "<mask token>\nregex_pattern = '[,.]'\nprint('\\n'.join(re.split(regex_pattern, input())))\n",
"step-4": "<mask token... | [
0,
1,
2,
3,
4
] |
a=range(1,11) #1~10숫자를 에이에 저장
b=1
for i in a: #a에있는 원소를 b에 곱하고 비에 저장
b*=i
print(b)
| normal | {
"blob_id": "8cb7290792f9390dd350e0c79711e0dd72d6063b",
"index": 9508,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in a:\n b *= i\nprint(b)\n",
"step-3": "a = range(1, 11)\nb = 1\nfor i in a:\n b *= i\nprint(b)\n",
"step-4": "a=range(1,11) #1~10숫자를 에이에 저장\nb=1\nfor i in a: #a에있는 원소를 ... | [
0,
1,
2,
3
] |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import render
from django.urls import reverse
from django.views.generic.edit import ... | normal | {
"blob_id": "c385fe2af9aebc9c4a42d4db5a341fcedeec3898",
"index": 3579,
"step-1": "<mask token>\n\n\ndef index(request):\n return render(request, 'canyon/index.html')\n\n\ndef results(request):\n return render(request, 'canyon/results.html')\n",
"step-2": "<mask token>\ndjango.setup()\n\n\ndef index(reque... | [
2,
3,
4,
5,
6
] |
import matplotlib.pyplot as plotOp
import numpy as np
from random import randint
import re as regexOp
| normal | {
"blob_id": "6c0a1d4ffd64e0566be53937d9b48975f2530852",
"index": 7767,
"step-1": "<mask token>\n",
"step-2": "import matplotlib.pyplot as plotOp\nimport numpy as np\nfrom random import randint\nimport re as regexOp\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
# prevent numpy exponential
# notation on print, default False
np.set_printoptions(suppress=True)
y_cord_df = pd.DataFrame(data=None, columns=['Time', 'Orien'])
list_no = np.arange(0.0, 108000.0, 1.0)
y_cord_df['... | normal | {
"blob_id": "ba5171d3de87ec01770a7174d9783d5058b0fced",
"index": 9896,
"step-1": "<mask token>\n\n\ndef vel_det(file, legend_label, line_color):\n fps = 60\n data_df = pd.read_hdf(path_or_buf=file)\n bodyparts = data_df.columns.get_level_values(1)\n coords = data_df.columns.get_level_values(2)\n b... | [
1,
2,
3,
4,
5
] |
import sys
import os
import utils
def run(name, dim_k, dump='dump', add_cmd=''):
res = all_res[name]
model = 'ATT_ts' if res.split('_')[1] == 'att' else 'LastItem'
cmd = f'python main.py -model={model} -ds=v3 -restore_model={res} -k={dim_k} -show_detail -{dump} -nb_topk=2000 -nb_rare_k=1000 -msg={name} {a... | normal | {
"blob_id": "548a236c4c485091d312593dcb0fa331ff98f1a8",
"index": 6359,
"step-1": "<mask token>\n\n\ndef run(name, dim_k, dump='dump', add_cmd=''):\n res = all_res[name]\n model = 'ATT_ts' if res.split('_')[1] == 'att' else 'LastItem'\n cmd = (\n f'python main.py -model={model} -ds=v3 -restore_mod... | [
1,
3,
4,
5,
6
] |
# Generated by Django 3.0.5 on 2020-04-30 06:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('products_app', '0003_auto_20200429_0739'),
]
operations = [
migrations.CreateModel(
name='User'... | normal | {
"blob_id": "cdc8c8aba384b7b1b5e741ffe4309eaee30aaada",
"index": 5405,
"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 = [('products_ap... | [
0,
1,
2,
3,
4
] |
from distutils.core import setup
setup(
name="zuknuft",
version="0.1",
author="riotbib",
author_email="riotbib@github",
scripts=["zukunft.py"],
install_requires=[
'bottle',
],
)
| normal | {
"blob_id": "638842cda666100ce197437cb354f66de77eb328",
"index": 8065,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='zuknuft', version='0.1', author='riotbib', author_email=\n 'riotbib@github', scripts=['zukunft.py'], install_requires=['bottle'])\n",
"step-3": "from distutils.core impor... | [
0,
1,
2,
3
] |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
class Gerenciador(ScreenManager):
pass
class Menu(Screen):
pass
class Tarefas(Screen):
def __init__(self, tarefas=[], **kwargs):
super().__init__(**kwargs)
for ta... | normal | {
"blob_id": "66b42791325a53172d4514cdd16ccd58d4edb186",
"index": 2409,
"step-1": "<mask token>\n\n\nclass Tarefas(Screen):\n <mask token>\n <mask token>\n\n\nclass Tarefa(BoxLayout):\n\n def __init__(self, text='', **kwargs):\n super().__init__(**kwargs)\n self.ids.label.text = text\n\n\nc... | [
5,
8,
9,
11
] |
import cv2 as cv
img = cv.imread('images/gradient.png', 0)
_,th1 = cv.threshold(img, 127,255, cv.THRESH_BINARY)
_,th2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
_,th3 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC) #freeze the pixel color after the threshold
_,th4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO... | normal | {
"blob_id": "6f356840944e11f52a280262697d7e33b3cca650",
"index": 2319,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncv.imshow('Threshold Trunc', th3)\ncv.imshow('Threshold2', th2)\ncv.imshow('Threshold', th1)\ncv.imshow('Image', img)\ncv.imshow('th4', th4)\ncv.imshow('th5', th5)\ncv.waitKey(0)\ncv.dest... | [
0,
1,
2,
3,
4
] |
import random
import re
from datetime import datetime, timedelta
from threading import Lock
from telegram.ext import run_async
from src.models.user import UserDB
from src.models.user_stat import UserStat
from src.utils.cache import cache, USER_CACHE_EXPIRE
from src.utils.logger_helpers import get_logger
logger = get... | normal | {
"blob_id": "109ca06685eece74034f77a98b1d7172a17aca21",
"index": 7469,
"step-1": "<mask token>\n\n\nclass PidorWeekly:\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def get_top_pidor(cls, cid, date=None):\n monday = cls.__get_current_monday(\n ) if date is None ... | [
9,
12,
13,
14,
15
] |
print ("Hello"*5)
| normal | {
"blob_id": "9ae7b6d081529a5c70b7362c852647b3638e7e98",
"index": 8105,
"step-1": "<mask token>\n",
"step-2": "print('Hello' * 5)\n",
"step-3": "print (\"Hello\"*5)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy.settings import CrawlerSettings
from scrapy import log, signals
from spiders.songspk_spider import SongsPKSpider
from scrapy.xlib.pydispatch import dispatcher
def stop_reactor():
reactor.stop()
dispatcher.connect(stop_reactor, sig... | normal | {
"blob_id": "0d14534b210b13ede4a687e418d05d756d221950",
"index": 3297,
"step-1": "from twisted.internet import reactor\nfrom scrapy.crawler import Crawler\nfrom scrapy.settings import CrawlerSettings\nfrom scrapy import log, signals\nfrom spiders.songspk_spider import SongsPKSpider\nfrom scrapy.xlib.pydispatch i... | [
0
] |
import pandas as pd
import numpy as np
import sys
#Best Mean Test
if len(sys.argv) <= 3:
print("Not enough args usage: anova.py <*.csv> <rv1,rv2> <target to beat>")
print("ex: best-mean.py testdata.csv nicdrop 95000")
print("<rv> is response variable")
exit()
target_to_beat = int(sys.argv[3]) #factors
rv = sys.ar... | normal | {
"blob_id": "b9e78629fe094d933fdc0ffa2f9d9d1880e78c12",
"index": 9078,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif len(sys.argv) <= 3:\n print('Not enough args usage: anova.py <*.csv> <rv1,rv2> <target to beat>')\n print('ex: best-mean.py testdata.csv nicdrop 95000')\n print('<rv> is respo... | [
0,
1,
2,
3,
4
] |
from hops import constants
class Cluster(object):
"""
Represents a Cluster in Cluster Analysis computed for a featuregroup or training dataset in the featurestore
"""
def __init__(self, cluster_json):
"""
Initialize the cluster object from JSON payload
Args:
:clus... | normal | {
"blob_id": "753c87a3d22aeca1001eb770831b846b175d873e",
"index": 9139,
"step-1": "<mask token>\n\n\nclass Cluster(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Cluster(object):\n <mask token>\n\n def __init__(self, cluster_json):\n \"\"\"\n Initialize t... | [
1,
2,
3,
4
] |
def cubarea(l2,b2,h2):
print("Area of cuboid =",2*(l2+b2+h2))
def cubperimeter(l2,b2,h2):
print("Perimeter of cuboid =",4*(l2+b2+h2))
| normal | {
"blob_id": "45a85ff765833fd62fc1670404d8994818788707",
"index": 6873,
"step-1": "<mask token>\n",
"step-2": "def cubarea(l2, b2, h2):\n print('Area of cuboid =', 2 * (l2 + b2 + h2))\n\n\n<mask token>\n",
"step-3": "def cubarea(l2, b2, h2):\n print('Area of cuboid =', 2 * (l2 + b2 + h2))\n\n\ndef cubpe... | [
0,
1,
2,
3
] |
import math
import random
import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption('space invaders')
background = pygame.image.load('background.png')
score = 0
previous_score = 0
score... | normal | {
"blob_id": "f5dffa3c22bb35ed07cb5ca28f2ba02ea3c07dda",
"index": 1083,
"step-1": "<mask token>\n\n\ndef player(x, y):\n screen.blit(player_image, (x, y))\n\n\ndef fire_bullet(x, y, n):\n global bullet_fired\n bullet_fired[n] = True\n screen.blit(bullet_image, (x + 16, y + 10))\n\n\ndef add_bullet():\... | [
15,
16,
18,
19,
20
] |
import sqlite3
import argparse
import json
import index_db
from collections import defaultdict
def query_doc(cursor, lang, title):
cursor.execute(index_db.select_lang_title, (lang, title))
result = cursor.fetchone()
if not result:
return None
return {
'lang': result[0],
'doc_id... | normal | {
"blob_id": "95e7e025660e71cbdf6a6a0812964fc26d4beec0",
"index": 9657,
"step-1": "<mask token>\n\n\ndef query_doc(cursor, lang, title):\n cursor.execute(index_db.select_lang_title, (lang, title))\n result = cursor.fetchone()\n if not result:\n return None\n return {'lang': result[0], 'doc_id':... | [
2,
3,
4,
5,
6
] |
from django.apps import AppConfig
class ModuloConfig(AppConfig):
name = 'modulo'
verbose_name = 'TUM:JungeAkademie - Modulo'
def ready(self):
#start-up / initialization code here!!!
from .recommender import Recommender
Recommender.initialize() | normal | {
"blob_id": "31275ca9e20da9d2709ea396e55c113b3ff4f571",
"index": 7738,
"step-1": "<mask token>\n\n\nclass ModuloConfig(AppConfig):\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ModuloConfig(AppConfig):\n <mask token>\n <mask token>\n\n def ready(self):\n ... | [
1,
2,
3,
4,
5
] |
from .cli import cli
if __name__ == "__main__":
exit(cli.main(prog_name="htmap"))
| normal | {
"blob_id": "069338b188f3cf16357b2502cbb3130b69918bd9",
"index": 286,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n exit(cli.main(prog_name='htmap'))\n",
"step-3": "from .cli import cli\nif __name__ == '__main__':\n exit(cli.main(prog_name='htmap'))\n",
"step-4": "... | [
0,
1,
2,
3
] |
"""
Download the full CHIRPS 2.0 data for a specific type (dekads, pentads, daily ...)
with the possibility to automatically recut the data over Argentina.
"""
import os
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
import subprocess
##############
# PARAMETERS to define
# Set a pre... | normal | {
"blob_id": "ff0495ee1f4aa1f243c82b709a974d3d7c37e8bd",
"index": 2425,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif download_dir != '':\n os.chdir(download_dir)\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n soup.findAll('a')\n one_a_tag = soup.f... | [
0,
1,
2,
3,
4
] |
from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper(
'http://localhost:3030/ds/query'
)
#Pizzas
def get_response_pizzas():
sparql.setQuery('''
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX saidi: <http://www.semanticweb.org/japor/ontologies/2021/5/Pizzas... | normal | {
"blob_id": "9690366a88a87951f5c51902118888cce8159ffc",
"index": 7219,
"step-1": "<mask token>\n\n\ndef get_response_carnes():\n sparql.setQuery(\n \"\"\"\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX saidi: <http://www.semanticweb.org/japor/ontologies/2021/5/PizzasLojan... | [
6,
7,
8,
10,
12
] |
from core.models import AnalyticsCacheSearchKeywordDay
from datetime import datetime, timedelta
def get_month():
return ["2017-10","2017-11","2017-12","2018-1","2018-2","2018-3","2018-4","2018-5","2018-6","2018-7","2018-8","2018-9","2018-10","2018-11", "2018-12"]
def run():
day = datetime.strptime("2017-1... | normal | {
"blob_id": "b048319a2ed182e70aa7f8a736ff02953577ec39",
"index": 2008,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run():\n day = datetime.strptime('2017-10', '%Y-%m')\n next_day = datetime.strptime('2017-11', '%Y-%m')\n last_day = datetime.strptime('2018-11', '%Y-%m')\n monthes = ... | [
0,
1,
2,
3,
4
] |
from django.http import HttpResponse
from django.shortcuts import render
from .models import game
def index(request):
all_games = game.objects.all()
context = {
'all_games' : all_games
}
return render(request,'game/index.html',context)
def gameview(response):
return HttpResponse("<h1>Ludo ... | normal | {
"blob_id": "6623ac194e380c9554d72a1b20bf860b958dda97",
"index": 5961,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef index(request):\n all_games = game.objects.all()\n context = {'all_games': all_games}\n return render(request, 'game/index.html', context)\n\n\n<mask token>\n",
"step-3... | [
0,
1,
2,
3,
4
] |
# Standard library
# Third party library
# Local library
from warehouse.server import run_server
from warehouse.server.config import log
if __name__ == "__main__":
log.initialize_logs()
run_server()
| normal | {
"blob_id": "8c8b5c1ff749a8563788b8d5be5332e273275be3",
"index": 6450,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n log.initialize_logs()\n run_server()\n",
"step-3": "from warehouse.server import run_server\nfrom warehouse.server.config import log\nif __name__ == '... | [
0,
1,
2,
3
] |
from typing import Any, Dict, List
import numpy as np
from kedro.io import AbstractDataSet
from msrest.exceptions import HttpOperationError
from azureml.core import Workspace, Datastore
from azureml.data.data_reference import DataReference
class AZblob_datastore_data(AbstractDataSet):
"""``ImageDataSet`` loads /... | normal | {
"blob_id": "eb981a2d7f0ff5e6cc4a4a76f269c93c547965ba",
"index": 715,
"step-1": "from typing import Any, Dict, List\n\nimport numpy as np\n\nfrom kedro.io import AbstractDataSet\nfrom msrest.exceptions import HttpOperationError\nfrom azureml.core import Workspace, Datastore\nfrom azureml.data.data_reference impo... | [
0
] |
# -*- coding:utf-8 -*-
from spider.driver.base.driver import Driver
from spider.driver.base.mysql import Mysql
import time
from pyquery import PyQuery
from spider.driver.base.field import Field,FieldName,Fieldlist,FieldType
from spider.driver.base.page import Page
from spider.driver.base.listcssselector import ListCssS... | normal | {
"blob_id": "1a7a28a2264ed0204184ab1dd273b0b114657fa7",
"index": 3004,
"step-1": "<mask token>\n\n\nclass WeixinSpider(Driver):\n <mask token>\n\n def get_article(self, data_list=[]):\n article_list = (self.\n until_presence_of_all_elements_located_by_css_selector(\n css_select... | [
3,
4,
5,
6,
7
] |
from marshmallow import ValidationError
from werkzeug.exceptions import HTTPException
from flask_jwt_extended.exceptions import JWTExtendedException
from memedata.util import mk_errors
from memedata import config
def jwt_error_handler(error):
code = 401
messages = list(getattr(error, 'args', []))
return m... | normal | {
"blob_id": "e1da3255668999c3b77aa8c9332b197a9203478e",
"index": 8992,
"step-1": "<mask token>\n\n\ndef jwt_error_handler(error):\n code = 401\n messages = list(getattr(error, 'args', []))\n return mk_errors(code, messages)\n\n\n<mask token>\n\n\ndef validation_error_handler(error):\n code = getattr(... | [
4,
5,
6,
7
] |
from typing import Dict, List
from .power_bi_querier import PowerBiQuerier
class DeathsByEthnicity(PowerBiQuerier):
def __init__(self) ->None:
self.source = 'd'
self.name = 'deaths by race'
self.property = 'race'
super().__init__()
def _parse_data(self, response_json: Dict[st... | normal | {
"blob_id": "d975b74370acc72101f808e70bef64cee39a5ab8",
"index": 6204,
"step-1": "<mask token>\n\n\nclass DeathsByEthnicity(PowerBiQuerier):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass DeathsByEthnicity(PowerBiQuerier):\n <mask token>\n\n def _parse_data(self, response_json... | [
1,
2,
3,
4
] |
import PyInstaller.__main__
import os
import shutil
# Paths
basePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
srcPath = os.path.join(basePath, 'src')
outPath = os.path.join(basePath, 'out')
workPath = os.path.join(outPath, 'work')
# Bundle
PyInstaller.__main__.run([
'--clean',
... | normal | {
"blob_id": "16a95573c4fccc10bdc5e37b307d0c85714b328c",
"index": 3548,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nPyInstaller.__main__.run(['--clean', '--onefile', '--workpath', workPath,\n '--distpath', outPath, '--hidden-import', 'win32timezone', os.path.join\n (srcPath, 'service.py'), os.pat... | [
0,
1,
2,
3,
4
] |
class Solution:
def isUgly(self, num):
if num == 0:
return False
for n in [2, 3, 5]:
while num % n == 0:
num = num / n
return num == 1
a = Solution()
print(a.isUgly(14))
print(a.isUgly(8))
print(a.isUgly(6))
print(a.isUgly(0))
| normal | {
"blob_id": "d39cc2dbbc83869e559f8355ceba5cf420adea5e",
"index": 1662,
"step-1": "class Solution:\n <mask token>\n\n\n<mask token>\n",
"step-2": "class Solution:\n\n def isUgly(self, num):\n if num == 0:\n return False\n for n in [2, 3, 5]:\n while num % n == 0:\n ... | [
1,
2,
3,
4
] |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from django import forms
from programs.models import *
from programs.forms import CustomUserCreationForm, CustomUserChangeForm
import pdb
class ProgramAdmin(admin.ModelAdmin):
list... | normal | {
"blob_id": "77e4bbe625251254cdadaeeb23dddf51e729e747",
"index": 832,
"step-1": "<mask token>\n\n\nclass DepartmentAdmin(admin.ModelAdmin):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def save_model(self, request, obj, form, change):\n if obj.code == '':\n obj... | [
17,
23,
24,
27,
29
] |
# Stubs for torch.nn.utils (Python 3)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from .clip_grad import clip_grad_norm, clip_grad_norm_, clip_grad_value_
from .convert_parameters import parameters_to_vector, vector_to_parameters
from .spectral_norm import remove_spectral_norm, spectr... | normal | {
"blob_id": "5d9ace3b6c5b4e24fc3b20b5e5640f2fcdb252bb",
"index": 9292,
"step-1": "<mask token>\n",
"step-2": "from .clip_grad import clip_grad_norm, clip_grad_norm_, clip_grad_value_\nfrom .convert_parameters import parameters_to_vector, vector_to_parameters\nfrom .spectral_norm import remove_spectral_norm, sp... | [
0,
1,
2
] |
# coding=utf-8
"""
author: wlc
function: 百科检索数据层
"""
# 引入外部库
import json
import re
from bs4 import BeautifulSoup
# 引入内部库
from src.util.reptile import *
class EncyclopediaDao:
@staticmethod
def get_key_content (key: str) -> list:
"""
获取指定关键字的百科内容检索内容
:param key:
:return:
"""
# 1.参数设置
url = 'https://... | normal | {
"blob_id": "a7f348b258e1d6b02a79c60e4fe54b6d53801f70",
"index": 3877,
"step-1": "<mask token>\n\n\nclass EncyclopediaDao:\n <mask token>\n <mask token>\n\n @staticmethod\n def get_faq_content(query: str, page: str) ->list:\n \"\"\"\n\t\t获取指定query的faq检索内容\n\t\t:param query:\n\t\t:param page:\n... | [
2,
3,
4,
5,
6
] |
from python_logging.Demo_CustomLogger import CustomLogger
CustomLogger.init_log()
# CustomLogger.info()
log_str = '%s/%s/%s\n' % ("demo1", "demo2", "demo3")
CustomLogger.info('[main]', log_str)
| normal | {
"blob_id": "ed5653455062cb3468c232cf0fa3f1d18793626a",
"index": 591,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nCustomLogger.init_log()\n<mask token>\nCustomLogger.info('[main]', log_str)\n",
"step-3": "<mask token>\nCustomLogger.init_log()\nlog_str = '%s/%s/%s\\n' % ('demo1', 'demo2', 'demo3')\nC... | [
0,
1,
2,
3,
4
] |
# 8-7. Album: Write a function called make_album() that builds a dictionary
# describing a music album. The function should take in an artist name and an
# album title, and it should return a dictionary containing these two pieces
# of information. Use the function to make three dictionaries representing
# di... | normal | {
"blob_id": "19888c998e8787533e84413272da1183f16fcdb1",
"index": 2974,
"step-1": "<mask token>\n\n\ndef make_album_two(artist_name, album_title, number_of_songs=None):\n \"\"\"Build a dictionary describing a music album\"\"\"\n music_album = {'Artist': artist_name.title(), 'Album': album_title.title()}\n ... | [
1,
2,
3,
4,
5
] |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#Print Stop words
stop_words = set(stopwords.words("english"))
print(stop_words)
example_text = "This is general sentence to just clarify if stop words are working or not. I have some awesome projects coming up"
words = word_tokenize(... | normal | {
"blob_id": "90f5629ac48edfccea57243ffb6188a98123367d",
"index": 5197,
"step-1": "from nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize\r\n\r\n#Print Stop words\r\nstop_words = set(stopwords.words(\"english\"))\r\nprint(stop_words)\r\n\r\nexample_text = \"This is general sentence to just c... | [
0
] |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2021/05/08 20:06
# @Author : Yi
# @FileName: show_slices.py
import os
import pydicom
import glob
import shutil
import random
import numpy as np
import cv2
import skimage.io as io
from data_Parameter import parse_args
import matplotlib.pyplot as plt
def d... | normal | {
"blob_id": "4905b820f33619a80a9915d0603bc39e0d0368d9",
"index": 6175,
"step-1": "<mask token>\n\n\ndef dir_create(path):\n \"\"\"创造新的文件夹。\n\n :param path: 文件夹路径\n :return:\n \"\"\"\n if os.path.exists(path) and os.listdir(path) != []:\n shutil.rmtree(path)\n os.makedirs(path)\n i... | [
7,
8,
9,
10,
11
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-23 17:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sepomex', '0006_auto_20151113_2154'),
]
operations... | normal | {
"blob_id": "99c27d13349eba391866cfed25cc052b40910ea5",
"index": 2837,
"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 = [('sepomex', '... | [
0,
1,
2,
3,
4
] |
import math
def upsample1(d, p):
# 普通结界
assert 1 <= p <= 10
return d + p
def upsample2(d, p):
# 倍增结界
assert 2 <= p <= 3
return d * p
def downsample(d, p):
# 聚集结界
assert 2 <= p <= 10
return math.ceil(d / p)
# 初始化杀伤力范围
lethal_radius = 1
# 结界参数(z, p)
config = [(1, 6),
... | normal | {
"blob_id": "cb6f68c8b8a6cead1d9fcd25fa2a4e60f7a8fb28",
"index": 9746,
"step-1": "<mask token>\n\n\ndef upsample1(d, p):\n assert 1 <= p <= 10\n return d + p\n\n\ndef upsample2(d, p):\n assert 2 <= p <= 3\n return d * p\n\n\ndef downsample(d, p):\n assert 2 <= p <= 10\n return math.ceil(d / p)\... | [
3,
4,
5,
6,
7
] |
'''
删除排序数组中的重复项:
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
你不需要考虑数组中超出新长度后... | normal | {
"blob_id": "ac0f0fbb9bcb450ac24198069ef8bea8b049ef47",
"index": 5824,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef delete_sort_array(origin_list):\n if len(origin_list) == 0:\n return 0\n elif len(origin_list) == 1:\n return 1\n else:\n for index, item in enumerat... | [
0,
1,
2,
3
] |
from django.forms import ModelForm
from django import forms
from models import *
from django.forms.widgets import *
class CommentForm(ModelForm):
# tags = TagField(widget=TagAutocomplete())
class Meta:
model=Comment
# fields = ('title', 'description', 'tags', 'enable_comments', 'owner')#, 'first_card' )
# w... | normal | {
"blob_id": "81535b43437f9bcb18973ceaa5c3340ad9bd4f0f",
"index": 4170,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass CommentForm(ModelForm):\n\n\n class Meta:\n model = Comment\n",
"step-3": "from django.forms import ModelForm\nfrom django import forms\nfrom models import *\nfrom d... | [
0,
1,
2,
3
] |
# Give a string that represents a polynomial (Ex: "3x ^ 3 + 5x ^ 2 - 2x - 5") and
# a number (whole or float). Evaluate the polynomial for the given value.
#Horner method
def horner( poly, x):
result = poly[0]
for i in range(1 , len(poly)):
result = result*x + poly[i]
return result
# Let us evalua... | normal | {
"blob_id": "750565af03d945fbdc32e26347b28977b203e9dc",
"index": 4858,
"step-1": "<mask token>\n",
"step-2": "def horner(poly, x):\n result = poly[0]\n for i in range(1, len(poly)):\n result = result * x + poly[i]\n return result\n\n\n<mask token>\n",
"step-3": "def horner(poly, x):\n resu... | [
0,
1,
2,
3,
4
] |
import os
import pickle
import collections
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython import embed
from optimizers.utils_1 import Model_1, Architecture_1
from optimizers.utils import Model, Architecture
colors={
'BOHB-PC-DARTS': 'darkorange',
'BOHB-DARTS': 'dod... | normal | {
"blob_id": "a757bbb9ad2f6f5bf04cdf4091b97841b8e40432",
"index": 6601,
"step-1": "<mask token>\n\n\ndef get_trajectories(args, global_min, path='regularized_evolution',\n methods=['RE', 'RS']):\n all_trajectories = {}\n for m in methods:\n dfs = []\n for seed in range(500):\n fi... | [
3,
4,
5,
6,
7
] |
import os
from apps.app_base.app_utils.cryp_key import decrypt, get_secret_key
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = get_secret_key
DEBUG = True
ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]']
# Application definition
INSTALLED_APPS = [
'corsheaders',
'd... | normal | {
"blob_id": "027a049ffced721f2cd697bc928bfdf718630623",
"index": 4692,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nSECRET_KEY = get_secret_key\nDEBUG = True\nALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]']\nINSTALLED_APPS = [... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2014-2016 by Mike Taylor
:license: MIT, see LICENSE for more details.
Micropub Tools
"""
import requests
from bs4 import BeautifulSoup, SoupStrainer
try: # Python v3
from urllib.parse import urlparse, urljoin
except ImportError:
from urlparse import urlparse, urlj... | normal | {
"blob_id": "1bb82a24faed6079ec161d95eff22aa122295c13",
"index": 3982,
"step-1": "<mask token>\n\n\ndef setParser(htmlParser='html5lib'):\n global _html_parser\n _html_parser = htmlParser\n\n\ndef discoverEndpoint(domain, endpoint, content=None, look_in={'name':\n 'link'}, test_urls=True, validateCerts=... | [
2,
5,
6,
7,
8
] |
#!/usr/bin/env python3
# coding=utf-8
import fire
import json
import os
import time
import requests
import time
import hashlib
import random
root_path, file_name = os.path.split(os.path.realpath(__file__))
ip_list_path = ''.join([root_path, os.path.sep, 'ip_list.json'])
class ProxySwift(object):
... | normal | {
"blob_id": "0ff96b2314927d7b3e763242e554fd561f3c9343",
"index": 5872,
"step-1": "<mask token>\n\n\nclass ProxySwift(object):\n <mask token>\n\n def requerst_get(self, url, data, *p, **kwargs):\n SecretKey = '3JCx8fAF7Bpq5Aj4t9wS7cfVB7hpXZ7j'\n PartnerID = '2017061217350058'\n TimeStam... | [
9,
10,
13,
14,
16
] |
from models import Sensor
import mysql.connector as mariadb
## CREATE A DB WITH MARIADB ##
mariadb_connection = mariadb.connect(user='web', password='raspberry', database='PlantHubDB')
cursor = mariadb_connection.cursor()
def closeConnection():
cursor.close()
mariadb_connection.close()
return
def getTask... | normal | {
"blob_id": "f471062573a5ec8cfeb194168edfba3d2700cac6",
"index": 9845,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef closeConnection():\n cursor.close()\n mariadb_connection.close()\n return\n\n\ndef getTasks(amount):\n mariadb_connection = mariadb.connect(user='web', password='raspb... | [
0,
3,
4,
5,
6
] |
from web3 import Web3, HTTPProvider, IPCProvider
from tcmb.tcmb_parser import TCMB_Processor
from ecb.ecb_parser import ECB_Processor
from web3.contract import ConciseContract
from web3.middleware import geth_poa_middleware
import json
import time
tcmb_currencies = ["TRY", "USD", "AUD", "DKK", "EUR", "GBP", "CHF", "SE... | normal | {
"blob_id": "ecd5097d9d497b62b89217ee3c46506f21fc15d2",
"index": 5065,
"step-1": "<mask token>\n\n\ndef epoch_day(epoch_time):\n epoch_time = int(epoch_time)\n return epoch_time - epoch_time % 86400\n\n\n<mask token>\n\n\ndef add_ecb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n ECB = ECB_Pro... | [
3,
4,
5,
6,
7
] |
"""GI on fast."""
import logging
from mpf.core.utility_functions import Util
from mpf.platforms.interfaces.gi_platform_interface import GIPlatformInterface
class FASTGIString(GIPlatformInterface):
"""A FAST GI string in a WPC machine."""
def __init__(self, number, sender):
"""Initialise GI string.
... | normal | {
"blob_id": "91cf6d08be2ad86c08de4dd48b2f35dedc55b4bb",
"index": 2177,
"step-1": "<mask token>\n\n\nclass FASTGIString(GIPlatformInterface):\n <mask token>\n\n def __init__(self, number, sender):\n \"\"\"Initialise GI string.\n\n TODO: Need to implement the enable_relay and control which stri... | [
3,
4,
5,
6,
7
] |
import cv2
print(cv2.__version__)
image = cv2.imread("download.jpeg", 1)
print(image)
print(image.shape)
print(image[0])
print("~~~~~~~~~~~~~~~")
print(image.shape[0])
print("~~~~~~~~~~~~~~~")
print(len(image)) | normal | {
"blob_id": "0b0ae6101fd80bdbcf37b935268f3e49230599fb",
"index": 5715,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(cv2.__version__)\n<mask token>\nprint(image)\nprint(image.shape)\nprint(image[0])\nprint('~~~~~~~~~~~~~~~')\nprint(image.shape[0])\nprint('~~~~~~~~~~~~~~~')\nprint(len(image))\n",
... | [
0,
1,
2,
3,
4
] |
import json
subjects = []
with open("sub.json", 'r') as subject_file:
subjects = json.load(subject_file)
print(json.dumps(subjects, separators=(',',':')))
| normal | {
"blob_id": "98bd4eb25a76fb9184f9abfcb920a6fbe46b9394",
"index": 631,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('sub.json', 'r') as subject_file:\n subjects = json.load(subject_file)\nprint(json.dumps(subjects, separators=(',', ':')))\n",
"step-3": "<mask token>\nsubjects = []\nwith o... | [
0,
1,
2,
3,
4
] |
__title__ = 'FUCKTHEINTRUDERS'
__description__ = 'Checking for Intruders in my locality'
__version__ = '0.0.1'
__author__ = 'Shivam Jalotra'
__email__ = 'shivam_11710495@nitkkr.ac.in'
__license__ = 'MIT 1.0'
| normal | {
"blob_id": "ba94a69ac356969ab593afc922a2517f4713771f",
"index": 5536,
"step-1": "<mask token>\n",
"step-2": "__title__ = 'FUCKTHEINTRUDERS'\n__description__ = 'Checking for Intruders in my locality'\n__version__ = '0.0.1'\n__author__ = 'Shivam Jalotra'\n__email__ = 'shivam_11710495@nitkkr.ac.in'\n__license__ ... | [
0,
1
] |
import items
import grupo
class Conexion:
def __init__(self, direccion, destino):
self.set_direccion(direccion)
self.set_destino(destino)
def __repr__(self):
return str(self.direccion()) + ' => ' + str(self.destino())
def direccion(self):
return self._direccion
def se... | normal | {
"blob_id": "f59e61977f7c72ab191aadccbd72d23f831b3a1c",
"index": 7050,
"step-1": "<mask token>\n\n\nclass Conexion:\n\n def __init__(self, direccion, destino):\n self.set_direccion(direccion)\n self.set_destino(destino)\n <mask token>\n <mask token>\n\n def set_direccion(self, direccion... | [
20,
22,
25,
26,
27
] |
# VGGNet
import numpy as np
np.random.seed(317)
from glob import glob
from itertools import cycle
from keras.applications.vgg19 import VGG19
from keras.optimizers import Adam
from keras.models import Model
from keras.layers import Input, BatchNormalization, Flatten, Dropout, Dense
from keras.utils import plot_model
fr... | normal | {
"blob_id": "c6a4d566460a06504abf7e2c54be4f2ea36e01fb",
"index": 7735,
"step-1": "<mask token>\n\n\nclass VGGNet(object):\n\n def __init__(self, checkpoint_name='VGGNet'):\n self.config = {'image_shape': [256, 256, 3], 'input_shape': [224, \n 224, 3], 'output_shape': [17], 'batch_size': 60, ... | [
7,
8,
9,
10,
11
] |
import numpy as n, pylab as p
from scipy import stats as st
a=st.norm(0,1)
b=st.norm(0.1,1)
domain=n.linspace(-4,4,10000)
avals=a.cdf(domain)
bvals=b.cdf(domain)
diffN=n.abs(avals-bvals).max()
a=st.norm(0,1)
b=st.norm(0,1.2)
domain=n.linspace(-4,4,10000)
avals=a.cdf(domain)
bvals=b.cdf(domain)
diffN2=n.abs(avals-bvals... | normal | {
"blob_id": "647258ee5f2f6f1cb8118bcf146b8959c65b70cd",
"index": 8045,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef weib(x, nn, a):\n return a / nn * (x / nn) ** (a - 1) * n.exp(-(x / nn) ** a)\n\n\n<mask token>\nprint('distancias de KS para os modelos matematicos:', diffN, diffN2, diffU,\n ... | [
0,
2,
3,
4,
5
] |
_base_ = [
'../models/cascade_rcnn_r50_fpn.py',
#'coco_instance.py',
'../datasets/dataset.py',
'../runtime/valid_search_wandb_runtime.py',
'../schedules/schedule_1x.py'
]
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa
model... | normal | {
"blob_id": "2874e05d6d5e0f13924e5920db22ea3343707dfa",
"index": 3898,
"step-1": "<mask token>\n",
"step-2": "_base_ = ['../models/cascade_rcnn_r50_fpn.py', '../datasets/dataset.py',\n '../runtime/valid_search_wandb_runtime.py', '../schedules/schedule_1x.py']\npretrained = (\n 'https://github.com/SwinTra... | [
0,
1,
2
] |
##########################################################################
#
# Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | normal | {
"blob_id": "d4c297af395581c6d955eb31a842ab86e599d23c",
"index": 4576,
"step-1": "<mask token>\n\n\nclass TestMotionPrimitive(unittest.TestCase):\n <mask token>\n\n def testItems(self):\n m = IECoreScene.MotionPrimitive()\n m[0] = IECoreScene.PointsPrimitive(1)\n m[1] = IECoreScene.Poi... | [
4,
5,
6,
7,
8
] |
import os
import pathlib
import enum
import warnings
import colorama
import requests
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import invoke
class MoleculeDriver(enum.Enum):
docker = 1
lxd = 2
vagrant = 3
class TestPlatform(enum.Enum):
linux... | normal | {
"blob_id": "5bdc08b66916959d462314b8a6e5794e5fa12b55",
"index": 7986,
"step-1": "<mask token>\n\n\nclass MoleculeDriver(enum.Enum):\n docker = 1\n lxd = 2\n vagrant = 3\n\n\nclass TestPlatform(enum.Enum):\n linux = 1\n ubuntu = 2\n centos = 3\n\n\n<mask token>\n\n\ndef print_sub_header(sub_hea... | [
10,
11,
13,
14,
16
] |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
import os
GFE_PATH = "C:\Haely\MS2017\sem2\EE 259\Project\grammatical_facial_expression"
def load_a_affirm_data(gfe_path=GFE_PATH):
csv_patha = os.path.join(gfe_path, "a_affirmative_datapoints.csv")
... | normal | {
"blob_id": "2fb8bce3a64787dbaf5a3bb3da53f70005048467",
"index": 4104,
"step-1": "<mask token>\n\n\ndef load_a_affirm_target(gfe_path=GFE_PATH):\n csv_targeta = os.path.join(gfe_path, 'a_affirmative_targets.csv')\n print(gfe_path)\n return pd.read_csv(csv_targeta)\n\n\ndef load_a_cond_data(gfe_path=GFE_... | [
19,
27,
29,
30,
40
] |
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
from dataset.mnist import load_mnist
from controller import Controller
# データの読み込み
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
# instance
controller = Controller()
# accuracy
trycount = ... | normal | {
"blob_id": "c2d8e34ab0b449a971c920fc86f259f093f16cc5",
"index": 7156,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append(os.pardir)\n<mask token>\nfor i in range(len(x_test)):\n p = controller.accuracy(x_test[i])\n a = np.argmax(t_test[i])\n result[p][a] += 1\n if p == a:\n ... | [
0,
1,
2,
3,
4
] |
import pymysql
class DB:
def __init__(self, host='localhost', port=3306, db_='test', user='wj',
passwd='', charset='utf8'):
self.db = db_
self.conn = pymysql.connect(host=host, port=port, db=db_, user=user, passwd=passwd, charset=charset)
self.cur = self.conn.curso... | normal | {
"blob_id": "80ad4459436e2e1cc44509e7dae18d1539bf2bc0",
"index": 8139,
"step-1": "<mask token>\n\n\nclass DB:\n <mask token>\n\n def __enter__(self):\n return self\n <mask token>\n\n def write(self, data):\n sql = \"INSERT INTO {}({}) VALUES ('%s')\".format('data', 'a') % data\n ... | [
4,
6,
7,
8,
9
] |
import sklearn.metrics as metrics
import sklearn.cross_validation as cv
from sklearn.externals import joblib
import MachineLearning.Reinforcement.InternalSQLManager as sqlManager
class ReinforcementLearner:
def __init__(self, clf=None, load=False, clfName=None):
"""
Initialise the Classifier, eith... | normal | {
"blob_id": "c9be3d25824093528e2bee51c045d05e036daa67",
"index": 9715,
"step-1": "<mask token>\n\n\nclass ReinforcementLearner:\n\n def __init__(self, clf=None, load=False, clfName=None):\n \"\"\"\n Initialise the Classifier, either from the provided model or from the stored classifier\n\n ... | [
3,
4,
5,
6,
8
] |
#!/usr/bin/env python
"""
##############################################################################
Software Package Risk Analysis Development Environment Specific Work Book View
##############################################################################
"""
# -*- coding: utf-8 -*-
#
# rtk.softw... | normal | {
"blob_id": "327371d373819273a2f77f63e0cedee6950dbc46",
"index": 976,
"step-1": "<mask token>\n\n\nclass RiskAnalysis(gtk.VPaned):\n <mask token>\n <mask token>\n\n def create_risk_analysis_page(self, notebook):\n \"\"\"\n Method to create the development environment risk analysis page and... | [
4,
5,
7,
9,
10
] |
'''
* @file IntQueue.py
* @author (original JAVA) William Fiset, william.alexandre.fiset@gmail.com
* liujingkun, liujkon@gmail.com
* (conversion to Python) Armin Zare Zadeh, ali.a.zarezadeh@gmail.com
* @date 23 Jun 2020
* @version 0.1
* @brief This file contains an implementation of an inte... | normal | {
"blob_id": "0ed99037d7ff708b7931fbc3553b1aeb19a20f53",
"index": 810,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass IntQueue(Queue):\n <mask token>\n\n def __init__(self, maxSize):\n \"\"\"\n maxSize is the maximum number of items\n that can be in the queue at any given time... | [
0,
8,
11,
12,
13
] |
from random import randint
import matplotlib.pyplot as plt
def generate_list(length: int) -> list:
"""Generate a list with given length with random integer values in the interval [0, length]
Args:
length (int): List length
Returns:
list: List generated with random values
"""
retu... | normal | {
"blob_id": "8804bfc5bed8b93e50279f0cbab561fe09d92a64",
"index": 6522,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef plot_table(timestamps: dict, threadList: list, mList: list) ->None:\n \"\"\"Plot standard deviation chart\n\n Args:\n k (list): Threads/Process used\n deviatio... | [
0,
1,
2,
3,
4
] |
N = int(input())
A_list = list(map(int, input().split()))
B_list = list(map(int, input().split()))
C_list = list(map(int, input().split()))
ans = 0
for i in range(N):
ans += B_list[A_list[i] - 1]
if i < N - 1:
if A_list[i] + 1 == A_list[i + 1]:
ans += C_list[A_list[i] - 1]
print(ans)
| normal | {
"blob_id": "cc160b1b0478446ba0daec4a0fe9e63453df3d96",
"index": 5029,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(N):\n ans += B_list[A_list[i] - 1]\n if i < N - 1:\n if A_list[i] + 1 == A_list[i + 1]:\n ans += C_list[A_list[i] - 1]\nprint(ans)\n",
"step-3": "... | [
0,
1,
2
] |
import tensorflow as tf
import settings
import numpy as np
slim = tf.contrib.slim
class Model:
def __init__(self, training = True):
self.classes = settings.classes_name
self.num_classes = len(settings.classes_name)
self.image_size = settings.image_size
self.cell_size = setting... | normal | {
"blob_id": "8ccec24e1a7060269ffbb376ba0c480da9eabe0a",
"index": 819,
"step-1": "<mask token>\n\n\nclass Model:\n\n def __init__(self, training=True):\n self.classes = settings.classes_name\n self.num_classes = len(settings.classes_name)\n self.image_size = settings.image_size\n se... | [
6,
7,
8,
9,
10
] |
from yama.record import Record
class MongoStorage(object):
_collection = None
_connection = None
_root_id = None
_roots = None
def __init__(self, connection):
self._connection = connection
self._collection = connection.objects
self._roots = connection.roots
root_do... | normal | {
"blob_id": "816c11717c4f26b9013f7a83e1dfb2c0578cbcf8",
"index": 1269,
"step-1": "<mask token>\n\n\nclass MongoStorage(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connect... | [
7,
8,
9,
10
] |
'''
Copyright
Jelen forráskód a Budapesti Műszaki és Gazdaságtudományi Egyetemen tartott
"Deep Learning a gyakorlatban Python és LUA alapon" tantárgy segédanyagaként készült.
A tantárgy honlapja: http://smartlab.tmit.bme.hu/oktatas-deep-learning
Deep Learning kutatás: http://smartlab.tmit.bme.hu/deep-learning
A forr... | normal | {
"blob_id": "cc097b4d2a5a521a0adb83ca1b58470b4ce84f39",
"index": 7143,
"step-1": "<mask token>\n\n\ndef data():\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n num_classes = 10\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, nu... | [
2,
3,
4,
5,
6
] |
# app/__init__.py
import json
from flask_api import FlaskAPI, status
import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyConnectionField, SQLAlchemyObjectType
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from flask import request, jsonify, abort, make_response
fr... | normal | {
"blob_id": "2f76bcfde11597f87bb9e058f7617e95c78ed383",
"index": 7950,
"step-1": "<mask token>\n\n\nclass Department(SQLAlchemyObjectType):\n\n\n class Meta:\n model = DepartmentModel\n interfaces = relay.Node,\n\n\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n all_employ... | [
3,
4,
5,
6,
7
] |
from collections import deque
warp = dict()
u, v = map(int, input().split())
for _ in range(u + v):
s, e = map(int, input().split())
warp[s] = e
q = deque()
q.append(1)
check = [-1] * 101
check[1] = 0
while q:
now = q.popleft()
for k in range(1, 7):
if now + k <= 100 and check[now + k] == -1:
... | normal | {
"blob_id": "dd792c502317288644d4bf5d247999bb08d5f401",
"index": 5369,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _ in range(u + v):\n s, e = map(int, input().split())\n warp[s] = e\n<mask token>\nq.append(1)\n<mask token>\nwhile q:\n now = q.popleft()\n for k in range(1, 7):\n ... | [
0,
1,
2,
3
] |
ii = [('CoolWHM.py', 1), ('SoutRD.py', 1), ('BrewDTO.py', 2), (
'FitzRNS2.py', 1), ('LyelCPG3.py', 1), ('TaylIF.py', 2)]
| normal | {
"blob_id": "fbba928d51ccd08dbac25fcf2098be3a0d494d34",
"index": 6659,
"step-1": "<mask token>\n",
"step-2": "ii = [('CoolWHM.py', 1), ('SoutRD.py', 1), ('BrewDTO.py', 2), (\n 'FitzRNS2.py', 1), ('LyelCPG3.py', 1), ('TaylIF.py', 2)]\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
... | [
0,
1
] |
import pkg_resources
from twisted.enterprise import adbapi
from twisted.internet import defer
# Start a logger with a namespace for a particular subsystem of our application.
from twisted.logger import Logger
log = Logger("database")
class Database:
def __init__(self, context, db_filename="database.sqlite"):
... | normal | {
"blob_id": "45c1510d19af0979326a1b9975ec363b0b80a291",
"index": 8123,
"step-1": "<mask token>\n\n\nclass Database:\n\n def __init__(self, context, db_filename='database.sqlite'):\n session_files = context['session_files']\n db_filename = session_files.session_dir / db_filename\n database... | [
8,
9,
12,
15,
16
] |
"""
util - other functions
"""
import torch
import numpy as np
from common_labelme import Config
from torch.autograd import Variable
I = torch.FloatTensor(np.eye(Config.batch_size),)
E = torch.FloatTensor(np.ones((Config.batch_size, Config.batch_size)))
normalize_1 = Config.batch_size
normalize_2 = Config.batch_size *... | normal | {
"blob_id": "be9179b33991ba743e6e6b7d5dd4dc85ffc09fc3",
"index": 6331,
"step-1": "<mask token>\n\n\ndef mig_loss_function(output1, output2, p):\n new_output = output1 / p\n m = new_output @ output2.transpose(1, 0)\n noise = torch.rand(1) * 0.0001\n m1 = torch.log(m * I + I * noise + E - I)\n m2 = ... | [
10,
11,
12,
14,
15
] |
#
#River Sheppard
#
#
from PIL import Image
if __name__ == "__main__":
scale = 768
# creating the new image in RGB mode
bitmap = Image.new("RGB", (scale, scale), "white")
# Allocating the storage for the image and
# loading the pixel data.
pix = bitmap.load()
... | normal | {
"blob_id": "507251113d80eaa3684081f7814470053b04dda9",
"index": 1436,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n scale = 768\n bitmap = Image.new('RGB', (scale, scale), 'white')\n pix = bitmap.load()\n c = complex(-0.585, 0.85)\n move = 0.0\n maxIter = ... | [
0,
1,
2,
3
] |
"""
Class: Dataset
This class is responsible of loading datasets
After initializing using load method the class results two parameter:
train: contains train set
test: contains test set
It's able of returning data structure in form of three lists:
- users
- items
- values (which are ratings)
"""
... | normal | {
"blob_id": "b668945820abe893b92fdf26ccd8563ccff804ee",
"index": 1981,
"step-1": "<mask token>\n\n\nclass DatasetLoader(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass DatasetLoader(object):\n <mask token>\n\n def __init__(self, ds_i... | [
1,
4,
5,
6,
7
] |
#!/usr/local/bin/python
import requests as rq
import sqlite3 as sq
from dateutil import parser
import datetime
import pytz
import json
from os.path import expanduser
import shutil
from os.path import isfile
import time
#FRED Config
urls = {'FRED':"http://api.stlouisfed.org/fred"}
urls['FRED_SER'] = urls['FRED'] + "/se... | normal | {
"blob_id": "8dfb1312d82bb10f2376eb726f75a4a596319acb",
"index": 3143,
"step-1": "#!/usr/local/bin/python\nimport requests as rq\nimport sqlite3 as sq\nfrom dateutil import parser\nimport datetime\nimport pytz\nimport json\nfrom os.path import expanduser\nimport shutil\nfrom os.path import isfile\nimport time\n#... | [
0
] |
from distutils.core import setup, Extension
setup(name='supermodule', version='1.0', \
ext_modules=[Extension('supermodule', ['main.c'])])
| normal | {
"blob_id": "78c8f953b924f3e664570b844bf736a788e9cfb7",
"index": 3607,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='supermodule', version='1.0', ext_modules=[Extension(\n 'supermodule', ['main.c'])])\n",
"step-3": "from distutils.core import setup, Extension\nsetup(name='supermodule', ... | [
0,
1,
2,
3
] |
import string
import random
file_one_time_pad = open("encryption_file.txt","r")
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21,25,20,15,16,14,10,26,24,9,8,13]
alphabets = ['a','b','c','d','e','f','g','h','i','j','... | normal | {
"blob_id": "4b647d37d390a4df42f29bbfc7e4bae4e77c5828",
"index": 8935,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile_one_time_pad.close()\nprint(p_text)\n<mask token>\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alph... | [
0,
1,
2,
3,
4
] |
from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask_login import (LoginManager, login_user, logout_user,
login_required, current_user)
import forms
import models
import sqlite3
DEBUG = True
app = Flask(__name__)
app.secret_key = 'auoesh.bouoastuh.43,uoausoehuos... | normal | {
"blob_id": "849c468e4890c19806c678089ec8668576538b12",
"index": 2717,
"step-1": "<mask token>\n\n\n@login_manager.user_loader\ndef load_user(userid):\n try:\n return models.user.get(models.User.id == userid)\n except models.DoesNotExist:\n return None\n\n\ndef initialize():\n models.DATAB... | [
8,
9,
10,
13,
14
] |
from keras.models import Sequential
from keras.layers import Convolution2D # for 2d images
from keras.layers import MaxPool2D
from keras.layers import Flatten
from keras.layers import Dense
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
cnn = Sequential()
rgb = 64
# step 1: convolu... | normal | {
"blob_id": "9fa5f4b4aeb7fe42d313a0ec4e57ce15acbfcf46",
"index": 3960,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncnn.add(Convolution2D(32, 3, 3, input_shape=(rgb, rgb, 3), activation='relu'))\ncnn.add(MaxPool2D(pool_size=(2, 2)))\ncnn.add(Flatten())\ncnn.add(Dense(output_dim=128, activation='relu'))... | [
0,
1,
2,
3,
4
] |
from django.shortcuts import render, HttpResponse, redirect
from ..login.models import *
from ..dashboard.models import *
def display(request, id):
context = {'job': Job.objects.get(id=int(id))}
return render(request, 'handy_helper_exam/display.html', context)
| normal | {
"blob_id": "f1fdba1c07a29aa22ee8d0dcbd6f902aa2e8b4c2",
"index": 9342,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef display(request, id):\n context = {'job': Job.objects.get(id=int(id))}\n return render(request, 'handy_helper_exam/display.html', context)\n",
"step-3": "from django.short... | [
0,
1,
2
] |
#!/usr/bin/python
import os
import sys
fdatadir = "/fdata/hepx/store/user/taohuang/NANOAOD/"
datasets = []; NumSample = []; sampleN_short = []
Nanodatasets = []; localdirs = {}
MCxsections = []
#doTT=True; doDY=True; doVV=True; doSingleT=True; doWjets=True; dottV=True
##DoubleEG
datasets.append('/DoubleEG/Run2016B-0... | normal | {
"blob_id": "72b5e76f63e347d7275b0b711fa02b7f327785f6",
"index": 7369,
"step-1": "#!/usr/bin/python\nimport os\nimport sys\n\nfdatadir = \"/fdata/hepx/store/user/taohuang/NANOAOD/\"\ndatasets = []; NumSample = []; sampleN_short = []\nNanodatasets = []; localdirs = {}\nMCxsections = []\n#doTT=True; doDY=True; do... | [
0
] |
#!/usr/bin/env python
'''
State Machine for the Flare task
'''
import roslib
import rospy
import actionlib
from rospy.timer import sleep
import smach
import smach_ros
from dynamic_reconfigure.server import Server
import math
import os
import sys
import numpy as np
from bbauv_msgs.msg import *
from bbauv_msgs.srv... | normal | {
"blob_id": "0bb2a6ebbf75fae3466c34a435a531fabdc07f62",
"index": 2984,
"step-1": "<mask token>\n\n\nclass Disengage(smach.State):\n\n def __init__(self, flare_task):\n smach.State.__init__(self, outcomes=['start_complete',\n 'complete_outcome', 'aborted'])\n self.flare = flare_task\n ... | [
12,
13,
15,
16,
20
] |
"""
Given two strings A and B of lowercase letters, return true
if and only if we can swap two letters in A so that the result
equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
"""
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False... | normal | {
"blob_id": "dd902f99ee8dc23f56641b8e75544a2d4576c19a",
"index": 4437,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution:\n\n def buddyStrings(self, A: str, B: str) ->bool:\n if len(A) != len(B):\n r... | [
0,
1,
2,
3
] |
def func(i):
if(i % 2 != 0): return False
visited = [0,0,0,0,0,0,0,0,0,0]
temp = i
while(i):
x = i%10
if (visited[x] == 1) or (x == 0): break
visited[x] = 1;
i = (int)(i / 10);
if(i == 0):
for y in str(temp):
if(temp % int(y) != 0): return False
else: return False... | normal | {
"blob_id": "1a8c9be389aad37a36630a962c20a0a36c449bdd",
"index": 3809,
"step-1": "<mask token>\n",
"step-2": "def func(i):\n if i % 2 != 0:\n return False\n visited = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n temp = i\n while i:\n x = i % 10\n if visited[x] == 1 or x == 0:\n ... | [
0,
1,
2,
3,
4
] |
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(
r'^create_new/$',
'hx_lti_assignment.views.create_new_assignment',
name="create_new_assignment",
),
url(
r'^(?P<id>[0-9]+)/edit/',
'hx_lti_assignment.views.edit_assignment',
name=... | normal | {
"blob_id": "2194fb4f0b0618f1c8db39f659a4890457f45b1d",
"index": 3963,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = patterns('', url('^create_new/$',\n 'hx_lti_assignment.views.create_new_assignment', name=\n 'create_new_assignment'), url('^(?P<id>[0-9]+)/edit/',\n 'hx_lti_assign... | [
0,
1,
2,
3
] |
'''
leetcode 338. 比特位计数
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
'''
class Solution(object):
def countBits(self, n):
"""
:type n: int
:rtype: List[int]
"""
out = [0] * (n+1)
for i in range(1,n+1,1):
if i%2==1: out[i]=o... | normal | {
"blob_id": "4cd1e385d18086b1045b1149d5f4573eaf9270c3",
"index": 6223,
"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 countBits(self, n):\n \"\"\"\n :type n: int\n :rty... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-03-15 16:39:32
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from widgets.favorits.favorit_win import Ui_DialogFavorit
import j... | normal | {
"blob_id": "14023785983f493af57189b3d96254efef2e33ae",
"index": 8180,
"step-1": "<mask token>\n\n\nclass Favorits(QDialog, Ui_DialogFavorit):\n <mask token>\n\n def __init__(self):\n super(Favorits, self).__init__()\n self.setupUi(self)\n self.buttonBox.button(QDialogButtonBox.Save).s... | [
4,
5,
7,
8,
9
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.