code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
'''
This module demonstrates how to use some functionality of python built-in csv module
'''
import csv
def csv_usage():
'''
This function demonstrates how to use csv module to read and write csv files
'''
with open('example.csv', 'r', newline='') as csvfile:
reader_c = csv.reader(csvfile, deli... | normal | {
"blob_id": "bcc2977f36ecc775f44ae4251ce230af9abf63ba",
"index": 7362,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef csv_usage():\n \"\"\"\n This function demonstrates how to use csv module to read and write csv files\n \"\"\"\n with open('example.csv', 'r', newline='') as csvfile:\n... | [
0,
1,
2,
3,
4
] |
def game_manager(info_list):
dictionary = {}
for piece_info in info_list:
piece_info = piece_info.split('||')
piece_info[2] = int(piece_info[2])
if piece_info[2] not in dictionary:
dictionary[piece_info[2]] = {(piece_info[1],piece_info[0])}
dictionary[piece_info[2]].a... | normal | {
"blob_id": "a382edb861a43ac3065a781ea996a8d1dd819954",
"index": 6649,
"step-1": "<mask token>\n",
"step-2": "def game_manager(info_list):\n dictionary = {}\n for piece_info in info_list:\n piece_info = piece_info.split('||')\n piece_info[2] = int(piece_info[2])\n if piece_info[2] no... | [
0,
1,
2,
3,
4
] |
import numpy
#Matrixmultiplikation
#Matrixinvertierung
#nicht p inv
#selbst invertierbar machen
import math
import operator | normal | {
"blob_id": "ece20c8c8fae2225cbac3552e254314b7116057c",
"index": 7095,
"step-1": "<mask token>\n",
"step-2": "import numpy\nimport math\nimport operator\n",
"step-3": "import numpy\n#Matrixmultiplikation\n#Matrixinvertierung\n#nicht p inv\n#selbst invertierbar machen\n\nimport math\nimport operator",
"step... | [
0,
1,
2
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the
# Pystacho Project (https://github.com/aruderman/pystacho/).
# Copyright (c) 2021, Francisco Fernandez, Benjamin Marcologno, Andrés Ruderman
# License: MIT
# Full Text: https://github.com/aruderman/pystacho/blob/master/LICENSE
# ===... | normal | {
"blob_id": "d7e24730ce9f2835d55d3995abec2a7d00eb05ef",
"index": 9024,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(PATH / 'pystacho' / '__init__.py') as fp:\n for line in fp.readlines():\n if line.startswith('__version__ = '):\n VERSION = line.split('=', 1)[-1].replace('... | [
0,
1,
2,
3,
4
] |
from itertools import cycle
STEP_VAL = 376
spinlock = []
for count in range(2018):
len(spinlock) % count
| normal | {
"blob_id": "c3755ff5d4262dbf6eaf3df58a336f5e61531435",
"index": 5149,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor count in range(2018):\n len(spinlock) % count\n",
"step-3": "<mask token>\nSTEP_VAL = 376\nspinlock = []\nfor count in range(2018):\n len(spinlock) % count\n",
"step-4": "fr... | [
0,
1,
2,
3
] |
# from django.shortcuts import render
# from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views import generic
from django.urls import reverse_lazy
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import aut... | normal | {
"blob_id": "c4b4585501319fd8a8106c91751bb1408912827a",
"index": 3180,
"step-1": "<mask token>\n\n\ndef top(request):\n return render(request, 'new_questions.html', {'title': 'Топ вопросов',\n 'questions': paginate(request, models.Question.objects.get_hot()),\n 'tags': paginate(request, models.T... | [
8,
12,
13,
18,
20
] |
from IPython import embed
from selenium import webdriver
b = webdriver.Firefox()
embed()
| normal | {
"blob_id": "9aa54f1259aceb052cfba74cedcfadfe68778ebd",
"index": 1020,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nembed()\n",
"step-3": "<mask token>\nb = webdriver.Firefox()\nembed()\n",
"step-4": "from IPython import embed\nfrom selenium import webdriver\nb = webdriver.Firefox()\nembed()\n",
... | [
0,
1,
2,
3
] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 foree <foree@foree-pc>
#
# Distributed under terms of the MIT license.
"""
配置logging的基本配置
"""
import logging
import sys
import os
from common.common import get_root_path
FILE_LEVEL = logging.DEBUG
STREAM_LEVEL = logging.WARN
LOG_DIR = ... | normal | {
"blob_id": "96910e9b6861fc9af0db3a3130d898fd1ee3daad",
"index": 3356,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif not os.path.exists(LOG_DIR):\n os.mkdir(LOG_DIR)\nif not os.path.exists(PATH_LOG):\n f = open(PATH_LOG, 'w')\n f.write('')\n f.close()\n<mask token>\nlogger.setLevel(loggin... | [
0,
1,
2,
3,
4
] |
import time
import jax.numpy as jnp
def tick():
return time.perf_counter()
def tock(t0, dat=None):
if dat is not None:
try:
_ = dat.block_until_ready()
except AttributeError:
_ = jnp.array(dat).block_until_ready()
return time.perf_counter() - t0
| normal | {
"blob_id": "e58dbb4f67c93abf3564dc0f38df8852313338f0",
"index": 5520,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef tock(t0, dat=None):\n if dat is not None:\n try:\n _ = dat.block_until_ready()\n except AttributeError:\n _ = jnp.array(dat).block_until_rea... | [
0,
1,
2,
3
] |
import unittest
from unittest.mock import patch
from redis import Redis
from rq.job import JobStatus
from rq.maintenance import clean_intermediate_queue
from rq.queue import Queue
from rq.utils import get_version
from rq.worker import Worker
from tests import RQTestCase
from tests.fixtures import say_hello
class Ma... | normal | {
"blob_id": "8dd864f1313f1e6f131ee11d4db99fbc46519126",
"index": 9826,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass MaintenanceTestCase(RQTestCase):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass MaintenanceTestCase(RQTestCase):\n\n @unittest.skipIf(get_version(Redis()) < (6, 2... | [
0,
1,
2,
3,
4
] |
from django.shortcuts import render
from django.http import response, HttpResponse, Http404
from django.views.generic import TemplateView
from django.db.models import Q
# Create your views here.
class Countries(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
return Cou... | normal | {
"blob_id": "fd7fe2e4ffaa4de913931e83fd1de40f79b08d98",
"index": 6222,
"step-1": "<mask token>\n\n\nclass Countries(TemplateView):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Countries(TemplateView):\n <mask token>\n\n def get_context_data(self, **kwargs):\n return C... | [
1,
2,
3,
4,
5
] |
import tornado.ioloop
import tornado.web
import json
import utils
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
class CondaHandler(BaseHandler):
... | normal | {
"blob_id": "44a9bb4d74d2e694f252d8726647bca13baa4df5",
"index": 853,
"step-1": "<mask token>\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n <mask token>\n\n\nclass CondaHandler(BaseHandler):\n\n def get(self, filePath):\n with open('packages/conda/' + filePath) as f:\n data = json... | [
5,
7,
8,
9,
10
] |
#!/usr/bin/env python
# Standardised set up
import RPi.GPIO as GPIO # External module imports GPIO
import time # Library to slow or give a rest to the script
import timeit # Alternative timing library for platform specific timing
import sys # Library to access program arguments and call exits
import os # Library provi... | normal | {
"blob_id": "4e9fd3ee2a78fae164d9f38704443ac5b2f4c11c",
"index": 1189,
"step-1": "<mask token>\n\n\nclass colour:\n purple = '\\x1b[95m'\n cyan = '\\x1b[96m'\n darkcyan = '\\x1b[36m'\n blue = '\\x1b[94m'\n green = '\\x1b[92m'\n yellow = '\\x1b[93m'\n red = '\\x1b[91m'\n bold = '\\x1b[1m'\... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from multiprocess.managers import BaseManager
from linphonebase import LinphoneBase
class MyManager(BaseManager):
pass
MyManager.register('LinphoneBase', LinphoneBase)
manager = MyManager()
manager.start()
linphoneBase = manager.LinphoneBase()
| normal | {
"blob_id": "3bb25cedc29f9063046329db1c00e7d9e10ce1cc",
"index": 5089,
"step-1": "<mask token>\n\n\nclass MyManager(BaseManager):\n pass\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass MyManager(BaseManager):\n pass\n\n\nMyManager.register('LinphoneBase', LinphoneBase)\n<mask token>\nmanager.sta... | [
1,
2,
3,
4,
5
] |
import random
from elment.login_registration_element import LoginRegistration
from page.test_verification_code_page import VerificationCodeAction
public_number_vip = ['17800000000','17800000001','17800000002','17800000003','17800000004','17800000005','17800000006',
'17800000007','17800000008','1780000... | normal | {
"blob_id": "e5a698979bc84fe733a9bf5cd51e2f078956d468",
"index": 2461,
"step-1": "<mask token>\n\n\nclass LoginRegistrationAction(LoginRegistration):\n\n def check_welcome_xunyou(self):\n return self.welcome_xunyou().text\n <mask token>\n\n def logged_in_random(self):\n self.phone_id().sen... | [
14,
18,
20,
25,
26
] |
#!/usr/bin/env python3
from utils import mathfont
import fontforge
v1 = 5 * mathfont.em
v2 = 1 * mathfont.em
f = mathfont.create("stack-bottomdisplaystyleshiftdown%d-axisheight%d" % (v1, v2),
"Copyright (c) 2016 MathML Association")
f.math.AxisHeight = v2
f.math.StackBottomDisplayStyleShiftDown = ... | normal | {
"blob_id": "06638b361c1cbe92660d242969590dfa45b63a4d",
"index": 75,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmathfont.save(f)\n<mask token>\nmathfont.save(f)\n<mask token>\nmathfont.save(f)\n<mask token>\nmathfont.save(f)\n<mask token>\nmathfont.save(f)\n<mask token>\nmathfont.save(f)\n",
"step-... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
import argparse
import sys
import os
import cmudl.hw2p2 as hw2p2
class CLI(object):
def __init__(self):
parser = argparse.ArgumentParser(
description='CMU Deep Learning Utilities',
)
parser.add_argument('command', help='Subcommand to run')
# p... | normal | {
"blob_id": "0f74e0f0600c373c3ddd470f18dbb86cf213fb58",
"index": 9257,
"step-1": "<mask token>\n\n\nclass CLI(object):\n <mask token>\n\n def hw2p2(self):\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', type=str, default=None)\n args = parser.parse_args(sys.argv[2:])\n... | [
2,
3,
4,
5,
6
] |
import json
from asgiref.sync import async_to_sync
from daphne_API.diversifier import activate_diversifier
from daphne_API.models import Design
def send_archs_back(channel_layer, channel_name, archs):
async_to_sync(channel_layer.send)(channel_name,
{
... | normal | {
"blob_id": "564c613491b0d1797b216a0bd425690e9fae12bc",
"index": 7725,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef send_archs_from_queue_to_main_dataset(context):\n background_queue_qs = Design.objects.filter(activecontext_id__exact=\n context.eosscontext.activecontext.id)\n arch_... | [
0,
1,
2,
3,
4
] |
#Classe do controlador do servidor SEEEEEEERVIDOOOOOOOOOOR
from usuarioModel import *
class ControllerSC:
'''
O controlador define 2 ações:
- adicionar_pessoa: para adicionar novas pessoas no banco de
dados.
- listar_pessoas: retornar a lista das pessoas
Note que as 2 ações supracita... | normal | {
"blob_id": "39eecf1c7ec19f7c75721caa092c08569f53d3e5",
"index": 9449,
"step-1": "<mask token>\n\n\nclass ControllerSC:\n <mask token>\n <mask token>\n\n @staticmethod\n def entrarSC(login, senha):\n resultado = Usuario.entrar(login, senha)\n return resultado\n <mask token>\n <mas... | [
2,
5,
6,
7,
8
] |
class Balloon(object):
def __init__(self, color, size, shape):
self.color = color
self.size = size
self.shape = shape
self.inflated = False
self.working = True
def inflate(self):
if self.working:
self.inflated = True
else:
print "Y... | normal | {
"blob_id": "2747b2563c83e11261a7113d69921c1affb20ac8",
"index": 4675,
"step-1": "class Balloon(object):\n def __init__(self, color, size, shape):\n self.color = color\n self.size = size\n self.shape = shape\n self.inflated = False\n self.working = True\n\n def inflate(se... | [
0
] |
from django.shortcuts import render
from django.http import HttpResponse
def view1(request):
return HttpResponse(" Hey..,This is the first view using HttpResponce!")
def view2(request):
context={"tag_var":"tag_var"}
return render(request,"new.html",context)
# Create your views here.
| normal | {
"blob_id": "c9b62328a463fd38f3dbd1e7b5e1990f7eec1dba",
"index": 9793,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef view2(request):\n context = {'tag_var': 'tag_var'}\n return render(request, 'new.html', context)\n",
"step-3": "<mask token>\n\n\ndef view1(request):\n return HttpRespo... | [
0,
1,
2,
3,
4
] |
from pythongame.core.buff_effects import get_buff_effect, register_buff_effect, StatModifyingBuffEffect
from pythongame.core.common import ItemType, Sprite, BuffType, Millis, HeroStat
from pythongame.core.game_data import UiIconSprite, register_buff_text
from pythongame.core.game_state import Event, PlayerDamagedEnemy,... | normal | {
"blob_id": "61454a3d6b5b17bff871ededc6ddfe8384043884",
"index": 59,
"step-1": "<mask token>\n\n\nclass ItemEffect(AbstractItemEffect):\n <mask token>\n\n\nclass BuffedByHealingWand(StatModifyingBuffEffect):\n\n def __init__(self):\n super().__init__(BUFF_TYPE, {HeroStat.HEALTH_REGEN: HEALTH_REGEN_B... | [
3,
4,
6,
7,
8
] |
file = open("yo.txt", "wr")
file.write("Yo")
| normal | {
"blob_id": "207b6e56b683c0b069c531a4c6076c2822814390",
"index": 512,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile.write('Yo')\n",
"step-3": "file = open('yo.txt', 'wr')\nfile.write('Yo')\n",
"step-4": "file = open(\"yo.txt\", \"wr\")\n\nfile.write(\"Yo\")\n\n",
"step-5": null,
"step-ids":... | [
0,
1,
2,
3
] |
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
x = list()
for line in handle:
line.split() ## unnesssecary
if line.startswith("From "):
x.append(line[line.find(" ")+1:line.find(" ",line.find(" ")+1)])
counts = dict()
for name in x:
if name not in co... | normal | {
"blob_id": "28091b7251f980f3f63abdb03140edd0d789be8f",
"index": 6414,
"step-1": "name = raw_input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox-short.txt\"\nhandle = open(name)\nx = list()\nfor line in handle:\n line.split() ## unnesssecary\n if line.startswith(\"From \"):\n x.append(line[line... | [
0
] |
# Employee Table's Dictionary
employee={
1001:{
"empname":"Ashish",
"Designation Code":'E',
"Department":"R&D",
"Basic": 20000,
"HRA": 8000,
"IT": 3000
},
1002:{
"empname":"Sushma",
"Designation Code":'C',
"Department":"PM",
"Ba... | normal | {
"blob_id": "fcb0fb439db77c4d57c449ec8f720dbd3fef5abc",
"index": 2871,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\"\"\"\n\nEmployee Details:\nEmployee Id:\"\"\", id, '\\nName:', employee[id][\n 'empname'], '\\nDepartment:', employee[id]['Department'],\n '\\nDesignation:', DA[employee[id]... | [
0,
1,
2,
3
] |
import random
import matplotlib.pyplot as plt
import tensorflow.keras as keras
mnist = keras.datasets.mnist # MNIST datasets
# Load Data and splitted to train & test sets
# x : the handwritten data, y : the number
(x_train_data, y_train_data), (x_test_data, y_test_data) = mnist.load_data()
print('x_train_d... | normal | {
"blob_id": "b4eb62413fb8069d8f11c34fbfecc742cd79bdb8",
"index": 7057,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('x_train_data shape:', x_train_data.shape)\nprint(x_train_data.shape[0], 'train samples')\nprint(x_test_data.shape[0], 'test samples')\nprint(x_train_data[0])\n<mask token>\nprint(y... | [
0,
1,
2,
3,
4
] |
import h5py
import numpy as np
from matplotlib import pyplot
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed("Dropping to IPython shell")
filename = "SPY-VXX-20090507-20100427.hdf5"
start_day = 1
end_day = 245
#start_day = 108
#end_day = 111
start_day = 120
end_day = 245
start_day = 1
end_day = 120
s... | normal | {
"blob_id": "175e8ecdd0c9faa5fc981447f821763e0eb58b4d",
"index": 5609,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nipshell = IPShellEmbed('Dropping to IPython shell')\nfilename = 'SPY-VXX-20090507-20100427.hdf5'\nstart_day = 1\nend_day = 245\nstart_day = 120\nend_day = 245\nstart_day = 1\nend_day = 12... | [
0,
1,
2,
3
] |
import os
import io
import time
import multiprocessing as mp
from queue import Empty
import picamera
from PIL import Image
from http import server
import socketserver
import numpy as np
import cv2
class QueueOutputMJPEG(object):
def __init__(self, queue, finished):
self.queue = queue
self.finished ... | normal | {
"blob_id": "ffd034eb5f0482c027dcc344bddb01b90249511c",
"index": 3198,
"step-1": "<mask token>\n\n\nclass QueueOutputMJPEG(object):\n\n def __init__(self, queue, finished):\n self.queue = queue\n self.finished = finished\n self.stream = io.BytesIO()\n\n def write(self, buf):\n i... | [
12,
13,
16,
17,
18
] |
import numpy as np
class settings:
def __init__(self, xmax, xmin, ymax, ymin, yrange, xrange):
self.xmax = xmax
self.xmin = xmin
self.ymax = ymax
self.ymin = ymin
self.yrange = yrange
self.xrange = xrange
pass
def mapminmax(x, ymin=-1.0, ymax... | normal | {
"blob_id": "e4a66617adbe863459e33f77c32c89e901f66995",
"index": 2309,
"step-1": "<mask token>\n\n\nclass settings:\n\n def __init__(self, xmax, xmin, ymax, ymin, yrange, xrange):\n self.xmax = xmax\n self.xmin = xmin\n self.ymax = ymax\n self.ymin = ymin\n self.yrange = yra... | [
7,
8,
9,
11,
12
] |
/Users/tanzy/anaconda3/lib/python3.6/_dummy_thread.py | normal | {
"blob_id": "08a5a903d3757f8821554aa3649ec2ac2b2995a5",
"index": 911,
"step-1": "/Users/tanzy/anaconda3/lib/python3.6/_dummy_thread.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 15:10:34 2018
@author: nit_n
"""
from gaussxw import gaussxwab
from numpy import linspace, arange
from pylab import plot, show, xlabel, ylabel
from math import pi, exp, sqrt
k = 1.38065e-23 # joules/kelvin
h = 6.626e-34 # joules
lam1 = 390e-9 # meters
... | normal | {
"blob_id": "9b88a3976d522bdfd38502e29eefc1f1a0c29ed2",
"index": 2884,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef n(T):\n k = 1.38065e-23\n c = 300000000.0\n N = 100\n a = h * c / (lam2 * k * T)\n b = h * c / (lam1 * k * T)\n x, w = gaussxwab(N, a, b)\n s = 0.0\n for k... | [
0,
2,
3,
4,
5
] |
import datetime
import json
import logging
from grab import Grab
from actions import get_course_gold, get_chat_type, get_indexes, group_chat_id
# logging.basicConfig(
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# level=logging.DEBUG)
# logger = logging.getLogger(__name__)
results = None... | normal | {
"blob_id": "c4720eb5a42267970d3a98517dce7857c0ba8450",
"index": 8938,
"step-1": "<mask token>\n\n\ndef check_date():\n global results\n global date_post\n current_datetime = datetime.datetime.now()\n current_date = current_datetime.date()\n if date_post is not None:\n if date_post < curren... | [
4,
5,
6,
7,
9
] |
from functools import partial
import numpy as np
import scipy.stats as sps
# SPMs HRF
def spm_hrf_compat(t,
peak_delay=6,
under_delay=16,
peak_disp=1,
under_disp=1,
p_u_ratio = 6,
normalize=True,
... | normal | {
"blob_id": "596ee5568a32c3044e797375fbc705e2091f35c2",
"index": 4340,
"step-1": "<mask token>\n\n\ndef spm_hrf_compat(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp\n =1, p_u_ratio=6, normalize=True):\n \"\"\" SPM HRF function from sum of two gamma PDFs\n\n This function is designed to be par... | [
4,
5,
6,
7,
8
] |
from flask import Flask, jsonify, abort, make_response
from matchtype import matchtyper
from db import db_handle
import sys
api = Flask(__name__)
@api.route('/get/<key_name>', methods=['GET'])
def get(key_name):
li = db_handle(key_name)
if li[1] is None:
abort(404)
else:
result = matchtype... | normal | {
"blob_id": "44e9fd355bfab3f007c5428e8a5f0930c4011646",
"index": 3853,
"step-1": "<mask token>\n\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n result = matchtyper(li)\n return make_response... | [
2,
3,
4,
5
] |
import numpy as np
from sklearn.preprocessing import OneHotEncoder
def formator(value):
return "%.2f" % value
def features_preprocessor(datasetLocation):
data = np.genfromtxt(datasetLocation,delimiter=",",usecols=range(41)) ##!!! usecols = range(41)
encoder = OneHotEncoder(categorical_features=[1,2,3])
encoder.fi... | normal | {
"blob_id": "f50c9aec85418553f4724146045ab7c3c60cbb80",
"index": 4404,
"step-1": "import numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\n\ndef formator(value):\n\treturn \"%.2f\" % value\n\ndef features_preprocessor(datasetLocation):\n\tdata = np.genfromtxt(datasetLocation,delimiter=\",\",usecols=r... | [
0
] |
<<<<<<< HEAD
"""Module docstring"""
import os
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
=======
#!/usr/bin/python
"""Module docstring"""... | normal | {
"blob_id": "2bce18354a53c49274f7dd017e1f65c9ff1327b9",
"index": 2264,
"step-1": "<<<<<<< HEAD\n\"\"\"Module docstring\"\"\"\nimport os\nimport numpy as np\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection impo... | [
0
] |
from pyspark import SparkContext, RDD
from pyspark.sql import SparkSession, DataFrame
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import string
from kafka import KafkaProducer
import time
import pyspark
sc = SparkContext(master='local[4]')
ssc = StreamingContext(sc, b... | normal | {
"blob_id": "12fdeae0ae1618139b20176846e7df5b82f7aa01",
"index": 8274,
"step-1": "<mask token>\n\n\ndef send_rdd(rdd):\n out_list = rdd.collect()\n for word in out_list:\n producer.send('had2020011-out', value=str(word))\n\n\n<mask token>\n\n\ndef aggregator(values, old):\n return (old or 0) + su... | [
2,
3,
4,
5,
6
] |
from libs.storage.blocks.iterators.base import BaseBlockIterator
from libs.storage.const import SEPARATOR
class ContentsBlockIterator(BaseBlockIterator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.contents = self.block_content.split(SEPARATOR)
self.titles ... | normal | {
"blob_id": "b888745b3ce815f7c9eb18f5e76bacfadfbff3f5",
"index": 3153,
"step-1": "<mask token>\n\n\nclass ContentsBlockIterator(BaseBlockIterator):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ContentsBlockIterator(BaseBlockIterator):\n\n def __init__(self, *args, **kwargs):\n ... | [
1,
2,
3,
4
] |
from django.conf.urls import url
from myapp import views
urlpatterns = [
url(r'^$', views.homepage, name='homepage'),
url(r'^search/', views.my_search_view, name = 'article_detail')
] | normal | {
"blob_id": "388e43850a2e114cfe7869293ee814831a088b3e",
"index": 8468,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('^$', views.homepage, name='homepage'), url('^search/',\n views.my_search_view, name='article_detail')]\n",
"step-3": "from django.conf.urls import url\nfrom myapp... | [
0,
1,
2,
3
] |
def slices(series, length):
if length <= 0:
raise ValueError("Length has to be at least 1")
elif length > len(series) or len(series) == 0:
raise ValueError("Length has to be larger than len of series")
elif length == len(series):
return [series]
else:
result = []
... | normal | {
"blob_id": "207bb7c79de069ad5d980d18cdfc5c4ab86c5197",
"index": 6544,
"step-1": "<mask token>\n",
"step-2": "def slices(series, length):\n if length <= 0:\n raise ValueError('Length has to be at least 1')\n elif length > len(series) or len(series) == 0:\n raise ValueError('Length has to be... | [
0,
1,
2
] |
import requests
from google.cloud import datastore
import google.cloud.logging
###Helper functions
def report_error(error_text):
"""Logs error to Stackdriver.
:param error_text: The text to log to Stackdriver
:type error_text: string
"""
client = google.cloud.logging.Client()
logger = client.l... | normal | {
"blob_id": "bf2b3b74f772026328cdd04412455ee758c43d3f",
"index": 8142,
"step-1": "<mask token>\n\n\ndef report_error(error_text):\n \"\"\"Logs error to Stackdriver.\n :param error_text: The text to log to Stackdriver\n :type error_text: string\n \"\"\"\n client = google.cloud.logging.Client()\n ... | [
10,
12,
13,
14,
15
] |
import h5py
import numpy as np
#import tracking
dt = h5py.special_dtype(vlen=bytes)
def stringDataset(group, name, data, system=None):
dset = group.create_dataset(name, (1,), dtype=dt, data=data)
if system:
addSystemAttribute(dset, system)
return dset
def addStringAttribute(dset_or_group, name, d... | normal | {
"blob_id": "d4ac5c6f08e9baa458fbe0ca7aa90c4d9372844f",
"index": 408,
"step-1": "<mask token>\n\n\ndef stringDataset(group, name, data, system=None):\n dset = group.create_dataset(name, (1,), dtype=dt, data=data)\n if system:\n addSystemAttribute(dset, system)\n return dset\n\n\ndef addStringAttr... | [
4,
5,
7,
8,
9
] |
import unittest
'''
시험 문제 2) 장식자 구현하기
- 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현
- 첫번째 인자 : 홀수의 합
- 두번째 인자 : 짝수의 합
모든 테스트가 통과하면, 다음과 같이 출력됩니다.
쉘> python final_2.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
'''
def divider(fn):
def wrap(*args):
o... | normal | {
"blob_id": "253804644e366382a730775402768bc307944a19",
"index": 6548,
"step-1": "<mask token>\n\n\ndef divider(fn):\n\n def wrap(*args):\n odd = sum(i for i in args if i % 2 != 0)\n even = sum(i for i in args if i % 2 == 0)\n return fn(odd, even)\n return wrap\n\n\n@divider\ndef mysum... | [
7,
8,
9,
10,
11
] |
from turtle import Screen
import time
from snake import Snake
from snake_food import Food
from snake_score import Scoreboard
screen = Screen()
screen.setup(width=600,height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
snake = Snake()
food=Food()
score=Scoreboard()
screen.... | normal | {
"blob_id": "cfc0ca0d8528937526f6c42721870f1739a2ae95",
"index": 5467,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nscreen.setup(width=600, height=600)\nscreen.bgcolor('black')\nscreen.title('Snake Game')\nscreen.tracer(0)\n<mask token>\nscreen.listen()\nscreen.onkey(snake.up, 'Up')\nscreen.onkey(snake... | [
0,
1,
2,
3,
4
] |
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
import subprocess
import os
import json
class HookView(APIView):
def post(self, request, *args, **kwargs):
SCRIPT_PAT... | normal | {
"blob_id": "6f5bca8c1afcd9d9971a64300a576ca2b2f6ef70",
"index": 1694,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass HookView(APIView):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass HookView(APIView):\n\n def post(self, request, *args, **kwargs):\n SCRIPT_PATH = os.path.... | [
0,
1,
2,
3,
4
] |
"""Test that Chopsticks remote processes can launch tunnels."""
from unittest import TestCase
from chopsticks.helpers import output_lines
from chopsticks.tunnel import Local, Docker, RemoteException
from chopsticks.facts import python_version
def ping_docker():
"""Start a docker container and read out its Python ... | normal | {
"blob_id": "4c63072b6242507c9b869c7fd38228488fda2771",
"index": 6098,
"step-1": "<mask token>\n\n\nclass RecursiveTest(TestCase):\n <mask token>\n\n def tearDown(self):\n ls = output_lines(['docker', 'ps', '-a'])\n images = []\n for l in ls[1:]:\n ws = l.split()\n ... | [
4,
5,
7,
8,
9
] |
from Domain.Librarie import vanzare_obiect, get_id, get_titlu, get_gen, get_pret, get_tip_reducere
def inverse_create(lst_vanzari, id_carte):
new_vanzari = []
for carte in lst_vanzari:
if get_id(carte) != id_carte:
new_vanzari.append(carte)
return new_vanzari
def get_by_id(id, lista):... | normal | {
"blob_id": "498d07421d848332ad528ef3d3910d70312b5f55",
"index": 2606,
"step-1": "<mask token>\n\n\ndef get_by_id(id, lista):\n \"\"\"\n ia vanzarea cu id-ul dat dintr-o lista\n :param id: id-ul vanzarii - string\n :param lista: lista de vanzari\n :return: vanzarea cu id-ul dat sau None daca nu ex... | [
4,
5,
6,
7,
8
] |
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf.urls import include
# from rest_framework import routers
from rest_framework.authtoken import views
# from adventure.api import PlayerViewSet, RoomViewSet
# from adventure.api import move
# router = routers.DefaultRoute... | normal | {
"blob_id": "a14114f9bb677601e6d75a72b84ec128fc9bbe61",
"index": 71,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('admin/', admin.site.urls), path('api/', include(\n 'api.urls')), path('api/adv/', include('adventure.urls'))]\n",
"step-3": "from django.contrib import admin\nfrom... | [
0,
1,
2,
3
] |
import sys
import time
import numpy
import pb_robot
import pyquaternion
import pybullet as p
from copy import deepcopy
from actions import PlaceAction, make_platform_world
from block_utils import get_adversarial_blocks, rotation_group, ZERO_POS, \
Quaternion, get_rotated_block, Pose, add_noise,... | normal | {
"blob_id": "5c1465bc70010ecabc156a04ec9877bbf66a229d",
"index": 5150,
"step-1": "<mask token>\n\n\nclass PandaAgent:\n\n def __init__(self, blocks, noise=5e-05, block_init_xy_poses=None,\n use_platform=False, use_vision=False, real=False,\n use_planning_server=False, use_learning_server=False,\... | [
20,
22,
24,
25,
26
] |
from lilaclib import *
def pre_build():
newver = _G.newver.removeprefix('amd-drm-fixes-')
for line in edit_file('PKGBUILD'):
if line.startswith('_tag'):
line = "_tag='amd-drm-fixes-" + newver + "'"
print(line)
newver2 = newver.replace("-",".")
update_pkgver_and_pkgrel(newver2)
def post_... | normal | {
"blob_id": "32eff306444966fab47815fcbae4aefb6769d29b",
"index": 9684,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef post_build():\n git_add_files('PKGBUILD')\n git_commit()\n update_aur_repo()\n",
"step-3": "<mask token>\n\n\ndef pre_build():\n newver = _G.newver.removeprefix('amd... | [
0,
1,
2,
3,
4
] |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import c... | normal | {
"blob_id": "84db1803a352e0ed8c01b7166f522d46ec89b6f5",
"index": 2487,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor train_index, test_index in kf.split(x):\n xtr = x.iloc[train_index]\n ytr = y[train_index]\n<mask token>\nif k % 2 == 0:\n k = k + 1\nelse:\n k = k\n<mask token>\nprint('S... | [
0,
1,
2,
3,
4
] |
""" Codewars kata: Evaluate mathematical expression. https://www.codewars.com/kata/52a78825cdfc2cfc87000005/train/python """
#######################################################################################################################
#
# Import
#
###########################################################... | normal | {
"blob_id": "ac14e88810b848dbf4ff32ea99fd274cd0285e1c",
"index": 3539,
"step-1": "<mask token>\n\n\nclass Calculator(object):\n <mask token>\n\n def _float_to_string_(self, f, p=40):\n result = f'{f:+1.{p}f}'\n if '.' in result:\n result = result.rstrip('0')\n if result[... | [
6,
7,
9,
10,
11
] |
#Una empresa les paga a sus empleados con base en las horas trabajadas en la semana.
#Realice un algoritmo para determinar el sueldo semanal de N trabajadores
#y, además, calcule cuánto pagó la empresa por los N empleados.
base = int(input("Dinero por hora trabajada: "))
emp = int(input("Dime el nº de empleados... | normal | {
"blob_id": "963e736fd4a942fb1c51e1e0a357ad6be48aed9a",
"index": 5985,
"step-1": "\r\n#Una empresa les paga a sus empleados con base en las horas trabajadas en la semana.\r\n#Realice un algoritmo para determinar el sueldo semanal de N trabajadores\r\n#y, además, calcule cuánto pagó la empresa por los N empleados... | [
0
] |
from django.db.models import Q
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from relations.models import Relation
from .. import models
class ConversationAccessPermission(BasePermission):
message = 'You cant see others conversations!'
def has_o... | normal | {
"blob_id": "56b5faf925d9a1bfaef348caeb35a7d3c323d57f",
"index": 8450,
"step-1": "<mask token>\n\n\nclass SendMessagePermission(BasePermission):\n <mask token>\n <mask token>\n\n\nclass MessageOwnerPermission(BasePermission):\n message = 'You cant modify your messages only!'\n\n def has_object_permis... | [
4,
6,
8,
10,
11
] |
import numpy as np, pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.base import BaseEstimator, TransformerMixin
from datetime import timedelta
import sys
DEBUG = False
class DailyAggregator(BaseEstimator, TransformerMixin):
''' Aggregates time-series values to daily level. '''
def... | normal | {
"blob_id": "9f7b1cfcc3c20910201fc67b5a641a5a89908bd1",
"index": 8980,
"step-1": "<mask token>\n\n\nclass IndexSetter(BaseEstimator, TransformerMixin):\n \"\"\" Set index \"\"\"\n\n def __init__(self, index_cols, drop_existing):\n self.index_cols = index_cols\n self.drop_existing = drop_exist... | [
41,
44,
52,
56,
62
] |
import numpy
numpy.random.seed(1)
M = 20
N = 100
import numpy as np
x = np.random.randn(N, 2)
w = np.random.randn(M, 2)
f = np.einsum('ik,jk->ij', w, x)
y = f + 0.1*np.random.randn(M, N)
D = 10
from bayespy.nodes import GaussianARD, Gamma, SumMultiply
X = GaussianARD(0, 1, plates=(1,N), shape=(D,))
alpha = Gamma(1e-5, ... | normal | {
"blob_id": "9af2b94c6eef47dad0348a5437593cc8561a7deb",
"index": 3593,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nnumpy.random.seed(1)\n<mask token>\nY.observe(y)\n<mask token>\nC.initialize_from_random()\n<mask token>\nQ.set_callback(R.rotate)\nQ.update(repeat=1000)\n<mask token>\nbpplt.hinton(C)\n"... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
import requests
import re
def get_content(url):
paste_info = {
'site': 'pomf',
'url': url
}
m = re.match('^.*/([0-9a-zA-Z]+)\.([a-zA-Z0-9]+)$',url)
response = requests.get(url)
if response.status_code != 200:
return
paste_info['ext'] = m.group(2)
... | normal | {
"blob_id": "78a6202f501bc116e21e98a3e83c9e3f8d6402b4",
"index": 3981,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_content(url):\n paste_info = {'site': 'pomf', 'url': url}\n m = re.match('^.*/([0-9a-zA-Z]+)\\\\.([a-zA-Z0-9]+)$', url)\n response = requests.get(url)\n if respons... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Agile Business Group sagl (<http://www.agilebg.com>)
# Author: Nicola Malcontenti <nicola.malcontenti@agilebg.com>
#
# This program is free software: you can redistribute it and/or modi... | normal | {
"blob_id": "b111d799b9e71cf36253c37f83dc0cdc8887a32e",
"index": 7404,
"step-1": "<mask token>\n\n\nclass StockPicking(orm.Model):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass StockPicking(orm.Model):\n <mask token>\n\n def _get_invoice_vals(self, cr, uid, key, inv_type, jou... | [
1,
2,
3,
4,
5
] |
# coding: utf-8
"""
Meme Meister
API to create memes # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.api.default_api import DefaultA... | normal | {
"blob_id": "fca46c095972e8190ee9c93f3bddbb2a49363a7f",
"index": 6903,
"step-1": "<mask token>\n\n\nclass TestDefaultApi(unittest.TestCase):\n <mask token>\n <mask token>\n\n def tearDown(self):\n pass\n <mask token>\n\n def test_meme_meme_id_delete(self):\n \"\"\"Test case for meme_... | [
5,
8,
9,
10,
11
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Greger Update Agent (GUA) module for the Greger Client Module
"""
__author__ = "Eric Sandbling"
__license__ = 'MIT'
__status__ = 'Development'
# System modules
import os, sys
import shutil
import logging
import subprocess
from threading import Event
from threading im... | normal | {
"blob_id": "a9b2a4d4924dcdd6e146ea346e71bf42c0259846",
"index": 593,
"step-1": "<mask token>\n\n\nclass GregerUpdateAgent(Thread):\n <mask token>\n <mask token>\n\n @property\n def localRevisionRecord(self):\n \"\"\"\n Get local revision record (.gcm)\n \"\"\"\n localLog ... | [
5,
6,
7,
8,
11
] |
"""
Test cases for ldaptor.protocols.ldap.delta
"""
from twisted.trial import unittest
from ldaptor import delta, entry, attributeset, inmemory
from ldaptor.protocols.ldap import ldapsyntax, distinguishedname, ldaperrors
class TestModifications(unittest.TestCase):
def setUp(self):
self.foo = ldapsyntax.L... | normal | {
"blob_id": "8054ccb07d0130b75927a4bb9b712ce3d564b8fe",
"index": 4702,
"step-1": "<mask token>\n\n\nclass TestModificationOpLDIF(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def testReplaceAll(self):\n m = delta.Replace('thud')\n self.assertEqua... | [
43,
46,
52,
54,
63
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cProfile
import re
import pstats
import os
import functools
# cProfile.run('re.compile("foo|bar")')
def do_cprofile(filename):
"""
decorator for function profiling
:param filename:
:return:
"""
def wrapper(func):
@functools.wraps... | normal | {
"blob_id": "8c055816def1c0a19e672ab4386f9b9a345b6323",
"index": 7837,
"step-1": "<mask token>\n\n\nclass Memoized(object):\n\n def __init__(self, func):\n self.func = func\n self.results = {}\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Memoized... | [
2,
4,
7,
8,
9
] |
# -*- coding: utf-8 -*-
from scrapy import Request
from ..items import ZhilianSpiderItem
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from scrapy_redis.spiders import RedisCrawlSpider
class ZhilianSpider(RedisCrawlSpider):
name = 'zhilianspider'
headers = {
'User-Ag... | normal | {
"blob_id": "894fa01e16d200add20f614fd4a5ee9071777db9",
"index": 3339,
"step-1": "<mask token>\n\n\nclass ZhilianSpider(RedisCrawlSpider):\n <mask token>\n <mask token>\n <mask token>\n\n def start_requests(self):\n url = (\n 'https://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E4%B8... | [
2,
3,
4,
5,
6
] |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditio... | normal | {
"blob_id": "9fa534664056a8cf9e9a64ccc7d6dd4de2ec0936",
"index": 1514,
"step-1": "<mask token>\n\n\nclass Trainer(object):\n <mask token>\n\n def __init__(self, data_loader, model_name, model, optimizer_fn,\n final_steps, lr_scheduler_fn=None, step=0, ckpt_path=None, log_path\n =None, n_epoch... | [
8,
12,
13,
14,
15
] |
from StringIO import StringIO
import gzip
import urllib2
import urllib
url="http://api.syosetu.com/novelapi/api/"
get={}
get["gzip"]=5
get["out"]="json"
get["of"]="t-s-w"
get["lim"]=500
get["type"]="er"
url_values = urllib.urlencode(get)
request = urllib2.Request(url+"?"+url_values)
response = urllib2.urlopen(reque... | normal | {
"blob_id": "4b622c7f9b5caa7f88367dd1fdb0bb9e4a81477b",
"index": 2338,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif response.info().get('Content-Type') == 'application/x-gzip':\n buf = StringIO(response.read())\n f = gzip.GzipFile(fileobj=buf)\n data = f.read()\nelse:\n data = response.r... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
# Copyright 2019, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=undefined-loop-variable
"""
Run through RB for different qubit numbers to check that it's working
and that... | normal | {
"blob_id": "995e42312e286d82fa101128795d8aa60c1a6548",
"index": 4203,
"step-1": "<mask token>\n\n\nclass TestRB(unittest.TestCase):\n <mask token>\n\n @staticmethod\n def choose_pattern(pattern_type, nq):\n \"\"\"\n Choose a valid field for rb_opts['rb_pattern']\n :param pattern_ty... | [
6,
7,
8,
9,
10
] |
def test_corr_callable_method(self, datetime_series):
my_corr = (lambda a, b: (1.0 if (a == b).all() else 0.0))
s1 = Series([1, 2, 3, 4, 5])
s2 = Series([5, 4, 3, 2, 1])
expected = 0
tm.assert_almost_equal(s1.corr(s2, method=my_corr), expected)
tm.assert_almost_equal(datetime_series.corr(datetim... | normal | {
"blob_id": "5e68233fde741c0d2a94bf099afb6a91c08e2a29",
"index": 6071,
"step-1": "<mask token>\n",
"step-2": "def test_corr_callable_method(self, datetime_series):\n my_corr = lambda a, b: 1.0 if (a == b).all() else 0.0\n s1 = Series([1, 2, 3, 4, 5])\n s2 = Series([5, 4, 3, 2, 1])\n expected = 0\n ... | [
0,
1,
2
] |
from django.shortcuts import redirect, render
from users.models import CustomUser
from .models import Profile
def profile_page_view(request, username):
current_user = request.user
user = CustomUser.objects.get(username=username)
profile = Profile.objects.get(user=user)
if current_user in profile.follow... | normal | {
"blob_id": "3caaa455cda0567b79ae063c777846157839d64f",
"index": 8548,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef profile_page_view(request, username):\n current_user = request.user\n user = CustomUser.objects.get(username=username)\n profile = Profile.objects.get(user=user)\n if ... | [
0,
1,
2,
3,
4
] |
import pathlib, random, cv2
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
import albumentations as A
from matplotlib import pyplot as plt
from functools import partial
from sklearn.model_selection import train_test_split
# GPU setup
gpus = tf.config.experimental.list_physical_devices(... | normal | {
"blob_id": "943e8be7a9ee4e494c0a42e1368555f3df3de897",
"index": 1518,
"step-1": "<mask token>\n\n\ndef aug_fn(image):\n data = {'image': image}\n aug_data = transforms(**data)\n aug_img = aug_data['image']\n aug_img = tf.cast(aug_img, tf.float32) / 255.0\n aug_img = tf.image.per_image_standardiza... | [
7,
10,
11,
12,
16
] |
class Coms:
def __init__(self, name, addr, coord):
self.name = name
self.addr = addr
self.coord = coord
def getString(self):
return "회사명\n"+self.name+"\n\n주소\n"+self.addr
def getTeleString(self):
return "회사명 : " + self.name + ", 주소 : " + self.addr
class Jobs:
d... | normal | {
"blob_id": "bcc24d5f97e46433acb8bcfb08fe582f51eb28ce",
"index": 2932,
"step-1": "<mask token>\n\n\nclass Jobs:\n\n def __init__(self, name, type, experience, education, keyword, salary,\n url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n ... | [
4,
5,
6,
7,
9
] |
from django.shortcuts import render
from django.views.generic import View #导入View
from .models import UpdateDbData,User
from wanwenyc.settings import DJANGO_SERVER_YUMING
from .forms import UpdateDbDataForm
# Create your views here.
#添加场景的view
class UpdateDbDataView(View): #继承View
"""
测试数据复制编写页面处理
... | normal | {
"blob_id": "129c7f349e2723d9555da44ae62f7cfb7227b9ae",
"index": 5618,
"step-1": "<mask token>\n\n\nclass UpdateDbDataView(View):\n <mask token>\n\n def get(self, request, testupdatadb_id):\n if request.user.username == 'check':\n return render(request, 'canNotAddupdatedbdata.html', {\n ... | [
2,
3,
4,
5,
6
] |
#Print table using while loop
tablenumber = int(input("Enter a number: "))
upperlimit = int(input("Enter a upper limit: "))
lowerlimit = int(input("Enter a lower limit: "))
i = upperlimit
while (i <= lowerlimit):
print (i,"*",tablenumber,"=",i*tablenumber)
i=i+1
print("========================================... | normal | {
"blob_id": "e2c69191d81724cac44bebba3111a773e408b7c8",
"index": 639,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile i <= lowerlimit:\n print(i, '*', tablenumber, '=', i * tablenumber)\n i = i + 1\nprint('=======================================================')\n<mask token>\nfor foreachnumb... | [
0,
1,
2,
3
] |
import tkinter as tk
import random
from tkinter import messagebox as mb
n = 16
class Application(tk.Frame):
playButtons = [0] * n
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(sticky='NEWS')
self.createWidgets()
def show_win(self):
msg = "YOU ... | normal | {
"blob_id": "f29bc0263f8bb1d59ab2442347727d9d3233ec77",
"index": 9893,
"step-1": "<mask token>\n\n\nclass Application(tk.Frame):\n <mask token>\n <mask token>\n\n def show_win(self):\n msg = 'YOU WIN!'\n mb.showinfo('Information', msg)\n self.makePlayButtons()\n\n def move(self, ... | [
5,
7,
8,
9,
11
] |
from distutils.core import setup
setup(name='dcnn_visualizer', version='', packages=['dcnn_visualizer',
'dcnn_visualizer.backward_functions'], url='', license='', author=
'Aiga SUZUKI', author_email='tochikuji@gmail.com', description='',
requires=['numpy', 'chainer', 'chainercv'])
| normal | {
"blob_id": "b9a75f4e106efade3a1ebdcfe66413107d7eccd0",
"index": 7884,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='dcnn_visualizer', version='', packages=['dcnn_visualizer',\n 'dcnn_visualizer.backward_functions'], url='', license='', author=\n 'Aiga SUZUKI', author_email='tochikuji@... | [
0,
1,
2
] |
from pyecharts.charts.pie import Pie
from pyecharts.charts.map import Map
import static.name_map
from pymongo import MongoClient
# html代码头尾
html1 = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>疫情数据可视化</title><script src="/static/echarts/echarts.js"></script><script src="/static/china.js"></... | normal | {
"blob_id": "f1c65fc4acafbda59aeea4f2dfca2cf5012dd389",
"index": 8982,
"step-1": "<mask token>\n\n\ndef make_PieChart(country):\n global Data\n Data = []\n client = MongoClient()\n db = client.mydb\n if country == 'China':\n tb = db.ChinaData\n else:\n tb = db.WorldData\n re = ... | [
2,
3,
4,
5,
6
] |
# Planet Class
from turtle import *
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2*3.1415*self.radius... | normal | {
"blob_id": "668b63d1f1bd035226e3e12bc6816abc897affc3",
"index": 9975,
"step-1": "<mask token>\n\n\nclass Planet:\n\n def __init__(self, x, y, radius):\n self.radius = radius\n self.x = x\n self.y = y\n canvas = Screen()\n canvas.setup(800, 800)\n self.turtle = Turtle... | [
4,
6,
7,
8,
9
] |
from scipy.optimize import newton
from math import sqrt
import time
def GetRadius(Ri,DV,mu):
def f(Rf):
return sqrt(mu/Ri)*(sqrt(2*Rf/(Rf+Ri))-1)+sqrt(mu/Rf)*(1-sqrt(2*Ri/(Rf+Ri)))-DV
return newton(f,Ri)
if __name__ == '__main__':
starttime = time.time()
print(GetRadius(10000.0,23546.2146710... | normal | {
"blob_id": "20722cf82371d176942e068e91b8fb38b4db61fd",
"index": 6951,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef GetRadius(Ri, DV, mu):\n\n def f(Rf):\n return sqrt(mu / Ri) * (sqrt(2 * Rf / (Rf + Ri)) - 1) + sqrt(mu / Rf\n ) * (1 - sqrt(2 * Ri / (Rf + Ri))) - DV\n re... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python3
################################################################################
# Usefull functions to shorten some of my plotting routine #####################
################################################################################
import matplotlib.pyplot as plt
import seaborn as sns
i... | normal | {
"blob_id": "b935c48210b1965ebb0de78384f279b71fc17d5d",
"index": 7044,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef set_sns_standard(context='paper', font_scale=1.4, linewidth=1.5, font=\n 'serif'):\n rc_params = {'lines.linewidth': linewidth, 'text.usetex': True}\n sns.set(style='tick... | [
0,
2,
3,
4,
5
] |
"""Utils module."""
import click
import os.path
import pandas as pd
from tensorflow.keras.models import load_model
from tensorflow.keras.regularizers import l1_l2
from tensorflow.keras.callbacks import CSVLogger, ModelCheckpoint, TensorBoard
from zalando_classification.models import build_model
def get_basename(na... | normal | {
"blob_id": "6553312c9655c821444ff5f60e4d68c7fc08bd08",
"index": 1118,
"step-1": "<mask token>\n\n\ndef get_basename(name, split_num):\n return f'{name}.split{split_num:d}'\n\n\n<mask token>\n\n\ndef maybe_load_model(name, split_num, checkpoint_dir, resume_from_epoch,\n batch_norm, l1_factor, l2_factor, op... | [
3,
4,
5,
6,
7
] |
import argparse
from figure import Figure
from figure.Circle import Circle
from figure.Square import Square
class FCreator(object):
__types = ['square', 'circle']
def createParser(self, line: str):
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--type', required=True, choices=... | normal | {
"blob_id": "086ee4de1d74654ef85bd0a169fdf49c8f52bef2",
"index": 3792,
"step-1": "<mask token>\n\n\nclass FCreator(object):\n <mask token>\n <mask token>\n\n def editParser(self, line: str):\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--name', required=True)\n ... | [
5,
7,
8,
9,
12
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-07-10 02:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('civictechprojects', '0036_auto_20200708_2251'),
]
operations = [
migration... | normal | {
"blob_id": "99154212d8d5fdb92cd972c727791158d09e3e2c",
"index": 3789,
"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 = [('civictechpr... | [
0,
1,
2,
3,
4
] |
import json
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
from flask import abort, Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from helpers import login_required
# Configure application
app = ... | normal | {
"blob_id": "4f674b30c919c7ec72c11a8edd9692c91da7cb90",
"index": 9595,
"step-1": "<mask token>\n\n\n@app.route('/tracks', methods=['POST'])\ndef get_user_tracks():\n ids = json.loads(request.data)['ids']\n tracks.extend(ids)\n return 'success'\n\n\n@app.route('/')\n@login_required\ndef index():\n use... | [
4,
6,
7,
8,
9
] |
from PIL import Image
from flask_restplus import Namespace, Resource
from werkzeug.datastructures import FileStorage
from core.models.depthinthewild import DepthInTheWild
from core.utils import serve_pil_image
api = Namespace('nyudepth', description='Models Trained on NYUDepth')
upload_parser = api.parser()
upload_pars... | normal | {
"blob_id": "acf409f2e56cd16b7dc07476b49b9c18675f7775",
"index": 5540,
"step-1": "<mask token>\n\n\n@api.route('/depthinthewild/transform')\n@api.expect(upload_parser)\nclass DepthInTheWildDepthTransform(Resource):\n <mask token>\n\n\n@api.route('/depthinthewild/transform_raw')\n@api.expect(upload_parser)\ncl... | [
3,
5,
6,
7
] |
from Get2Gether.api_routes.schedule import schedule_router
from Get2Gether.api_routes.auth import auth_router
from Get2Gether.api_routes.event import event_router
| normal | {
"blob_id": "cd9d10a3ee3956762d88e76a951023dd77023942",
"index": 6411,
"step-1": "<mask token>\n",
"step-2": "from Get2Gether.api_routes.schedule import schedule_router\nfrom Get2Gether.api_routes.auth import auth_router\nfrom Get2Gether.api_routes.event import event_router\n",
"step-3": null,
"step-4": nu... | [
0,
1
] |
from tkinter import *
root = Tk()
ent = Entry(root)
ent.pack()
def click():
ent_text = ent.get()
lab = Label(root, text=ent_text)
lab.pack()
btn = Button(root, text="Click Me!", command=click)
btn.pack()
root.mainloop()
| normal | {
"blob_id": "49f1b4c9c6d15b8322b83396c22e1027d241da33",
"index": 2311,
"step-1": "<mask token>\n\n\ndef click():\n ent_text = ent.get()\n lab = Label(root, text=ent_text)\n lab.pack()\n\n\n<mask token>\n",
"step-2": "<mask token>\nent.pack()\n\n\ndef click():\n ent_text = ent.get()\n lab = Label... | [
1,
2,
3,
4,
5
] |
function handler(event, context, callback){
var
AWS = require("aws-sdk"),
DDB = new AWS.DynamoDB({
apiVersion: "2012-08-10",
region: "us-east-1"
}),
city_str = event.city_str.toUpperCase(),
data = {
city_str: city_str,
... | normal | {
"blob_id": "7bac3b224586f8c42a104123432a7321a1251369",
"index": 7115,
"step-1": "function handler(event, context, callback){\r\n var \r\n AWS = require(\"aws-sdk\"),\r\n DDB = new AWS.DynamoDB({\r\n apiVersion: \"2012-08-10\",\r\n region: \"us-east-1\"\r\n }),\r\n ... | [
0
] |
from django.urls import path, re_path
from app.views import UploaderAPIView, TeacherListAPIView, TeacherDetailAPIView
app_name = "directory"
urlpatterns = [
re_path(r"^directory/uploader/?$", UploaderAPIView.as_view(), name="teacher_uploader"),
re_path(r"^directory/teachers/?$", TeacherListAPIView.as_view(), ... | normal | {
"blob_id": "666e839b4d66dc4eede4e7325bfd4f4b801fd47d",
"index": 5330,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'directory'\nurlpatterns = [re_path('^directory/uploader/?$', UploaderAPIView.as_view(),\n name='teacher_uploader'), re_path('^directory/teachers/?$',\n TeacherListAPIVie... | [
0,
1,
2,
3
] |
import numpy as np
import matplotlib.pyplot as plt
# some important constants
x_bound = y_bound = 1.
dx = dy = 0.05
k = 0.1
nx, ny = int(x_bound/dx), int(y_bound/dy)
dx2, dy2 = dx*dx, dy*dy
dt = (dx2 / k) / 4.0
t_end = 80 * dt
# set the grid
u0 = np.zeros((nx, ny))
u_exact = np.zeros((nx, ny))
u = np.zeros((nx, ny))... | normal | {
"blob_id": "c556aaf6aecb3c91d9574e0a158a9fa954108d70",
"index": 8193,
"step-1": "<mask token>\n\n\ndef get_exact(x, y, t, trunc):\n \"\"\"Get the exact solution at a set t\n \"\"\"\n Z = 0\n for n in range(1, trunc):\n for m in range(1, trunc):\n Z_num = -120 * ((-n) ** 4 * np.pi *... | [
2,
4,
5,
6,
7
] |
import pickle as pickle
import os
import pandas as pd
import torch
import numpy as np
import random
from sklearn.metrics import accuracy_score
from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification, Trainer, TrainingArguments, XLMRobertaConfig, ElectraForSequenceClassification, Electra... | normal | {
"blob_id": "d3b6a105b14d9c3485a71058391a03c2f4aa5c10",
"index": 8628,
"step-1": "<mask token>\n\n\ndef seed_everything(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = ... | [
3,
4,
6,
7,
8
] |
import random as rnd
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support, roc_auc_score
import os
def mkdir_tree(source):
... | normal | {
"blob_id": "11ca13aca699b1e0744243645b3dbcbb0dacdb7e",
"index": 9588,
"step-1": "<mask token>\n\n\ndef mkdir_tree(source):\n if source is None:\n source = 'default'\n base_dirs = ['../data/clf_meta/%s/' % source]\n print('base_dirsssssss', base_dirs)\n for base_dir in base_dirs:\n if n... | [
3,
4,
5,
6,
7
] |
#!/usr/bin/env python3
"""
This file contains all the required methods for the street prediction utilizing
the Hough transform.
"""
import numpy as np
import scipy.ndimage as ndi
from skimage.draw import polygon
from skimage.transform import hough_line
def draw_roads(roads, shape):
"""
Creates an image wit... | normal | {
"blob_id": "f76185095ebb1adbf7ae22ffb500ffc3d6b0a30d",
"index": 6019,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef find_roads(probability_map, *, input_threshold=0.3, max_roads=None,\n min_strength=0.17, num_angles=720, roads_min_angle=np.pi / 8,\n roads_min_distance=50, debugimage=None,... | [
0,
3,
4,
5,
6
] |
# генераторы списков и словарей
# lists
my_list = [1, 2, 3, 4, 5]
new_list = []
for i in my_list:
new_list.append(i**2)
new_list_comp = [el**2 for el in my_list]
lines = [line.strip() for line in open("text.txt")]
new_list_1 = [el for el in my_list if el % 2 == 0]
str_1 = 'abc'
str_2 = 'def'
str_3 = 'gh'
new_... | normal | {
"blob_id": "e54eea2261517a2b15fde23c46b3fe75c0efec64",
"index": 7746,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in my_list:\n new_list.append(i ** 2)\n<mask token>\nprint(my_dict)\n<mask token>\nprint(new_list_round)\n",
"step-3": "my_list = [1, 2, 3, 4, 5]\nnew_list = []\nfor i in my_li... | [
0,
1,
2,
3
] |
import numpy as np
#
#
#
basedir = '/n/regal/pfister_lab/haehn/CREMITEST/'
testA = basedir + 'testA.npz.npy'
testA_targets = basedir + 'testA_targets.npz.npy'
testB = basedir + 'testB.npz.npy'
testB_targets = basedir + 'testB_targets.npz.npy'
testC = basedir + 'testC.npz.npy'
testC_targets = basedir + 'testC_targets... | normal | {
"blob_id": "5cb7af5ded532058db7f5520d48ff418ba856f04",
"index": 6150,
"step-1": "import numpy as np\n\n#\n#\n#\n\nbasedir = '/n/regal/pfister_lab/haehn/CREMITEST/'\n\ntestA = basedir + 'testA.npz.npy'\ntestA_targets = basedir + 'testA_targets.npz.npy'\ntestB = basedir + 'testB.npz.npy'\ntestB_targets = basedir ... | [
0
] |
#!/usr/bin/env python
import ROOT
ROOT.gROOT.SetBatch()
ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = kError;')
import os
import time
import varial.tools
import varial.generators as gen
import itertools
from varial.sample import Sample
import varial.analysis as analysis
# import varial.toolinterface
dirname = 'VLQToHi... | normal | {
"blob_id": "05ced056bf2f59f85bef82e53803e7df7ff8c8df",
"index": 1156,
"step-1": "<mask token>\n\n\ndef select_histograms(wrp):\n use_this = True\n if use_cuts and all('NoGenSel-' + c not in wrp.in_file_path for c in\n current_cuts):\n use_this = False\n if wrp.name.startswith('cf_'):\n ... | [
10,
13,
14,
18,
20
] |
from urllib.error import URLError
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import pymysql
import ssl
from pymysql import Error
def decode_page(page_bytes, charsets=('utf-8',)):
"""通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)"""
page_html = None
for charset in charsets:
try... | normal | {
"blob_id": "53fae0103168f4074ba0645c33e4640fcefdfc96",
"index": 731,
"step-1": "<mask token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(c... | [
5,
6,
7,
8,
9
] |
import copy
import math
import operator
import numpy as np, pprint
def turn_left(action):
switcher = {
(-1, 0): (0, -1),
(0, 1): (-1, 0),
(1, 0): (0, 1),
(0, -1): (1, 0)
}
return switcher.get(action)
def turn_right(action):
switcher = {
(-1, 0): (0, 1),
... | normal | {
"blob_id": "e1c68c7eb899718dd1c28dc6e95d5538c2b8ad74",
"index": 4510,
"step-1": "import copy\nimport math\nimport operator\n\nimport numpy as np, pprint\n\n\ndef turn_left(action):\n switcher = {\n (-1, 0): (0, -1),\n (0, 1): (-1, 0),\n (1, 0): (0, 1),\n (0, -1): (1, 0)\n\n }\n... | [
0
] |
# -*- snakemake -*-
#
# CENTIPEDE: Transcription factor footprinting and binding site prediction
# install.packages("CENTIPEDE", repos="http://R-Forge.R-project.org")
#
# http://centipede.uchicago.edu/
#
include: '../ngs.settings.smk'
config_default = {
'bio.ngs.motif.centipede' : {
'options' : '',
... | normal | {
"blob_id": "4620b52a43f2469ff0350d8ef6548de3a7fe1b55",
"index": 5019,
"step-1": "<mask token>\n",
"step-2": "include: '../ngs.settings.smk'\n<mask token>\nupdate_config(config_default, config)\n<mask token>\n",
"step-3": "include: '../ngs.settings.smk'\nconfig_default = {'bio.ngs.motif.centipede': {'options... | [
0,
1,
2,
3
] |
#配置我们文件所在目录的搜寻环境
import os,sys
#第一步先拿到当前文件的路径
file_path = os.path.abspath(__file__)
#第二步 根据这个路径去拿到这个文件所在目录的路径
dir_path = os.path.dirname(file_path)
#第三步:讲这个目录的路径添加到我们的搜寻环境当中
sys.path.append(dir_path)
#第四步,动态设置我们的setting文件
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gulishop.settings")
#第五步,让设置好的环境初始化生效
... | normal | {
"blob_id": "35ae9c86594b50bbe4a67d2cc6b20efc6f6fdc64",
"index": 295,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append(dir_path)\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gulishop.settings')\n<mask token>\ndjango.setup()\n<mask token>\nfor lev1 in row_data:\n cat1 = GoodsCategory... | [
0,
1,
2,
3,
4
] |
#coding=utf-8
from __future__ import division
import os
def judgeReported(evi, content):
for item in evi['reported']:
flag = content.find(item)
if flag > 0:
return 'Y'
for item in evi['properly']['neg']:
flag = content.find(item)
if flag > 0:
return... | normal | {
"blob_id": "064f535b7ea0f1e4a09bdf830021f17d175beda7",
"index": 4422,
"step-1": "#coding=utf-8\n\nfrom __future__ import division\nimport os\n \ndef judgeReported(evi, content):\n for item in evi['reported']:\n flag = content.find(item)\n if flag > 0:\n return 'Y'\n for item i... | [
0
] |
import os
import sys
sys.path.append("..")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import accuracy_score
import config
from mikasa.common import timer
fro... | normal | {
"blob_id": "23f0ba622097eb4065337ea77ea8104a610d6857",
"index": 6317,
"step-1": "<mask token>\n\n\ndef run_train(model_name, base_trainer, X, y):\n cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=config.SEED)\n trainer = RSACVTrainer(cv, base_trainer)\n trainer.fit(X=X, y=y, random_state=co... | [
3,
4,
5,
6,
7
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.