code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
# written by Mohammad Shahrad @UBC RECENT_NEWS_COUNT = 5 import json with open("./all-news.json") as f: allNews = json.load(f) recent_news_counter = 0 with open("./recent-news.js", "w") as f: f.write("document.write('\\\n") f.write("<ul>\\\n") for value in allNews.values(): f.write("<li>\\\n...
normal
{ "blob_id": "6097840cdf4b42efaca3e197f88703d927abe889", "index": 2548, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('./all-news.json') as f:\n allNews = json.load(f)\n<mask token>\nwith open('./recent-news.js', 'w') as f:\n f.write(\"document.write('\\\\\\n\")\n f.write('<ul>\\\\\\n'...
[ 0, 1, 2, 3, 4 ]
def read_int(): return int(input().strip()) def read_ints(): return list(map(int, input().strip().split(' '))) def solve(): K, S = read_ints() # X+Y+Z = S # 0 <= X,Y,Z <= K total = 0 for X in range(K+1): if S-X < 0: break # Y+Z=S-X Y_min = max(S-X-K,...
normal
{ "blob_id": "46b1fc975fbeedcafaa66c85c378e2249a495647", "index": 8827, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef read_ints():\n return list(map(int, input().strip().split(' ')))\n\n\ndef solve():\n K, S = read_ints()\n total = 0\n for X in range(K + 1):\n if S - X < 0:\n ...
[ 0, 2, 3, 4, 5 ]
from wagtail.tests.utils import WagtailPageTests from setup_guide.models import SetupGuideLandingPage, SetupGuidePage from home.models import HomePage class SetupGuideLandingPageTests(WagtailPageTests): def test_can_create_under_homepage(self): self.assertCanCreateAt(HomePage, SetupGuideLandingPage) ...
normal
{ "blob_id": "5fdcbccb99880da79eb0efbdecd328ca1cf73d7f", "index": 1415, "step-1": "<mask token>\n\n\nclass SetupGuideLandingPageTests(WagtailPageTests):\n <mask token>\n <mask token>\n\n\nclass SetupGuidePageTests(WagtailPageTests):\n\n def test_can_create_under_landing_page(self):\n self.assertCa...
[ 3, 4, 5, 6, 7 ]
"""Functions for updating and performing bulk inference using an Keras MPNN model""" from typing import List, Dict, Tuple import numpy as np import tensorflow as tf from molgym.mpnn.data import convert_nx_to_dict from molgym.mpnn.layers import custom_objects from molgym.utils.conversions import convert_smiles_to_nx ...
normal
{ "blob_id": "95ab8fce573ef959946d50d9af6e893cb8798917", "index": 6714, "step-1": "<mask token>\n\n\nclass MPNNMessage:\n \"\"\"Package for sending an MPNN model over pickle\"\"\"\n\n def __init__(self, model: tf.keras.Model):\n \"\"\"\n Args:\n model: Model to be sent\n \"\"...
[ 9, 11, 12, 13, 14 ]
import sys from arguments_parser import parse_args from open_ldap import OpenLdap from csv_parser import parse_csv, random_password from smtp_mail import SmtpServer def create_user(open_ldap, smtp, entries): """ If the 'ldap_insert' returns True, then the email will be send with the account info. """ ...
normal
{ "blob_id": "4f0a0089ad128edca3052da58a4c71f935592e25", "index": 4499, "step-1": "<mask token>\n\n\ndef create_user(open_ldap, smtp, entries):\n \"\"\"\n If the 'ldap_insert' returns True, then\n the email will be send with the account info.\n \"\"\"\n try:\n if open_ldap.ldap_insert(entrie...
[ 2, 3, 4, 5, 6 ]
# Generated by Django 3.0.3 on 2020-02-09 06:29 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('devices_collect', '0004_auto_20200209_1304'), ] operations = [ migrations.AlterField( ...
normal
{ "blob_id": "b07d042c61e9e6647822989444e72db2e01c64d0", "index": 5751, "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 = [('devices_col...
[ 0, 1, 2, 3, 4 ]
from basetest import simtest import testutil import logging, random from nitro_parts.lib.imager import ccm as CCM import numpy ############################################################################### class DotProductTest(simtest): def _set_coeff(self, c): cq = (c * 32).astype(numpy.uint8) ...
normal
{ "blob_id": "53110d6e7923cf65c514d54950a0be165582e9a0", "index": 4909, "step-1": "<mask token>\n\n\nclass DotProductTest(simtest):\n <mask token>\n <mask token>\n\n def _check(self, c, d):\n d = numpy.array(d)\n ds = d.copy()\n ds[d > 511] = d[d > 511] - 1024\n c = numpy.arra...
[ 3, 4, 5, 6, 7 ]
# -*- coding: utf-8 -*- """ Created on Thu Apr 4 12:47:30 2019 Title: MP4-Medical Image Processing @author: MP4 Team """ # Validate window controller class ValidateWindowCtr(object): # Initialization def __init__(self, fig, im_trans, im_truth, im_segmen, vol_trans, vol_truth, vol_segmen, ax_trans,...
normal
{ "blob_id": "e0b28fdcbc3160bcccbb032949317a91a32eeb1b", "index": 5394, "step-1": "<mask token>\n\n\nclass ValidateWindowCtr(object):\n\n def __init__(self, fig, im_trans, im_truth, im_segmen, vol_trans,\n vol_truth, vol_segmen, ax_trans, ax_truth, ax_segmen, index_trans,\n index_truth, index_seg...
[ 4, 5, 6, 7, 8 ]
# Generated by Django 3.0.2 on 2020-08-27 16:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('info', '0010_auto_20200808_2117'), ] operations = [ migrations.AddField( model_name='profile', name='annual_income',...
normal
{ "blob_id": "45b2b611a80b93c9a7d8ec8a09e5838147e1ea76", "index": 8626, "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 = [('info', '001...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 2 18:52:27 2021 @author: burak """ import veriler import gorsel import numpy as np from sklearn.neighbors import KNeighborsClassifier neighbors = np.arange(1,13) train_accuracy = np.empty(len(neighbors)) test_accuracy = np.empty(len(neighbors)) ...
normal
{ "blob_id": "133bd0b2affc3d29390edeab51299d294dafb709", "index": 4188, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor n, k in enumerate(neighbors):\n knn = KNeighborsClassifier(n_neighbors=k, metric='minkowski')\n knn.fit(veriler.X_train, veriler.y_train.ravel())\n train_accuracy[n] = knn.sc...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python #-*- coding : utf-8 -*- import string import keyword alphas = string.letters + '_' nums = string.digits keywords = keyword.kwlist checklst = alphas + nums print 'Welcome to the Identifier Checker v1.0' myInput = raw_input('Identifier to test? ') if myInput in keywords: print 'Okay as a keywor...
normal
{ "blob_id": "2420c835ff91c1269cb16fca2e60e191e1e8ce13", "index": 6457, "step-1": "#!/usr/bin/env python\n#-*- coding : utf-8 -*-\n\nimport string\nimport keyword\n\nalphas = string.letters + '_'\nnums = string.digits\nkeywords = keyword.kwlist\nchecklst = alphas + nums\n\nprint 'Welcome to the Identifier Checker...
[ 0 ]
T = int(input()) for cnt in range(1, T + 1): S = input() S_list = [] card = {'S': 13, 'D': 13, 'H': 13, 'C': 13} print('#' + str(cnt), end=' ') for i in range(0, len(S), 3): S_list.append(S[i:i + 3]) if len(set(S_list)) != len(S_list): print('ERROR') else: for i in S_...
normal
{ "blob_id": "45750152313fd3670867c61d0173e4cb11a806ba", "index": 4468, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor cnt in range(1, T + 1):\n S = input()\n S_list = []\n card = {'S': 13, 'D': 13, 'H': 13, 'C': 13}\n print('#' + str(cnt), end=' ')\n for i in range(0, len(S), 3):\n ...
[ 0, 1, 2 ]
import web import datetime # run with sudo to run on port 80 and use GPIO urls = ('/', 'index', '/survey', 'survey') render = web.template.render('templates/') class survey: def GET(self): return render.survey() class index: def GET(self): i = web.input(enter=None) ...
normal
{ "blob_id": "07a0ba3ded8a2d4a980cfb8e3dbd6fd491ea24b0", "index": 1842, "step-1": "<mask token>\n\n\nclass survey:\n <mask token>\n\n\nclass index:\n\n def GET(self):\n i = web.input(enter=None)\n date = datetime.datetime.now().ctime()\n hour = datetime.datetime.now().hour\n retu...
[ 3, 4, 5, 7, 8 ]
from twindb_backup.copy.binlog_copy import BinlogCopy from twindb_backup.status.binlog_status import BinlogStatus def test_get_latest_backup(raw_binlog_status): instance = BinlogStatus(raw_binlog_status) assert instance.get_latest_backup() == BinlogCopy(host='master1', name= 'mysqlbin005.bin', created...
normal
{ "blob_id": "0dc556336cee9e5f41c036c6fcf6da950216693c", "index": 5910, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_get_latest_backup(raw_binlog_status):\n instance = BinlogStatus(raw_binlog_status)\n assert instance.get_latest_backup() == BinlogCopy(host='master1', name=\n 'm...
[ 0, 1, 2 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-08-26 21:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exchange', '0004_auto_20170826_2120'), ] operations = [ migrations.AlterMod...
normal
{ "blob_id": "264896da4d92797b9f31e28c19a2e315efff815a", "index": 138, "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 = [('exchange', '...
[ 0, 1, 2, 3, 4 ]
from django import template from ..models import Article # 得到django 负责管理标签和过滤器的类 register = template.Library() @register.simple_tag def getlatestarticle(): latearticle = Article.objects.all().order_by("-atime") return latearticle
normal
{ "blob_id": "804c75b3ab0b115e5187d44e4d139cfb553269a9", "index": 6791, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@register.simple_tag\ndef getlatestarticle():\n latearticle = Article.objects.all().order_by('-atime')\n return latearticle\n", "step-3": "<mask token>\nregister = template.Li...
[ 0, 1, 2, 3, 4 ]
import pytest import problem22 as p22 def test_burst(): """Test burst() in Cluster""" print('\nTesting burst()') cluster = p22.Cluster('..#\n#..\n...') assert cluster.infected[p22.Position(0, 2)] == p22.State.Infected assert cluster.infected[p22.Position(1, 0)] == p22.State.Infected assert clus...
normal
{ "blob_id": "f0a3778e74d113a5de778fa17ec321c6680c56c2", "index": 1143, "step-1": "<mask token>\n\n\ndef test_burst_evolved():\n \"\"\"Test burst() in EvolvedCluster\"\"\"\n cluster = p22.EvolvedCluster('..#\\n#..\\n...')\n assert cluster.infected[p22.Position(0, 2)] == p22.State.Infected\n assert clu...
[ 4, 5, 6, 7, 8 ]
# a little more thing to be done. def eval_loop(): while True: s = input('Please input: ') if s != 'done': print(eval(s)) else: break eval_loop()
normal
{ "blob_id": "80969de6924ae5fe6bb8e7f1211e7aca28c63989", "index": 2615, "step-1": "<mask token>\n", "step-2": "def eval_loop():\n while True:\n s = input('Please input: ')\n if s != 'done':\n print(eval(s))\n else:\n break\n\n\n<mask token>\n", "step-3": "def eval...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- """ This is a simple sample for seuif.py License: this code is in the public domain Author: Cheng Maohua Email: cmh@seu.edu.cn Last modified: 2016.4.20 """ from seuif97 import * import matplotlib.pyplot as plt import numpy as np p1,t1 = 16, 535 p2,t2 = 3.56,315 h1 = pt2h(p1, t1) s1 = ...
normal
{ "blob_id": "ebe546794131eddea396bd6b82fbb41aeead4661", "index": 572, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.plot(point_p1_s, point_p1_h, 'bs-')\nplt.plot(point_p2_s, point_p2_h, 'bs-')\nplt.plot(point_is_s, point_is_h, 'ys-')\nplt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')\n...
[ 0, 1, 2, 3, 4 ]
""" COMPARISON OPERATORS """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' greaterThan = 10 > 5 # Is '10' greater than '5' ? Evaluates to True greaterThanOrEqualTo = 10 >= 10 # Is '10' greater than or equal to '10' # ? Evaluates to True lessThan = 5 < 10 # Is '5' les...
normal
{ "blob_id": "3b737aaa820da8f70a80480c6404e4d3a9d2262e", "index": 5602, "step-1": "<mask token>\n", "step-2": "<mask token>\n__author__ = 'Sol Amour - amoursol@gmail.com'\n__twitter__ = '@solamour'\n__version__ = '1.0.0'\ngreaterThan = 10 > 5\ngreaterThanOrEqualTo = 10 >= 10\nlessThan = 5 < 10\nlessThanOrEqualT...
[ 0, 1, 2 ]
''' Created on Dec 2, 2013 A reference entity implementation for Power devices that can be controlled via RF communication. @author: rycus ''' from entities import Entity, EntityType from entities import STATE_UNKNOWN, STATE_OFF, STATE_ON from entities import COMMAND_ON, COMMAND_OFF class GenericPower(Entity): ...
normal
{ "blob_id": "18e76df1693d4fc27620a0cf491c33197caa5d15", "index": 4055, "step-1": "<mask token>\n\n\nclass GenericPower(Entity):\n <mask token>\n\n def __init__(self, unique_id, entity_type=EntityType.find(100), name=\n 'Unnamed entity', state=STATE_UNKNOWN, state_value=None, last_checkin=0\n ...
[ 5, 6, 7, 8, 9 ]
#!/usr/bin/python import glob import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import seaborn as sns import os from pathlib import Path #import math #functions related to elasticity of WLC def f1(l,lp, kbt): return kbt/lp*(1./(4*(1.-l)*(1.-l))-.25+l) def derf1(l,lp,kbt): return k...
normal
{ "blob_id": "9817600759bc01e89f6c48bdc2d256651aedf74d", "index": 1788, "step-1": "<mask token>\n\n\ndef derf1(l, lp, kbt):\n return kbt / lp * (0.5 / ((1.0 - l) * (1.0 - l) * (1.0 - l)) + 1.0)\n\n\ndef xdefWLC(kbt, l, p, f):\n l0 = 0.9999\n lnew = l0 - (f1(l0, p, kbt) - f) / derf1(l0, p, kbt)\n if ab...
[ 4, 6, 7, 8, 9 ]
import keras from keras.applications import VGG16 from keras.preprocessing.image import ImageDataGenerator from keras.models import Model import matplotlib.pyplot as plt from keras.callbacks import History import numpy as np import os import cPickle as pickle import scipy from scipy import spatial def getM...
normal
{ "blob_id": "461b2de86907047df53c3857c6b0397e77de3fcd", "index": 5139, "step-1": "import keras\r\nfrom keras.applications import VGG16\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import Model\r\nimport matplotlib.pyplot as plt\r\nfrom keras.callbacks import History\r\nimport ...
[ 0 ]
import re with open('input.txt') as f: input_file = f.readlines() input_file = [x.strip() for x in input_file] def check_passport(text): arr = text.split() dct = {} for elem in arr: key = elem.split(":")[0] val = elem.split(":")[1] dct[key] = val try: if len(dc...
normal
{ "blob_id": "166329c967e83806e3482179a56ac7e5541d5010", "index": 1589, "step-1": "<mask token>\n\n\ndef check_passport(text):\n arr = text.split()\n dct = {}\n for elem in arr:\n key = elem.split(':')[0]\n val = elem.split(':')[1]\n dct[key] = val\n try:\n if len(dct['byr'...
[ 1, 2, 3, 4, 5 ]
import time import os import random def generate_sequence(difficulty): print("Try to remember the numbers! : ") random_list = random.sample(range(1, 101), difficulty) time.sleep(2) print(random_list) time.sleep(0.7) os.system('cls') time.sleep(3) return random_list def get_list_from_...
normal
{ "blob_id": "bff9fb50f1901094c9ab3d61566509835c774f21", "index": 6776, "step-1": "<mask token>\n\n\ndef is_list_equal(a, b):\n if a == b:\n print('CORRECT answer! :) ')\n time.sleep(2)\n print('See you next time !')\n time.sleep(3)\n return True\n else:\n print('Th...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- """ Created on Mon Jul 8 11:51:49 2019 @author: Christian Post """ # TODO: row index as an attribute of Data? # make iterrows return a row object to access column names for each row import csv import os import datetime def euro(number): return f'{number:.2f} €'.replace(...
normal
{ "blob_id": "8db952ba5bf42443da89f4064caf012036471541", "index": 2307, "step-1": "<mask token>\n\n\ndef euro(number):\n return f'{number:.2f} €'.replace('.', ',')\n\n\n<mask token>\n\n\nclass Data:\n\n def __init__(self, data=None, columns=[]):\n self.data = {}\n self.columns = columns\n ...
[ 8, 10, 11, 12, 13 ]
""" Python asyncio Protocol extension for TCP use. """ import asyncio import logging import socket class TcpTestProtocol(asyncio.Protocol): """ Extension of asyncio protocol for TCP data """ def __init__(self, test_stream=None, no_delay=False, window=None, server=None): """ Initialize ...
normal
{ "blob_id": "9f0e286268732e8cabb028b7c84f5ba72a6e8528", "index": 3068, "step-1": "<mask token>\n\n\nclass TcpTestProtocol(asyncio.Protocol):\n <mask token>\n <mask token>\n\n @property\n def socket_id(self):\n \"\"\"Return socket id\"\"\"\n return self._sock_id\n\n def set_owner(self...
[ 9, 11, 12, 13, 15 ]
#write a program that displays the wor "Hello!" print("Hello!")
normal
{ "blob_id": "b7a7941b3555b30ac7e743a5457df76f9eb7cb15", "index": 9714, "step-1": "<mask token>\n", "step-2": "print('Hello!')\n", "step-3": "#write a program that displays the wor \"Hello!\"\n\nprint(\"Hello!\")\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# Author: Andreas Francois Vermeulen print("CrawlerSlaveYoke") print("CSY-000000023.py")
normal
{ "blob_id": "322795bce189428823c45a26477555052c7d5022", "index": 8933, "step-1": "<mask token>\n", "step-2": "print('CrawlerSlaveYoke')\nprint('CSY-000000023.py')\n", "step-3": "# Author: Andreas Francois Vermeulen\nprint(\"CrawlerSlaveYoke\")\nprint(\"CSY-000000023.py\")\n", "step-4": null, "step-5": nu...
[ 0, 1, 2 ]
# Given two binary trees, write a function to check if they are equal or not. # # Two binary trees are considered equal if they are structurally identical and the nodes have the same value. # # Return 0 / 1 ( 0 for false, 1 for true ) for this problem # # Example : # # Input : # # 1 1 # / \ / \ # 2 3 ...
normal
{ "blob_id": "4a0eca90de3ce7fb0ab6decb0ec6aadb32c1a9fa", "index": 601, "step-1": "<mask token>\n\n\nclass Solution:\n\n def solution(self, rootA, rootB):\n if rootA == rootB:\n print('h')\n return True\n if rootA is None or rootB is None:\n return False\n r...
[ 2, 3, 4, 5, 6 ]
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time n=int(input("Enter the number of votes : ")) print() p...
normal
{ "blob_id": "0e2b4e8e8c5a728e5123dfa704007b0f6adaf1e1", "index": 4561, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint()\n<mask token>\ndriver.get('https://strawpoll.com/jhzd6qwjw')\nfor i in range(0, n + 1):\n driver.delete_all_cookies()\n try:\n button = WebDriverWait(driver, 10).unti...
[ 0, 1, 2, 3, 4 ]
import os from flask import Flask # from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy # from flask_bcrypt import Bcrypt from flask_wtf.csrf import CSRFProtect app = Flask(__name__) csrf = CSRFProtect(app) # bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = 'v\xf9\xf7\x11\x13\x18\xfaMYp\xed_\x...
normal
{ "blob_id": "24c9b562411a63f0d3f2ee509bb60dafe7fbecd1", "index": 373, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.config.from_object(__name__)\n<mask token>\n", "step-3": "<mask token>\napp = Flask(__name__)\ncsrf = CSRFProtect(app)\napp.config['SECRET_KEY'] = 'vù÷\\x11\\x13\\x18úMYpí_èÉw\\x06\\...
[ 0, 1, 2, 3, 4 ]
# # PySNMP MIB module SYSLOG-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYSLOG-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:31:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
normal
{ "blob_id": "46cdea08cab620ea099ad7fa200782717249b91b", "index": 6741, "step-1": "<mask token>\n\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleVal...
[ 2, 4, 5, 6, 7 ]
''' Generate a ten-character alphanumeric password with at least one lowercase, at least one uppercase character, and at least three digits ''' import secrets import string alphabets = string.ascii_letters + string.digits while True: password = "".join(secrets.choice(alphabets) for i in range(10)) if(a...
normal
{ "blob_id": "0c283cd31203291da24226a0eae781bd397e84d4", "index": 9526, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n password = ''.join(secrets.choice(alphabets) for i in range(10))\n if any(c.islower() for c in password) and any(c.isupper() for c in password\n ) and sum(c.isd...
[ 0, 1, 2, 3, 4 ]
from rest_framework import serializers from books.models import Genres, Format, Book, Review, ExtraTableForPrice class GenresSerializer(serializers.ModelSerializer): class Meta: model = Genres fields = ('title', ) class PriceSerializer(serializers.ModelSerializer): class Meta: model...
normal
{ "blob_id": "9c50a3abd353d5ba619eaa217dcc07ab76fb850c", "index": 2519, "step-1": "<mask token>\n\n\nclass BookSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Book\n fields = '__all__'\n\n def create(self, validated_data):\n formats = validated_data.pop('format', []...
[ 9, 11, 12, 13, 14 ]
from time import sleep import requests import json import pymysql db = pymysql.connect(host="localhost", user="root", password="root", db="xshop", port=33061) def getCursor(): cursor = db.cursor() return cursor class Classify(object): def __init__(self, **args): self.cl_name = args['cl_name'] ...
normal
{ "blob_id": "6d51a088ba81cfc64c2e2a03f98b0ee354eda654", "index": 4292, "step-1": "<mask token>\n\n\ndef getCursor():\n cursor = db.cursor()\n return cursor\n\n\nclass Classify(object):\n\n def __init__(self, **args):\n self.cl_name = args['cl_name']\n self.cl_grade = args['cl_grade'] is No...
[ 7, 8, 9, 10, 12 ]
from flask import Flask, jsonify, request, render_template from werkzeug import secure_filename import os from utils import allowed_file, convert_html_to_pdf, convert_doc_to_pdf app = Flask(__name__) @app.route('/', methods=['GET']) def index(): """ Renders Index.html """ try: return render_template...
normal
{ "blob_id": "860f77b031c815df40a16669dae8d32af4afa5bf", "index": 868, "step-1": "<mask token>\n\n\n@app.route('/', methods=['GET'])\ndef index():\n \"\"\" Renders Index.html \"\"\"\n try:\n return render_template('index.html')\n except Exception as e:\n print('Exception Occurred', e)\n ...
[ 2, 3, 4, 5, 6 ]
import random import numpy as np import matplotlib.pyplot as plt import torchvision def plot_image(img, ax, title): ax.imshow(np.transpose(img, (1,2,0)) , interpolation='nearest') ax.set_title(title, fontsize=20) def to_numpy(image, vsc): return torchvision.utils.make_grid( image.view(1, vsc.c...
normal
{ "blob_id": "ae27f97b5633309d85b9492e1a0f268847c24cd5", "index": 9366, "step-1": "<mask token>\n\n\ndef plot_image(img, ax, title):\n ax.imshow(np.transpose(img, (1, 2, 0)), interpolation='nearest')\n ax.set_title(title, fontsize=20)\n\n\n<mask token>\n\n\ndef plot_encoding(image, vsc, latent_sz, alpha=Non...
[ 3, 4, 5, 6, 7 ]
from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path from external_api import views urlpatterns = [path('darksky/', views.DarkSkyView.as_view())] urlpatterns = format_suffix_patterns(urlpatterns)
normal
{ "blob_id": "e40f0a25d0c02f36c254e630133dc1fb11f29d4d", "index": 8156, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('darksky/', views.DarkSkyView.as_view())]\nurlpatterns = format_suffix_patterns(urlpatterns)\n", "step-3": "from rest_framework.urlpatterns import format_suffix_patt...
[ 0, 1, 2 ]
import PyPDF2 from pathlib import Path def get_filenames(): """ Get PDF files not yet reordered in the current directory :return: list of PDF file names """ filenames = [] for filename in Path('.').glob('*.pdf'): if 'reordered' not in filename.stem: filenames.append(filenam...
normal
{ "blob_id": "2b3a42fed98b43cdd78edd751b306ba25328061a", "index": 8652, "step-1": "<mask token>\n\n\ndef appendix_and_index_pages():\n \"\"\"\n Prompt user to input appendix pages (if one exists) and index pages\n :return: start and end pages of the appendix and index\n \"\"\"\n\n def index_pages()...
[ 2, 5, 7, 8, 9 ]
import os.path import bcolz import numpy as np import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") if not os.path.exists('db'): print("db not found, creating") ct = bcolz.ctable([np.empty(0, dtype="i8")], names=['data'], ...
normal
{ "blob_id": "71ac7240287b83be6ec1f2d98e3ee531a8a219e0", "index": 9879, "step-1": "<mask token>\n", "step-2": "<mask token>\nsocket.bind('tcp://*:5555')\nif not os.path.exists('db'):\n print('db not found, creating')\n ct = bcolz.ctable([np.empty(0, dtype='i8')], names=['data'], rootdir='db')\nelse:\n ...
[ 0, 1, 2, 3, 4 ]
def check_orthogonal(u, v): return u.dot(v) == 0 def check_p(): import inspect import re local_vars = inspect.currentframe().f_back.f_locals return len(re.findall("p\\s*=\\s*0", str(local_vars))) == 0
normal
{ "blob_id": "36e538ca7fbdbf6e2e6ca1ae126e4e75940bb5cd", "index": 4316, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef check_p():\n import inspect\n import re\n local_vars = inspect.currentframe().f_back.f_locals\n return len(re.findall('p\\\\s*=\\\\s*0', str(local_vars))) == 0\n", "...
[ 0, 1, 2, 3 ]
from django.urls import path, re_path from .views import * app_name = 'articles' urlpatterns = [ path('',articles_list,name='list'), path('create', create_article, name='create'), path('<slug:slug>', article_detail,name='detail'), ]
normal
{ "blob_id": "1c222f42c5c0178f97391f1bdc60bba110f3d118", "index": 9866, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_name = 'articles'\nurlpatterns = [path('', articles_list, name='list'), path('create',\n create_article, name='create'), path('<slug:slug>', article_detail,\n name='detail')]\n"...
[ 0, 1, 2, 3 ]
from __future__ import absolute_import from talin.quotations import register_xpath_extensions def init(): register_xpath_extensions()
normal
{ "blob_id": "c218428908c28a8c65bd72e66dcddaf7db1909d7", "index": 4325, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef init():\n register_xpath_extensions()\n", "step-3": "from __future__ import absolute_import\nfrom talin.quotations import register_xpath_extensions\n\n\ndef init():\n regi...
[ 0, 1, 2 ]
import numpy import multiprocessing from functools import partial from textutil.text import read_file from textutil.util import B import mmap import tqdm class Growable(object): def __init__(self, capacity=1024, dtype=numpy.uint32, grow=2): self.grow = grow self.capacity=capacity self.dty...
normal
{ "blob_id": "8a2fe83ab1adae7de94eb168290ce4843ab39fe1", "index": 9476, "step-1": "<mask token>\n\n\nclass Growable(object):\n\n def __init__(self, capacity=1024, dtype=numpy.uint32, grow=2):\n self.grow = grow\n self.capacity = capacity\n self.dtype = dtype\n self.arr = numpy.empty...
[ 5, 6, 7, 9, 10 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages config = { 'name': 'beziers', 'author': 'Simon Cozens', 'author_email': 'simon@simon-cozens.org', 'url': 'https://github.com/simoncozens/beziers.py', 'description': 'Bezier curve manipulation library', 'lo...
normal
{ "blob_id": "98ddf0be2c38cd9b10dfa9cc09f53907b34c1287", "index": 7728, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n setup(**config)\n", "step-3": "<mask token>\nconfig = {'name': 'beziers', 'author': 'Simon Cozens', 'author_email':\n 'simon@simon-cozens.org', 'url':...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindo...
normal
{ "blob_id": "2d503c93160b6f44fba2495f0ae0cf9ba0eaf9d6", "index": 8930, "step-1": "<mask token>\n\n\nclass Ui_MainWindow(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Ui_MainWindow(object):\n <mask token>\n\n def retranslateUi(self, MainWindow):\n _translate = ...
[ 1, 2, 3, 4, 5 ]
s = input() ans = 0 t = 0 for c in s: if c == "R": t += 1 else: ans = max(ans, t) t = 0 ans = max(ans, t) print(ans)
normal
{ "blob_id": "85c97dfeb766f127fa51067e5155b2da3a88e3be", "index": 4811, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor c in s:\n if c == 'R':\n t += 1\n else:\n ans = max(ans, t)\n t = 0\n<mask token>\nprint(ans)\n", "step-3": "s = input()\nans = 0\nt = 0\nfor c in s:\n ...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python3 """ brightness an image""" import tensorflow as tf def change_brightness(image, max_delta): """brightness an image""" img = tf.image.adjust_brightness(image, max_delta) return img
normal
{ "blob_id": "07e068dbc1ba1bcb85121ee49f2f9337cae188ba", "index": 9388, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef change_brightness(image, max_delta):\n \"\"\"brightness an image\"\"\"\n img = tf.image.adjust_brightness(image, max_delta)\n return img\n", "step-3": "<mask token>\nim...
[ 0, 1, 2, 3 ]
# Problem statement here: https://code.google.com/codejam/contest/975485/dashboard#s=p0 # set state of both bots # for instruction i # look at this instruction to see who needs to press their button now # add walk time + 1 to total time # decriment walk time of other bot by walk time +1 of current bot (rectif...
normal
{ "blob_id": "d1944493b7f3e74462ca0163a8c0907e4976da06", "index": 4806, "step-1": "<mask token>\n\n\ndef other_bot(bot_name):\n if bot_name == 'O':\n return 'B'\n else:\n return 'O'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef solve_sequence(seq):\n O_init_walk_time = 0\n B_i...
[ 1, 3, 4, 5, 6 ]
import helpers import os import os.path import json import imp import source.freesprints from pygame.locals import * class PluginLoader: available_plugins = None def __init__(self): self.checkAvailablePlugins() def checkAvailablePlugins(self): print helpers.pluginsPath() ...
normal
{ "blob_id": "639669174435492f43bf51680c2724863017e9d2", "index": 527, "step-1": "import helpers\nimport os\nimport os.path\nimport json\nimport imp\nimport source.freesprints\nfrom pygame.locals import *\n\nclass PluginLoader:\n available_plugins = None\n \n def __init__(self):\n self.checkAvaila...
[ 0 ]
from django.urls import path from main.views import IndexView, BuiltinsView, CustomView app_name = 'main' urlpatterns = [path('', IndexView.as_view(), name='index'), path( 'builtins/', BuiltinsView.as_view(), name='builtins'), path('custom/', CustomView.as_view(), name='custom')]
normal
{ "blob_id": "7b527f9ec66ddf35f3395d78c857c021975402c7", "index": 5141, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_name = 'main'\nurlpatterns = [path('', IndexView.as_view(), name='index'), path(\n 'builtins/', BuiltinsView.as_view(), name='builtins'), path('custom/',\n CustomView.as_view(),...
[ 0, 1, 2 ]
"""empty message Revision ID: 3e4ee9eaaeaa Revises: 6d58871d74a0 Create Date: 2016-07-25 15:30:38.008238 """ # revision identifiers, used by Alembic. revision = '3e4ee9eaaeaa' down_revision = '6d58871d74a0' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
normal
{ "blob_id": "db49313d2bc8b9f0be0dfd48c6065ea0ab3294cb", "index": 4032, "step-1": "<mask token>\n\n\ndef downgrade():\n op.drop_index(op.f('ix_account_sub_int'), table_name='account')\n op.drop_index(op.f('ix_account_mac'), table_name='account')\n op.drop_index(op.f('ix_account_interface'), table_name='a...
[ 1, 2, 3, 4, 5 ]
import argparse import datetime import json import os import sys import hail as hl from .utils import run_all, run_pattern, run_list, RunConfig from .. import init_logging def main(args): init_logging() records = [] def handler(stats): records.append(stats) data_dir = args.data_dir or os....
normal
{ "blob_id": "d4625dd743dd6648044e40b02743ae80f4caea36", "index": 9572, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main(args):\n init_logging()\n records = []\n\n def handler(stats):\n records.append(stats)\n data_dir = args.data_dir or os.environ.get('HAIL_BENCHMARK_DIR'\n ...
[ 0, 1, 2, 3, 4 ]
# encoding: utf-8 from SpiderTools.tool import platform_system from SpidersLog.file_handler import SafeFileHandler from Env.parse_yaml import FileConfigParser from Env import log_variable as lv from staticparm import root_path from SpiderTools.tool import get_username import logging import logging.handlers import trace...
normal
{ "blob_id": "63001128d9cb934d6f9d57db668a43ba58f4ece3", "index": 1679, "step-1": "<mask token>\n\n\nclass ICrawlerLog:\n <mask token>\n\n def __init__(self, name, logger=None):\n self.logger = logger\n self.name = name\n\n @property\n def save(self, *args, **kwargs):\n \"\"\"\n ...
[ 3, 4, 5, 6, 7 ]
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): # Positional arguments parser.add_argument('poll_id', nargs='+', type=int) # Named (optional arguments) ...
normal
{ "blob_id": "b2d5b16c287dc76a088f6e20eca4a16dd0aad00f", "index": 8797, "step-1": "<mask token>\n\n\nclass Command(BaseCommand):\n <mask token>\n <mask token>\n\n def handle(self, *args, **options):\n s = ''\n result = 0\n tag = sum([options[i] for i in ['add', 'substract', 'multiply...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- """ Copyright (C) 2015, MuChu Hsu Contributed by Muchu Hsu (muchu1983@gmail.com) This file is part of BSD license <https://opensource.org/licenses/BSD-3-Clause> """ import unittest import logging from cameo.spiderForCROWDCUBE import SpiderForCROWDCUBE """ 測試 抓取 CROWDCUBE """ class SpiderForCRO...
normal
{ "blob_id": "45856b4c5cbf1d3b414ad769135b2d974bc0a22b", "index": 7120, "step-1": "<mask token>\n\n\nclass SpiderForCROWDCUBETest(unittest.TestCase):\n\n def setUp(self):\n logging.basicConfig(level=logging.INFO)\n self.spider = SpiderForCROWDCUBE()\n self.spider.initDriver()\n <mask to...
[ 3, 4, 6, 7, 8 ]
""" Benchmark module: can also compare multiple functions """ import gc from inspect import ( signature, getsourcelines ) from operator import itemgetter from time import perf_counter from SpeedIT.ProjectErr import Err from SpeedIT.Utils import ( format_time, get_table_rst_formatted_lines ) def _helper_...
normal
{ "blob_id": "b2d3ebe4b1ce8f6f0fde8495fb90542080b810ce", "index": 1390, "step-1": "<mask token>\n\n\nclass _TimeIT(object):\n <mask token>\n\n def __init__(self, func, args_list, kwargs_dict, setup_line_list,\n check_too_fast, run_sec, name, perf_counter_reference_time):\n \"\"\" Constructor. ...
[ 4, 6, 7, 8, 9 ]
import json from aioredis import Redis from aiologger.loggers.json import ExtendedLogRecord from aiologger.handlers.base import Handler from app.core import config class RedisHandler(Handler): def __init__( self, redis_client, key=f"{config.APP_NAME}-log", *args, **kwargs...
normal
{ "blob_id": "fe581ca8176fed01309f0d852f72564863aa0895", "index": 8413, "step-1": "<mask token>\n\n\nclass RedisHandler(Handler):\n <mask token>\n <mask token>\n\n async def emit(self, record: ExtendedLogRecord) ->None:\n await self.redis_client.rpush(self.key, self.format(record))\n\n async de...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/env python # https://github.com/git/git/blob/master/Documentation/githooks.txt#L181 # This hook is called by 'git push' and can be used to prevent a push from taking # place. The hook is called with two parameters which provide the name and # location of the destination remote, if a named remote is not bei...
normal
{ "blob_id": "eabc81cacacc40d55234b60927b17069980a08f8", "index": 7245, "step-1": "<mask token>\n", "step-2": "<mask token>\nsys.argv.extend(sys.stdin.read().split())\n<mask token>\nif len(sys.argv) > 3:\n local_ref = sys.argv[3]\n local_sha1 = sys.argv[4]\n remote_ref = sys.argv[5]\n remote_sha1 = ...
[ 0, 1, 2, 3, 4 ]
############################################################### # Yolanda Gunter # Lab 4 # My program uses decisions, repetition, functions, files, lists # and exception handling that will get the input from a file to # run program that asks User for current date, reads a contact file # list that contains...
normal
{ "blob_id": "661f94f5770df1026352ee344d0006466662bb3c", "index": 2537, "step-1": "def main():\n try:\n contacts = open('contactsLab4.txt', 'r')\n names = []\n birthdates = []\n name = contacts.readline()\n while name != '':\n names.append(name.rstrip('\\n'))\n ...
[ 2, 3, 4, 6, 7 ]
""" ___________________________________________________ | _____ _____ _ _ _ | | | __ \ | __ (_) | | | | | | |__) |__ _ __ __ _ _ _| |__) || | ___ | |_ | | | ___/ _ \ '_ \ / _` | | | | ___/ | |/ _ \| __| | | | | | __/ | | | (_| | |_| | | | | |...
normal
{ "blob_id": "81f49c55edff7678e9d1745e39a8370e2c31c9ea", "index": 8850, "step-1": "\"\"\"\n ___________________________________________________\n | _____ _____ _ _ _ |\n | | __ \\ | __ (_) | | | |\n | | |__) |__ _ __ __ _ _ _| |__) || | ___ | |_ |\...
[ 0 ]
import json import nltk with open('posts.json', 'r') as infile: posts = [] for line in infile: posts.append(json.loads(line[0:len(line)-2])) for post in posts: print '\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
normal
{ "blob_id": "2f15814d97708e33585ea6b45e89b5a5e69d82fe", "index": 5694, "step-1": "import json\nimport nltk\n\nwith open('posts.json', 'r') as infile:\n\tposts = []\n\tfor line in infile:\n\t\tposts.append(json.loads(line[0:len(line)-2]))\n\nfor post in posts:\n print '\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
[ 0 ]
import logging import terrestrial.config as config logger = logging.getLogger(f'{__name__}.common') def health(): return 'OK', 200 def verify_token(token): """ Verifies Token from Authorization header """ if config.API_TOKEN is None: logger.error('API token is not configured, auth will f...
normal
{ "blob_id": "167bd2c405171443c11fbd13575f8c7b20877289", "index": 8470, "step-1": "<mask token>\n\n\ndef health():\n return 'OK', 200\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef health():\n return 'OK', 200\n\n\ndef verify_token(token):\n \"\"\"\n Verifies Token from Authorization header\...
[ 1, 2, 3, 4 ]
# fabric이 실행할 대상을 제어. from fabric.api import * AWS_EC2_01 = 'ec2-52-78-143-155.ap-northeast-2.compute.amazonaws.com' # Running PROJECT_DIR = '/var/www/kamper' APP_DIR = '%s/app' % PROJECT_DIR """ # the user to use for the remote commands env.user = 'appuser' # the servers where the commands are executed env.ho...
normal
{ "blob_id": "98db990f406cc6815480cca33011c8b0b2ad67c7", "index": 2343, "step-1": "<mask token>\n\n\ndef deploy():\n print('deploying')\n pass\n", "step-2": "<mask token>\n\n\ndef pack():\n local('git checkout')\n local('git commit -a -s -m \"Fabric Pack Commit\"')\n\n\ndef deploy():\n print('dep...
[ 1, 2, 3, 4, 5 ]
input = """ t(Z) :- t0(Z). t(Z) :- g(X,Y,Z), t(X), not t(Y). t0(2). g(5,1,3). g(1,2,4). g(3,4,5). """ output = """ t(Z) :- t0(Z). t(Z) :- g(X,Y,Z), t(X), not t(Y). t0(2). g(5,1,3). g(1,2,4). g(3,4,5). """
normal
{ "blob_id": "df5c79c79d827b6b3de7ceb4b1e3c652c8956346", "index": 2620, "step-1": "<mask token>\n", "step-2": "input = \"\"\"\nt(Z) :- t0(Z).\nt(Z) :- g(X,Y,Z), t(X), not t(Y).\n\nt0(2).\ng(5,1,3).\ng(1,2,4).\ng(3,4,5).\n\n\"\"\"\noutput = \"\"\"\nt(Z) :- t0(Z).\nt(Z) :- g(X,Y,Z), t(X), not t(Y).\n\nt0(2).\ng(5...
[ 0, 1 ]
# -*- coding: utf-8 -*- """MicroPython rotary encoder library.""" from machine import Pin ENC_STATES = (0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0) class Encoder(object): def __init__(self, pin_x='P4', pin_y='P5', pin_mode=Pin.PULL_UP, scale=1, min=0, max=100, reverse=False): s...
normal
{ "blob_id": "1406b2ab78b52823a8f455c8e2719f6bd84bd168", "index": 822, "step-1": "<mask token>\n\n\nclass Encoder(object):\n\n def __init__(self, pin_x='P4', pin_y='P5', pin_mode=Pin.PULL_UP, scale=\n 1, min=0, max=100, reverse=False):\n self.pin_x = pin_x if isinstance(pin_x, Pin) else Pin(pin_x...
[ 7, 9, 10, 11, 12 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import torch from torch import nn, autograd import config import time import copy import progressbar as pb from dataset import TrainDataSet from model import BiAffineSrlModel from fscore import FScore config.add_option('-m', '--mode', dest='mode', default='train...
normal
{ "blob_id": "038ccba05113fb7f2f589eaa7345df53cb59a5af", "index": 18, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef train(num_epochs=30):\n lossfunction = nn.CrossEntropyLoss()\n trainset = TrainDataSet()\n model = BiAffineSrlModel(vocabs=trainset.vocabs)\n optimizer = torch.optim.Ada...
[ 0, 1, 2, 3, 4 ]
from __future__ import division import numpy as np import matplotlib.pyplot as plt #import matplotlib.cbook as cbook import Image from matplotlib import _png from matplotlib.offsetbox import OffsetImage import scipy.io import pylab #for question 1 (my data) def resample(ms,srate): return int(round(ms/1000*srate)) de...
normal
{ "blob_id": "a81ee0a855c8a731bafe4967b776e3f93ef78c2a", "index": 8908, "step-1": "from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import matplotlib.cbook as cbook\nimport Image\nfrom matplotlib import _png\nfrom matplotlib.offsetbox import OffsetImage\nimport scipy.io\nimpo...
[ 0 ]
#crfで英文に固有表現認識(タグ付け)をする #usr/bin/python3 #coding:utf-8 from itertools import chain from sklearn.metrics import classification_report, confusion_matrix from sklearn.preprocessing import LabelBinarizer import sklearn import pycrfsuite from sklearn import cross_validation import sys import os import math import random d...
normal
{ "blob_id": "af9b83b6e213359f5e193918b6c09c22220e5457", "index": 607, "step-1": "<mask token>\n\n\ndef word2features(sent, i):\n word = sent[i][0]\n tag = sent[i][1]\n features = ['bias', 'word.lower=' + word.lower(), 'word[-3:]=' + word[-\n 3:], 'word[-2:]=' + word[-2:], 'word.isupper=%s' % word...
[ 4, 5, 7, 8, 9 ]
import unittest from unflatten import _path_tuples_with_values_to_dict_tree, dot_colon_join, dot_colon_split from unflatten import _recognize_lists from unflatten import _tree_to_path_tuples_with_values from unflatten import brackets_join from unflatten import flatten from unflatten import unflatten class BracketsRe...
normal
{ "blob_id": "5119b1b6817e002c870b4d6a19fe9aee661fff7e", "index": 8425, "step-1": "<mask token>\n\n\nclass RecognizeListsTestCase(unittest.TestCase):\n\n def test_simple(self):\n self.assertListEqual(_recognize_lists({(0): 'a', (1): {'b': -1, 'c':\n {(0): 'd', (1): -2}}}), ['a', {'b': -1, 'c'...
[ 13, 17, 20, 21, 22 ]
############################################-############################################ ################################ F I L E A U T H O R S ################################ # MIKE - see contacts in _doc_PACKAGE_DESCRIPTION ####################################### A B O U T #######################################...
normal
{ "blob_id": "58667da8898c2277ecc3d9d738d6553dd3416436", "index": 7323, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef some_func():\n CFG.start_clock_module = datetime.datetime.now()\n LOG.write_me('\\tSTART - CLEAN.py (' + datetime.datetime.now().strftime(\n '%y-%m-%d | %H:%M') + ')'...
[ 0, 1, 2, 3, 4 ]
from typing import * class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cells = {} for i in range(9): for j in range(9): if board[i][j] != ".": val = board[i][j] # is unique in r...
normal
{ "blob_id": "57c911c9a10f9d116f1b7099c5202377e16050f1", "index": 7871, "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 isValidSudoku(self, board: List[List[str]]) ->bool:\n cells = {}\n for i ...
[ 0, 1, 2, 3, 4 ]
#!python import pdb import argparse import os import re import sys import string from utilpack import path from subprocess import Popen from subprocess import PIPE def popen(cmd): spl = cmd.split() return Popen(spl, stdout=PIPE).communicate()[0] def debug (s): s dists = 0 def get_setup_ini (setup_in...
normal
{ "blob_id": "e3b8bec0cc7df217052a3182f9a862f0e3622afd", "index": 5318, "step-1": "#!python\nimport pdb\nimport argparse\nimport os\nimport re\nimport sys\nimport string\nfrom utilpack import path\nfrom subprocess import Popen\nfrom subprocess import PIPE\n\n\ndef popen(cmd):\n spl = cmd.split()\n return Po...
[ 0 ]
############################################################### ## File Name: 11_exercise.py ## File Type: Python File ## Author: surge55 ## Course: Python 4 Everybody ## Chapter: Chapter 11 - Regular Expressions ## Excercise: n/a ## Description: Code walkthrough from book ## Other References: associated files...
normal
{ "blob_id": "860908126d473e6c4ed070992a1b518683fd4c27", "index": 3275, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor line in hand:\n line = line.rstrip()\n x = re.findall('([0-9]+)', line)\n if len(x) > 0:\n for i in x:\n total += float(i)\nprint('sum is', int(total))\n", ...
[ 0, 1, 2, 3, 4 ]
""" Type data Dictionary hanya sekedar menghubungkan KEY dan VALUE KVP = KEY VALUE PAIR """ kamus = {} kamus['anak'] = 'son' kamus['istri'] = 'wife' kamus['ayah'] = 'father' print(kamus) print(kamus['ayah']) print('\nData ini dikirimkan server gojek, memberikan info driver di sekitar pemakai aplikasi') data_server_g...
normal
{ "blob_id": "67b101df690bbe9629db2cabf0060c0f2aad9722", "index": 2389, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(kamus)\nprint(kamus['ayah'])\nprint(\n \"\"\"\nData ini dikirimkan server gojek, memberikan info driver di sekitar pemakai aplikasi\"\"\"\n )\n<mask token>\nprint(data_server_...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import json import urllib2 # Es importante agregar la variable de ambiente: # export PYTHONIOENCODING='UTF-8' # para redireccionar la salida std a un archivo. def call(url): try: request = urllib2.Request(url) response = urllib2.urlopen(req...
normal
{ "blob_id": "c81fde7fb5d63233c633b8e5353fe04477fef2af", "index": 4770, "step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport json\nimport urllib2\n\n# Es importante agregar la variable de ambiente:\n# export PYTHONIOENCODING='UTF-8'\n# para redireccionar la salida std a un archivo.\n\nd...
[ 0 ]
from flask_minify.utils import get_optimized_hashing class MemoryCache: def __init__(self, store_key_getter=None, limit=0): self.store_key_getter = store_key_getter self.limit = limit self._cache = {} self.hashing = get_optimized_hashing() @property def store(self): ...
normal
{ "blob_id": "ef5c51a5c706387b62ef3f40c7cadf7dbef6d082", "index": 8671, "step-1": "<mask token>\n\n\nclass MemoryCache:\n\n def __init__(self, store_key_getter=None, limit=0):\n self.store_key_getter = store_key_getter\n self.limit = limit\n self._cache = {}\n self.hashing = get_opt...
[ 6, 7, 8, 9, 10 ]
#!/usr/bin/env python """ Power calculation based for admixture mapping. @ref: Design and Analysis of admixture mapping studies, (2004). @Author: wavefancy@gmail.com Usage: PowerCalculation.py -r aratio -n nhap PowerCalculation.py -h | --help | -v | --version | -f | --format Not...
normal
{ "blob_id": "7f9046582ff03d1c72d191a8f78c911cbc8a0650", "index": 5907, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef ShowFormat():\n \"\"\"File format example\"\"\"\n print(\n \"\"\"\n #rfmix output, 3 person, 2 snps\n ------------------------\n1 1 2 1 2 2\n1 2 2 1 2 2\n\n ...
[ 0, 1, 2, 3, 4 ]
import sys sys.path.append('preprocess') import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt from matplotlib.pyplot import savefig import numpy as np import refit_cfg import os import random from sklearn.model_selection import train_test_split name = ['WashingMachine', 'Kettle', 'Microwave', 'Fr...
normal
{ "blob_id": "30405a6f20a44b2252b6894ef6d0e818861702f8", "index": 9857, "step-1": "<mask token>\n\n\ndef align_process(house_id):\n data = np.load('data\\\\REFIT\\\\original_data\\\\%d.npy' % house_id)\n new_data = []\n current_index = 0\n current_time = int(data[0][0])\n end_time = int(data[-1][0]...
[ 14, 15, 22, 23, 26 ]
''' This file creates the model of Post, which maps to the post table in the mysql database. The model Provider contains four attributes: author, title, content, and created time. ''' from django.db import models class Post(models.Model): ''' The education post by provider database model ''' author ...
normal
{ "blob_id": "4fa9c00a07c8263a6a3afd460b84f21637a771ec", "index": 3081, "step-1": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return '{}'.format(self.title)\n", "step-2": "<mask token>\n...
[ 2, 3, 4, 5, 6 ]
a = input() b = [] ind = [] for i in a: if i.isalpha(): b.append(i) else: ind.append(a.index(i)) c = list(reversed(b)) for i in ind: c.insert(i, a[i]) print(''.join(c))
normal
{ "blob_id": "8fedaeb13fde117cf6b7ace23b59c26e4aab2bc2", "index": 4492, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in a:\n if i.isalpha():\n b.append(i)\n else:\n ind.append(a.index(i))\n<mask token>\nfor i in ind:\n c.insert(i, a[i])\nprint(''.join(c))\n", "step-3": "a ...
[ 0, 1, 2 ]
from __future__ import unicode_literals import json, alice_static import logging from random import choice # Импортируем подмодули Flask для запуска веб-сервиса. from flask import Flask, request app = Flask(__name__) logging.basicConfig(level=logging.DEBUG) # Хранилище данных о сессиях. sessionStorage = {} # Задаем...
normal
{ "blob_id": "2df679fc3407c15f5d0c006e9da8d1fc74bcf875", "index": 5705, "step-1": "from __future__ import unicode_literals\nimport json, alice_static\nimport logging\nfrom random import choice\n# Импортируем подмодули Flask для запуска веб-сервиса.\nfrom flask import Flask, request\napp = Flask(__name__)\n\n\nlog...
[ 0 ]
from coarsegrainparams import * from inva_fcl_stab import * from Eq import * from Dynamics import * from sympy import Matrix,sqrt def construct_param_dict(params,K_RC,K_CP,m_P): """ Construct all the parameters from its relationships with body size and temperature, using the normalizing constants and scaling e...
normal
{ "blob_id": "99c12e925850fe7603831df5b159db30508f4515", "index": 3832, "step-1": "<mask token>\n\n\ndef construct_param_dict(params, K_RC, K_CP, m_P):\n \"\"\"\n Construct all the parameters from its relationships with body size and temperature, using the normalizing constants and scaling exponent w\n \...
[ 5, 8, 9, 10, 11 ]
from datetime import datetime from poop import objstore class Comment(objstore.Item): __typename__ = 'comment' __table__ = 'comment' relatesToId = objstore.column('relates_to_id') relatesToVersion = objstore.column('relates_to_version') posted = objstore.column() approved = objstore.colum...
normal
{ "blob_id": "e398908ba74306c5a746d7643b38f08651cf92ec", "index": 4205, "step-1": "<mask token>\n\n\nclass Comment(objstore.Item):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, *a, **k):\n relatesTo = ...
[ 2, 3, 4, 5, 6 ]
from Psql_Database_Setup import * import requests, json engine = create_engine('postgresql://myuser:mypass@localhost:5432/mydb') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() response = requests.get("https://api.github.com/emojis") response = json.loads(response.te...
normal
{ "blob_id": "0aa95b6a72472e8e260c07f4c42a327384ca0da4", "index": 9173, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor key, value in response.items():\n Emoji = Emojis(name=key, url=value)\n session.add(Emoji)\n session.commit()\n", "step-3": "<mask token>\nengine = create_engine('postgresq...
[ 0, 1, 2, 3, 4 ]
# Generated by Django 3.0.4 on 2020-07-20 00:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_auto_20200720_0154'), ] operations = [ migrations.DeleteModel( name='Report', ), migrations.AlterF...
normal
{ "blob_id": "98bc6e0552991d7de1cc29a02242b25e7919ef82", "index": 3764, "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 = [('users', '00...
[ 0, 1, 2, 3, 4 ]
import logging from tqdm import tqdm logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def create_tables(db_engine): """RUN SQL STATEMENTS TO CREATE TABLES""" with db_engine.connect() as conn: create_table_stmts = [] create_drugs_table = """ DROP TABLE IF EXISTS dr...
normal
{ "blob_id": "f4c3b6ee6389b31c6a280bf7cfe920a2791c1299", "index": 4125, "step-1": "<mask token>\n\n\ndef create_tables(db_engine):\n \"\"\"RUN SQL STATEMENTS TO CREATE TABLES\"\"\"\n with db_engine.connect() as conn:\n create_table_stmts = []\n create_drugs_table = \"\"\"\n DROP TABLE I...
[ 1, 2, 3, 4, 5 ]
class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ if n == 0: nums1 = nums1 if nums1[m-1] <= nums2[0]: for i in range(n): nums1[m+i] = nums2[i] ...
normal
{ "blob_id": "4f13e2858d9cf469f14026808142886e5c3fcc85", "index": 28, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n\n\n<mask token>\n", "step-3": "class Solution:\n\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n Do not return anything, modify nums1 in-place ins...
[ 0, 1, 2, 3, 4 ]
from sklearn import datasets, svm import matplotlib.pyplot as plt digits = datasets.load_digits() X, y = digits.data[:-1], digits.target[:-1] clf = svm.SVC(gamma=0.1, C=100) clf.fit(X, y) prediction = clf.predict(digits.data[-1:]) actual = digits.target[-1:] print("prediction = " + str(prediction) + ", actual = " + ...
normal
{ "blob_id": "0d98472d1c04bfc52378aa6401a47d96582696a2", "index": 4046, "step-1": "<mask token>\n", "step-2": "<mask token>\nclf.fit(X, y)\n<mask token>\nprint('prediction = ' + str(prediction) + ', actual = ' + str(actual))\nplt.matshow(digits.images[-1])\nplt.show()\n", "step-3": "<mask token>\ndigits = dat...
[ 0, 1, 2, 3, 4 ]
# This file imports all files for this module for easy inclusions around the game. from viewController import * from navigationController import * from noticer import * from Images import * from fancyButton import * from constants import * from textObject import * from UIButton import * # from spriteFromRect import ...
normal
{ "blob_id": "7168a8eb401478aa26ee9033262bb5c8fe33f186", "index": 7011, "step-1": "<mask token>\n", "step-2": "from viewController import *\nfrom navigationController import *\nfrom noticer import *\nfrom Images import *\nfrom fancyButton import *\nfrom constants import *\nfrom textObject import *\nfrom UIButto...
[ 0, 1, 2 ]
def sumIntervals(input): interval = set() if len(input) > 0: for data in input: if len(data) == 2 and data[0] < data[1]: for i in range(data[0], data[1]): interval.add(i) else: return 1 return len(interval) else: ...
normal
{ "blob_id": "25434fccff4401df2cebc9b0c4d0231f056b4e81", "index": 6346, "step-1": "<mask token>\n", "step-2": "def sumIntervals(input):\n interval = set()\n if len(input) > 0:\n for data in input:\n if len(data) == 2 and data[0] < data[1]:\n for i in range(data[0], data[1]...
[ 0, 1, 2 ]
from __future__ import absolute_import from __future__ import division from __future__ import print_function from cv2 import DualTVL1OpticalFlow_create as DualTVL1 from tensorflow.python.platform import flags import os import sys sys.path.insert(0, '..') from utils import image_funcs import numpy as np def make_di...
normal
{ "blob_id": "42a717591fb8fe480581d8996e9811d0292d0eb1", "index": 7567, "step-1": "<mask token>\n\n\ndef make_dir(directory):\n import os\n import errno\n try:\n os.makedirs(directory)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\n<mask token>\n\n\ndef save...
[ 3, 5, 6, 7, 8 ]
import pandas as pd import numpy as np import matplotlib.pyplot as plt import xlrd from enum import Enum from sklearn import linear_model from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import statsmodels.formula.api as smf import statsmodels.api as sm import statsmodels.formula.a...
normal
{ "blob_id": "a903f9c5cae1c2eb2f40dc8ba29f0625a3d34224", "index": 9690, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef forward_selected(data, response):\n \"\"\"Linear model designed by forward selection.\n\n Parameters:\n -----------\n data : pandas DataFrame with all possible predict...
[ 0, 2, 3, 4, 5 ]
import numpy as np import os pwd = os.path.dirname(os.path.realpath(__file__)) train_data = np.load(os.path.join(pwd, 'purchase2_train.npy'), allow_pickle =True) test_data = np.load(os.path.join(pwd, 'purchase2_test.npy'), allow_pickle=True) train_data = train_data.reshape((1,))[0] test_data = test_data.reshape((1,...
normal
{ "blob_id": "8c364a518ab615803ea99520e90ee1dd24d37a8c", "index": 2524, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef load(indices, category='train'):\n if category == 'train':\n if max(indices) < len(X_train) and max(indices) < len(y_train):\n return X_train[indices], y_trai...
[ 0, 1, 2, 3 ]
'''Чи можна в квадратному залі площею S помістити круглу сцену радіусом R так, щоб від стіни до сцени був прохід не менше K?''' from math import sqrt s = int(input('Input your area of square (S): ')) r = int(input('Input your radius of scene (R): ')) k = int(input('Input your width of passage (K): ')) k2 = sqrt...
normal
{ "blob_id": "31a2fa5b2febc2ef80b57e45c2ebb662b886c4b7", "index": 6043, "step-1": "<mask token>\n", "step-2": "<mask token>\nif k2 >= k:\n print(' Yes, the scene can be set.')\nelse:\n print(\" Sorry, but the scene can't be set.\")\n", "step-3": "<mask token>\ns = int(input('Input your area of squ...
[ 0, 1, 2, 3, 4 ]
from django.shortcuts import render, Http404, HttpResponse, redirect from django.contrib.auth import authenticate, login from website.form import UserForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from website.models import UserProfile from website.form import UserForm import pandas as ...
normal
{ "blob_id": "d261efa72e1ab77507a1fd84aa2e462c6969af56", "index": 6579, "step-1": "<mask token>\n\n\ndef df_to_sql_T_1(filefullpath, sheet, row_name):\n excel_df = pd.read_excel(filefullpath, sheetname=sheet)\n excel_df = excel_df.dropna(how='all')\n excel_df = excel_df.dropna(axis=1, how='all')\n exc...
[ 5, 6, 7, 8, 9 ]
import re from prometheus_client.core import GaugeMetricFamily class ArrayHardwareMetrics: def __init__(self, fa): self.fa = fa self.chassis_health = None self.controller_health = None self.component_health = None self.temperature = None self.temperature = None ...
normal
{ "blob_id": "527d514cbad0916fecfe0da68de04d3b130d94c7", "index": 5156, "step-1": "<mask token>\n\n\nclass ArrayHardwareMetrics:\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ArrayHardwareMetrics:\n\n def __init__(self, fa):\n self.fa = fa\n self.c...
[ 1, 2, 3, 5, 6 ]
""" CONVERT HOURS INTO SECONDS Write a function that converts hours into seconds. Examples: - how_many_seconds(2) -> 7200 - how_many_seconds(10) -> 36000 - how_many_seconds(24) -> 86400 Notes: - 60 seconds in a minute; 60 minutes in a hour. - Don't forget to return your answer. """ """ U.P.E...
normal
{ "blob_id": "34c7e6b6bc687bc641b7e3b9c70fd0844af8e340", "index": 8969, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef how_many_seconds(hrs_int):\n secs_int = None\n if hrs_int > 0 and hrs_int is not None:\n secs_int = hrs_int * 60 * 60\n return secs_int\n else:\n rai...
[ 0, 1, 2 ]
class Boundary(): def __init__(self, py5_inst, x1, y1, x2, y2): self.py5 = py5_inst self.a = self.py5.create_vector(x1, y1) self.b = self.py5.create_vector(x2, y2) def show(self): self.py5.stroke(255) self.py5.line(self.a.x, self.a.y, self.b.x, self.b.y)
normal
{ "blob_id": "df00cc501b7b682cc1f4fbc9ae87a27984e6b5ef", "index": 5424, "step-1": "<mask token>\n", "step-2": "class Boundary:\n <mask token>\n <mask token>\n", "step-3": "class Boundary:\n <mask token>\n\n def show(self):\n self.py5.stroke(255)\n self.py5.line(self.a.x, self.a.y, se...
[ 0, 1, 2, 3, 4 ]