code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
from models.readingtip import ReadingTip
from database import db
class ReadingTipRepository:
def __init__(self):
pass
def get_tips(self, user, tag="all"):
if tag == "all":
return ReadingTip.query.filter_by(user=user).all()
else:
return ReadingTip.query.filter_by... | normal | {
"blob_id": "d82b68d5c83ae538d7a8b5ae5547b43ac4e8a3d4",
"index": 6910,
"step-1": "<mask token>\n\n\nclass ReadingTipRepository:\n <mask token>\n\n def get_tips(self, user, tag='all'):\n if tag == 'all':\n return ReadingTip.query.filter_by(user=user).all()\n else:\n retur... | [
4,
7,
9,
11,
12
] |
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render, HttpResponseRedirect, Http404
from django.contrib.auth import authenticate, login, logout
from accounts.forms import RegistrationForm, LoginForm, StudentDetailsForm, companyDetailsForm, SocietyDetailsForm
from accounts.models im... | normal | {
"blob_id": "7f21fcc1265be8b3263971a4e76470616459f433",
"index": 6061,
"step-1": "from django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render, HttpResponseRedirect, Http404\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom accounts.forms import RegistrationForm, ... | [
0
] |
# -*- coding: utf-8 -*-
import sqlalchemy as sa
import ujson
from aiohttp import web, WSMsgType
from .db import TLE
from .log import logger
from .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column
async def query(request):
filters = []
if 'filters' not in request.query:
rai... | normal | {
"blob_id": "c414e5d3934f741540fb5721a529b48f95e17016",
"index": 5982,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nasync def query(request):\n filters = []\n if 'filters' not in request.query:\n raise web.HTTPBadRequest(reason='Query parameter `filters` is required'\n )\n ... | [
0,
1,
2,
3
] |
DEFAULT_SIZE = 512
class DataEncoding:
@staticmethod
def segment_decode(segment):
arr = bytearray(segment)
ack_binary = bytearray([arr[i] for i in range(4)])
tip_binary = bytearray([arr[4]])
len_binary = bytearray([arr[i] for i in (5,6)])
ack = int.from... | normal | {
"blob_id": "47c5375816ab35e8225e5f3695f7ee2ab5336076",
"index": 4312,
"step-1": "<mask token>\n\n\nclass DataEncoding:\n\n @staticmethod\n def segment_decode(segment):\n arr = bytearray(segment)\n ack_binary = bytearray([arr[i] for i in range(4)])\n tip_binary = bytearray([arr[4]])\n ... | [
6,
8,
9,
10,
11
] |
SPACE = 0
MARK = 1
def frame_to_bit_chunks(frame_values, baud_rate=45.45, start_bit=SPACE, stop_bit=MARK):
"""フレームごとの信号強度からデータビットのまとまりに変換する"""
binary_values = frame_to_binary_values(frame_values)
bit_duration_values = binary_values_to_bit_duration(binary_values)
bit_values = bit_duration_to_bit_value... | normal | {
"blob_id": "ff67ef77958e78335dc1dc2c7e08bf42998387c6",
"index": 2374,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef binary_values_to_bit_duration(binary_values):\n \"\"\"連続する0/1の長さを測る\"\"\"\n previous_binary_value = SPACE\n previous_time = 0\n current_binary_value = SPACE\n curre... | [
0,
3,
4,
5,
7
] |
from datetime import datetime
from unittest import mock
import pytest
from freezegun import freeze_time
from datahub.ingestion.api.common import PipelineContext
from src.datahub.ingestion.source.aws.s3_util import make_s3_urn
FROZEN_TIME = "2020-04-14 07:00:00"
@pytest.mark.integration
def test_athena_config_query... | normal | {
"blob_id": "1304b6373edeca394070b8a3d144608cf07172e3",
"index": 9448,
"step-1": "<mask token>\n\n\n@pytest.mark.integration\ndef test_athena_config_query_location_old_plus_new_value_not_allowed():\n from datahub.ingestion.source.sql.athena import AthenaConfig\n with pytest.raises(ValueError):\n Ath... | [
3,
4,
5,
6,
7
] |
import sys
from ulang.runtime.main import main
main(sys.argv)
| normal | {
"blob_id": "e0c5498d9b18a6a32fcd2725ef4f6a1adaef6c68",
"index": 2098,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmain(sys.argv)\n",
"step-3": "import sys\nfrom ulang.runtime.main import main\nmain(sys.argv)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
"""
Package for django_static_template.
"""
| normal | {
"blob_id": "818623621b609d67f8f657be4ade6e3bb86a0bc5",
"index": 4226,
"step-1": "<mask token>\n",
"step-2": "\"\"\"\r\nPackage for django_static_template.\r\n\"\"\"\r\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
#!/usr/bin/env python
# Copyright (C) 2014 Open Data ("Open Data" refers to
# one or more of the following companies: Open Data Partners LLC,
# Open Data Research LLC, or Open Data Capital LLC.)
#
# This file is part of Hadrian.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... | normal | {
"blob_id": "780dc49c3eaef3fb25ca0aac760326b1c3adc633",
"index": 6002,
"step-1": "<mask token>\n\n\nclass Dot(LibFcn):\n name = prefix + 'dot'\n sig = Sigs([Sig([{'x': P.Array(P.Array(P.Double()))}, {'y': P.Array(P.\n Double())}], P.Array(P.Double())), Sig([{'x': P.Map(P.Map(P.Double(\n )))},... | [
26,
42,
47,
53,
59
] |
#@@---------------------------@@
# Author: Chamil Jayasundara
# Date: 5/18/17
# Description: Extract SFLOW data from slow logs
#@@---------------------------@@
import itertools
from collections import defaultdict
"""Flow Sample and Datagram Objects"""
class Container(object):
def __init__(self, id):
... | normal | {
"blob_id": "395ff2e7c052b57548151fc71fad971c94ebceea",
"index": 3974,
"step-1": "<mask token>\n\n\nclass WithinDatagram(object):\n\n def __init__(self, traceObj):\n self.Trace = traceObj\n self.current_datagram = None\n <mask token>\n\n\nclass WithinFlowsample(object):\n\n def __init__(se... | [
9,
12,
14,
16,
23
] |
# coding=utf-8
from lxml import etree
import frontik.handler
class Page(frontik.handler.PageHandler):
def get_page(self):
self.set_xsl(self.get_argument('template', 'simple.xsl'))
self.doc.put(etree.Element('ok'))
if self.get_argument('raise', 'false') == 'true':
raise front... | normal | {
"blob_id": "6f331eedcdaceaded142c3ffe9400aaa817613c1",
"index": 5795,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Page(frontik.handler.PageHandler):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Page(frontik.handler.PageHandler):\n\n def get_page(self):\n self.set_xsl... | [
0,
1,
2,
3,
4
] |
import graphics
from graphics import *
class Renderer():
def __init__(self, engine, width=700, height=600):
self.width = width
self.height = height
self.engine = engine
self.win = GraphWin("Game Board", width, height)
self.win.setBackground("blue")
def update(self):
... | normal | {
"blob_id": "85a3682f144f02aa412d45c901f76c65de2e816d",
"index": 5599,
"step-1": "<mask token>\n\n\nclass Renderer:\n <mask token>\n <mask token>\n <mask token>\n\n def get_width(self):\n return self.width\n\n def draw_board(self):\n for i in range(0, 6):\n horLines = Line... | [
8,
9,
10,
12,
14
] |
print("gist test file4") | normal | {
"blob_id": "ec4725b5b60d10e86b29aab3723917ace5cf52f6",
"index": 8452,
"step-1": "<mask token>\n",
"step-2": "print('gist test file4')\n",
"step-3": "print(\"gist test file4\")",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
class Person:
def __init__(self,mood):
self.mood=mood;
def laugh(self):
self.mood.laugh()
def cry(self):
self.mood.cry()
def setMood(self, mood):
self.mood=mood
class Mood:
def laugh(self):
pass
def cry(self):
pass
class HappyMood(Mood):
def laugh(self):
print 'Ha ha ha!'
class SadMood(Mood)... | normal | {
"blob_id": "4deb691545887104b3fb70dd2be52138088ba1e8",
"index": 1751,
"step-1": "class Person:\n\tdef __init__(self,mood):\n\t\tself.mood=mood;\n\n\tdef laugh(self):\n\t\tself.mood.laugh()\n\n\tdef cry(self):\n\t\tself.mood.cry()\n\t\n\tdef setMood(self, mood):\n\t\tself.mood=mood\n\nclass Mood:\n\tdef laugh(se... | [
0
] |
'''
Module for handling configurable portions of tools
'''
from json import load
default_file_loc = 'config.json'
config = None
def loadConfiguration(fileloc):
'''Loads configuration from file location'''
global config
with open(fileloc, 'r') as file_:
conf = load(file_)
if config is None:
... | normal | {
"blob_id": "5261ae90a67e2df8dd1c679a8046ee3e0cbc6221",
"index": 3264,
"step-1": "<mask token>\n\n\ndef loadConfiguration(fileloc):\n \"\"\"Loads configuration from file location\"\"\"\n global config\n with open(fileloc, 'r') as file_:\n conf = load(file_)\n if config is None:\n config... | [
2,
3,
4,
5,
6
] |
from __future__ import division, print_function, absolute_import
"""
The dataset is stored in a CSV file, so we can use the TFLearn load_csv() function to
load the data from the CSV file into a python list.
We specify the 'target_column' argument to indicate that our labels (survived or not)
are located in the first... | normal | {
"blob_id": "87e9c1d264523d02b287dedb44472fc08b488908",
"index": 9630,
"step-1": "<mask token>\n\n\ndef preprocess(passengers, columns_to_delete):\n for column_to_delete in sorted(columns_to_delete, reverse=True):\n [passenger.pop(column_to_delete) for passenger in passengers]\n for i in range(len(p... | [
1,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
'''
Created on 2014-03-25
@author: ZhaoJianning
Modified by WangHairui on 2014-09-12
'''
import unittest
import Stability
import time
import os,sys
import runtests
import re
import android
import datetime
class TestCamera(unittest.TestCase):
def setUp(self):
... | normal | {
"blob_id": "a520a93ed2dcd26b9470ed56e96b65a1b3550176",
"index": 6260,
"step-1": "# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2014-03-25\r\n\r\n@author: ZhaoJianning\r\nModified by WangHairui on 2014-09-12\r\n'''\r\n\r\nimport unittest\r\nimport Stability\r\nimport time\r\nimport os,sys\r\nimport runtests\r\nim... | [
0
] |
import tensorflow as tf
import bbox_lib
def hard_negative_loss_mining(c_loss, negative_mask, k):
"""Hard negative mining in classification loss."""
# make sure at least one negative example
k = tf.maximum(k, 1)
# make sure at most all negative.
k = tf.minimum(k, c_loss.shape[-1])
neg_c_loss = ... | normal | {
"blob_id": "6e17fef4507c72190a77976e4a8b2f56880f2d6f",
"index": 4895,
"step-1": "<mask token>\n\n\ndef hard_negative_loss_mining(c_loss, negative_mask, k):\n \"\"\"Hard negative mining in classification loss.\"\"\"\n k = tf.maximum(k, 1)\n k = tf.minimum(k, c_loss.shape[-1])\n neg_c_loss = c_loss * ... | [
2,
3,
4,
5,
6
] |
ii = [('CookGHP3.py', 2), ('MarrFDI.py', 1), ('GodwWSL2.py', 2), (
'ChanWS.py', 6), ('SadlMLP.py', 1), ('WilbRLW.py', 1), ('AubePRP2.py',
1), ('MartHSI2.py', 1), ('WilbRLW5.py', 1), ('KnowJMM.py', 1), (
'AubePRP.py', 2), ('ChalTPW2.py', 1), ('ClarGE2.py', 2), ('CarlTFR.py',
3), ('SeniNSP.py', 4), ('Gri... | normal | {
"blob_id": "b80ccee42489aefb2858b8491008b252f6a2b9b7",
"index": 4864,
"step-1": "<mask token>\n",
"step-2": "ii = [('CookGHP3.py', 2), ('MarrFDI.py', 1), ('GodwWSL2.py', 2), (\n 'ChanWS.py', 6), ('SadlMLP.py', 1), ('WilbRLW.py', 1), ('AubePRP2.py', \n 1), ('MartHSI2.py', 1), ('WilbRLW5.py', 1), ('KnowJM... | [
0,
1
] |
# Create two integer variables and print their sum. What is the type of the
# result?
# Now, create a float variable and print its sum with an integer variable. What
# is the type of the result.
# Divide your smallest integer value by your largest integer value. Is the
# result what you expected? Now, do the same wit... | normal | {
"blob_id": "fcbbffe0682da9f2131fdddbef606dcae3303ce9",
"index": 1979,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(float(my_int))\n<mask token>\n",
"step-3": "greeting = 'My name is '\nyour_name = ''\nbest_string = 'I am '\nyour_age = 6\nmy_int = 5\nprint(float(my_int))\npi = 3.1415\n",
"ste... | [
0,
1,
2,
3
] |
import telebot
import os
from misc.answers import answer_incorrect, answer_correct, answer_start
from helper import get_challenge_text, get_solved_challenge_text, is_correct_answer
bot = telebot.TeleBot(os.environ.get('API_KEY_TELEGRAM'))
default_parse_mode = "Markdown"
@bot.message_handler(commands=['start'])
def w... | normal | {
"blob_id": "f9f66452756cb67689d33aeb2e77535086355a7d",
"index": 5115,
"step-1": "<mask token>\n\n\n@bot.message_handler(commands=['new_game'])\ndef new_game(message):\n print(f'try new game with message: {message.text}')\n answer = ''\n try:\n answer = get_challenge_text(message.text)\n p... | [
2,
4,
5,
6,
7
] |
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2020 ifm electronic gmbh
#
# THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
#
"""
This module provides the recording control GUI service for the nexxT framework.
"""
import logging
from pathlib import Path
from nexxT.Qt.QtCore import Qt, QStorageInf... | normal | {
"blob_id": "3e4771d074218fb0a77332ee61a4cc49f1c301b7",
"index": 9356,
"step-1": "<mask token>\n\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n <mask token>\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n self._directory = str(Path('.').ab... | [
6,
8,
9,
12,
15
] |
class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def validateIPv4(IP):
digits = IP.split('.')
if len(digits) != 4:
return False
for digitstr in digits:
if len(digitstr)... | normal | {
"blob_id": "6216a5e45fee8ade5ec9072c42c1b08f3b0f4c65",
"index": 2433,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n\n def valida... | [
0,
1,
2,
3
] |
""" Problem statement:
https://leetcode.com/problems/contains-duplicate-ii/description/
Given an array of integers and an integer k, find out whether
there are two distinct indices i and j in the array such that nums[i] = nums[j]
and the absolute difference between i and j is at most k.
"""
class Solution:
def c... | normal | {
"blob_id": "33c241747062ab0d374082d2a8179335503fa212",
"index": 3320,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution:\n\n def containsNearbyDuplicate(self, nums, k):\n \"\"\" Time complexi... | [
0,
1,
2,
3,
4
] |
class Figura:
def __init__(self):
print("Tworze obiekt klasy Figura...")
def pobierz_polozenie(self):
print("Metoda pobierz_polozenie klasy Figura.")
def nadaj_polozenie(self):
print("Metoda nadaj_polozenie klasy Figura.")
def wyswietl(self):
print("Metoda wyswietl klasy ... | normal | {
"blob_id": "774bf2b49f6e546f16294edc17e9ac34fa8a9ba8",
"index": 2711,
"step-1": "<mask token>\n\n\nclass Punkt(Figura):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Linia(Figura):\n\n def __init__(self):\n print('Tworze obiekt klasy Linia...')\n\n def wyswietl(... | [
27,
30,
31,
34,
41
] |
try:
from zcrmsdk.src.com.zoho.crm.api.dc.data_center import DataCenter
except Exception as e:
from .data_center import DataCenter
class EUDataCenter(DataCenter):
"""
This class represents the properties of Zoho CRM in EU Domain.
"""
@classmethod
def PRODUCTION(cls):
"""
... | normal | {
"blob_id": "27c364ccf4a6703f74c95ebb386f8ced38b1eafd",
"index": 4960,
"step-1": "<mask token>\n\n\nclass EUDataCenter(DataCenter):\n <mask token>\n\n @classmethod\n def PRODUCTION(cls):\n \"\"\"\n This method represents the Zoho CRM Production environment in EU domain\n :return: An... | [
4,
5,
7,
8,
9
] |
cadena = input("Introduzca su cadena: ")
separador = input("Introduzca el separador: ")
print(cadena.replace(" ", separador)) | normal | {
"blob_id": "290b8b4c3aeafc84b1e9cce7e6d2a5e770bd8716",
"index": 3444,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(cadena.replace(' ', separador))\n",
"step-3": "cadena = input('Introduzca su cadena: ')\nseparador = input('Introduzca el separador: ')\nprint(cadena.replace(' ', separador))\n",
... | [
0,
1,
2,
3
] |
from flask import Blueprint, request, jsonify
from to_dict import *
from validacao import *
import sqlite3
from migration import conectar, create_database
from contextlib import closing
aluno = Blueprint("aluno", __name__)
@aluno.route("/hello")
def hello():
return "Hello, aluno"
@aluno.route("/reseta", methods ... | normal | {
"blob_id": "5068336ca1a180e09a7efd41eea596cdcebb33ae",
"index": 5586,
"step-1": "<mask token>\n\n\n@aluno.route('/hello')\ndef hello():\n return 'Hello, aluno'\n\n\n@aluno.route('/reseta', methods=['POST'])\ndef reseta():\n sqlaluno = 'DELETE FROM aluno'\n sqldisciplina = 'DELETE FROM disciplina'\n ... | [
6,
7,
8,
9,
10
] |
class User:
account = []
def __init__(self,balance,int_rate):
self.balance = balance
self.int_rate = int_rate
User.account.append(self)
def dep(self,amount):
self.balance += amount
return self
def make_withdrawal(self,amount):
if(self.balance-amount) >= 0... | normal | {
"blob_id": "ff3f6d50498f58f3a340e2d690165efcc1a5fb1d",
"index": 6000,
"step-1": "class User:\n <mask token>\n\n def __init__(self, balance, int_rate):\n self.balance = balance\n self.int_rate = int_rate\n User.account.append(self)\n\n def dep(self, amount):\n self.balance +=... | [
8,
10,
11,
12,
13
] |
#!/usr/bin/env python
# coding: utf-8
# # Cabecera
# In[1]:
# -*- coding: utf-8 -*-
# ------------- Cantidad de segundos que has vivido -------------
# # Definición de variables
# In[2]:
# Definición de variables
anios = 30
dias_por_anio = 365
horas_por_dia = 24
segundos_por_hora = 60
# # Operación
# In[3]... | normal | {
"blob_id": "f153da7e4537f807f6c9d9d268a00443933d8315",
"index": 4167,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(anios * dias_por_anio * horas_por_dia * segundos_por_hora)\n",
"step-3": "anios = 30\ndias_por_anio = 365\nhoras_por_dia = 24\nsegundos_por_hora = 60\nprint(anios * dias_por_anio ... | [
0,
1,
2,
3
] |
import json
from faker import Faker
import random
fake = Faker()
from faker.providers import date_time
fake.add_provider(date_time)
class Hour(object):
def __init__(self):
self.dayOfTheWeek = fake.day_of_week()
self.openingTime = str(random.randint(1, 12)) + 'AM'
self.closingTime = str(ra... | normal | {
"blob_id": "e3386b01bb0bdc7064a2e3e9f3edce8a3231721b",
"index": 3664,
"step-1": "<mask token>\n\n\nclass Hour(object):\n\n def __init__(self):\n self.dayOfTheWeek = fake.day_of_week()\n self.openingTime = str(random.randint(1, 12)) + 'AM'\n self.closingTime = str(random.randint(1, 12)) +... | [
2,
3,
4,
5
] |
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.touch_action import TouchAction
import time
import re
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import pymongo
def getSize():
x = driv... | normal | {
"blob_id": "6e614d1235a98ef496956001eef46b4447f0bf9b",
"index": 4677,
"step-1": "<mask token>\n\n\ndef getSize():\n x = driver.get_window_size()['width']\n y = driver.get_window_size()['height']\n return x, y\n\n\n<mask token>\n\n\ndef swipeUp(t):\n l = getSize()\n x1 = int(l[0] * 0.5)\n y1 = ... | [
3,
4,
5,
6,
7
] |
import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... | normal | {
"blob_id": "9e21a39358d97633b49ad83805990c29c19a80ed",
"index": 8599,
"step-1": "<mask token>\n\n\ndef _update_mpy_clip(clip, subclip, speed, frame, norm, loop, duration, pos,\n scale, vol, **kwargs):\n assert duration is not None\n if subclip is not None:\n if isinstance(subclip, (int, float)):... | [
8,
9,
10,
12,
15
] |
from enum import Enum
class AggregationTypes(Enum):
NO_AGG = 'NO-AGG'
STATIC = 'STATIC'
SUB_HOUR = 'SUB-HOUR'
DYNAMIC = 'DYNAMIC'
| normal | {
"blob_id": "436b89b91aed14525f847e6488b452b7ca0e1b70",
"index": 5322,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass AggregationTypes(Enum):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass AggregationTypes(Enum):\n NO_AGG = 'N... | [
0,
1,
2,
3
] |
from microbit import *
import radio
radio.on()
# receiver will show the distance to the beacon
# the number of receivers should be easily adjustable
while True:
message=radio.receive_full()
# the stronger the signal the higher the number
if message:
strength = message[1]+100
displaystrength... | normal | {
"blob_id": "dffa5e2f34788c6f5a5ccc7d8375317a830288b5",
"index": 7994,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nradio.on()\nwhile True:\n message = radio.receive_full()\n if message:\n strength = message[1] + 100\n displaystrength = int(strength / 10 + 1)\n display.show(s... | [
0,
1,
2,
3
] |
import xmlrpclib
import socket
import time
import math
import re
from roundup.exceptions import Reject
REVPAT = re.compile(r'(r[0-9]+\b|rev(ision)? [0-9]+\b)')
def extract_classinfo(db, klass, nodeid, newvalues):
if None == nodeid:
node = newvalues
content = newvalues['content']
else:
... | normal | {
"blob_id": "3ec0c20fb2dfed9930885885288cc5d47f4f5ee5",
"index": 6196,
"step-1": "\nimport xmlrpclib\nimport socket\nimport time\nimport math\nimport re\n\nfrom roundup.exceptions import Reject\n\nREVPAT = re.compile(r'(r[0-9]+\\b|rev(ision)? [0-9]+\\b)')\n\ndef extract_classinfo(db, klass, nodeid, newvalues):\n... | [
0
] |
from odoo import api, tools, fields, models, _
import base64
from odoo import modules
class InheritUser(models.Model):
_inherit = 'pos.config'
related_pos_user = fields.One2many('pos.session.users', 'pos_config', string='Related User')
class InheritSession(models.Model):
_name = 'pos.session.users'
... | normal | {
"blob_id": "2cff5fdfc86793592dd97de90ba9c3a11870b356",
"index": 8987,
"step-1": "<mask token>\n\n\nclass InheritUser(models.Model):\n _inherit = 'res.users'\n pos_sessions = fields.Many2many('pos.config', string=\n 'Point of Sale Accessible')\n\n @api.multi\n def write(self, vals):\n i... | [
4,
6,
7,
8,
10
] |
from django.apps import AppConfig
class ShortenConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'shorten'
| normal | {
"blob_id": "8c2920db7fc49d56aa8da6289cd22272ed3e3283",
"index": 4402,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass ShortenConfig(AppConfig):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass ShortenConfig(AppConfig):\n default_auto_field = 'django.db.models.BigA... | [
0,
1,
2,
3
] |
from flask import Flask, jsonify
import dataExtraction as dataEx
from flask_cors import CORS,cross_origin
from analyseSentiment import twitterDataExtaraction
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/scrapingDB"
mongo = PyMongo(app)
db = mongo.db
cors ... | normal | {
"blob_id": "17505f5c14190df3311c04c19f687937481b920b",
"index": 1168,
"step-1": "<mask token>\n\n\n@app.route('/visualisation/confirmed/<string:country>')\n@cross_origin()\ndef confirmedCases(country):\n array = dataEx.getData('Confirmed', country).tolist()\n return jsonify({'confirmed': array})\n\n\n@app... | [
17,
18,
19,
21,
22
] |
import doseresponse as dr
import numpy as np
import scipy.stats as st
import numpy.random as npr
import argparse
import itertools as it
# get rid of for real version
import pandas as pd
import os
seed = 1
npr.seed(seed)
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--samples", type=int, help="number... | normal | {
"blob_id": "2f6baf4de40224f5a3d00ded35e751184ab59d0d",
"index": 9201,
"step-1": "import doseresponse as dr\nimport numpy as np\nimport scipy.stats as st\n\nimport numpy.random as npr\nimport argparse\nimport itertools as it\n\n# get rid of for real version\nimport pandas as pd\nimport os\n\nseed = 1\nnpr.seed(s... | [
0
] |
from django.contrib import admin
from django.contrib.staticfiles.urls import static # 本Ch11.1
from django.urls import path, include
from . import settings_common, settings_dev # 本Ch11.1
import debug_toolbar
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('login_test_app.urls')),
path('... | normal | {
"blob_id": "ce626afa7c0fd2e190afd92b57a0ebebf19f9e9b",
"index": 6842,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns += static(settings_common.MEDIA_URL, document_root=settings_dev\n .MEDIA_ROOT)\n",
"step-3": "<mask token>\nurlpatterns = [path('admin/', admin.site.urls), path('', inclu... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class AcademyConfig(AppConfig):
name = 'academy'
verbose_name = u"Академия"
| normal | {
"blob_id": "619d2df45d0823930484f030a9a78e71ec718cb7",
"index": 6661,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass AcademyConfig(AppConfig):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass AcademyConfig(AppConfig):\n name = 'academy'\n verbose_name = u'Акад... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python3
import os
import netifaces
# nicList = netifaces.interfaces()
NICList = [i for i in netifaces.interfaces() if i != "lo"]
for i in NICList:
os.system("sudo ifconfig " + i + " promisc")
os.system("sudo python ./src/top.py")
| normal | {
"blob_id": "b38d23a7de3c805ddde4ed2d236e3c6e7bb5e2d0",
"index": 118,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in NICList:\n os.system('sudo ifconfig ' + i + ' promisc')\nos.system('sudo python ./src/top.py')\n",
"step-3": "<mask token>\nNICList = [i for i in netifaces.interfaces() if i ... | [
0,
1,
2,
3,
4
] |
import os
print(os.name)
#print(os.environ)
print(os.environ.get('PATH'))
print(os.path.abspath('.'))
os.path.join(os.path.abspath('.'),'testdir')
os.mkdir(os.path.abspath('.')) | normal | {
"blob_id": "fd059ae6e5eb3f7dc18dff6f9ed206002cea5fb2",
"index": 9788,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(os.name)\nprint(os.environ.get('PATH'))\nprint(os.path.abspath('.'))\nos.path.join(os.path.abspath('.'), 'testdir')\nos.mkdir(os.path.abspath('.'))\n",
"step-3": "import os\nprint... | [
0,
1,
2,
3
] |
"""Woma objects for dealing with HTTP.
Request and Response inherit from webob's Request and Response objects, so see
http://docs.webob.org/en/latest/ for full documentation. The only things
documented here are the customizations.
"""
from webob import Request as BaseRequest
from webob import Response as BaseResponse... | normal | {
"blob_id": "ca11e9cf0bcfcbd714c45b5c95bd2c2044b65909",
"index": 384,
"step-1": "<mask token>\n\n\nclass Client(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Request(BaseRequest):\n \"\"\"A webob.Request with additional properti... | [
8,
11,
12,
14,
16
] |
"""
Django settings for gamelibrary project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... | normal | {
"blob_id": "b42414b7d8ed80d8794ab7c49dfde1e5df0721f1",
"index": 1318,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nALLOWED_HOSTS = []\nINSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth',\n 'django.contrib.contentty... | [
0,
1,
2,
3
] |
#!/usr/bin/python
#coding:utf-8
import glob, os
#from collections import OrderedDict
aa = os.popen("grep -E 'register|cp' all.log |grep -v 'bohan' | awk '{ print $6 }' > /opt/csvt01/logs/tmp.txt").read().strip()
#os.system("grep -E 'register|cp' all.log |grep -v 'bohan' | awk '{ print $6 }' > /opt/csvt01/logs/tmp.t... | normal | {
"blob_id": "fc8f3be408f4d21de2ae18776cd60177c82bea77",
"index": 2068,
"step-1": "#!/usr/bin/python \n#coding:utf-8 \nimport glob, os\n#from collections import OrderedDict\naa = os.popen(\"grep -E 'register|cp' all.log |grep -v 'bohan' | awk '{ print $6 }' > /opt/csvt01/logs/tmp.txt\").read().strip()\n#os.syste... | [
0
] |
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100, default='admin')
content = models.TextField(max_length=5000)
... | normal | {
"blob_id": "0bc53130a4248178f4c3fabbae7d2546f0d5b8fd",
"index": 5996,
"step-1": "<mask token>\n\n\nclass Search_record(models.Model):\n title = models.CharField(max_length=100)\n url = models.CharField(max_length=100)\n searchCount = models.IntegerField(blank=True)\n zhihu_type = models.IntegerField... | [
18,
24,
25,
27,
29
] |
"""
Create all figures and Excel files that combine data from all embryos in a given genetic background
Copyright (C) 2017 Ahmet Ay, Dong Mai, Soo Bin Kwon, Ha Vu
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software ... | normal | {
"blob_id": "86928f4358e4999a5cec8bfad1fe055c9a2778d1",
"index": 6230,
"step-1": "<mask token>\n\n\ndef main():\n args = sys.argv[1:]\n num_args = len(args)\n req_args = [False] * 3\n num_bins = DEFAULT_NUM_BIN\n if num_args >= 6:\n i = 0\n while i < num_args - 1:\n option... | [
2,
3,
4,
5,
6
] |
import numpy as np
def shufflelists(lists):
li = np.random.permutation(len(lists[0])
lo = []
for i in range(len(li)):
| normal | {
"blob_id": "fc01c6fb812fe78ca04496494d68fcc90ae706f5",
"index": 3605,
"step-1": "import numpy as np\n\ndef shufflelists(lists):\n li = np.random.permutation(len(lists[0])\n lo = []\n for i in range(len(li)):\n \n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
... | [
0
] |
# -*- coding: utf-8 -*-
def merge_sort(mlist):
if len(mlist) <= 1:
return mlist
mid = int(len(mlist) / 2)
# 使用递归将数组二分分解
left = merge_sort(mlist[:mid])
right = merge_sort(mlist[mid:])
return merge(left, right) # 将每次分解出来的数组各自排序,合并成一个大数组
def merge(left, right):
"""
... | normal | {
"blob_id": "a6192e39d86005882d0bde040a99f364bf701c3b",
"index": 1266,
"step-1": "<mask token>\n",
"step-2": "def merge_sort(mlist):\n if len(mlist) <= 1:\n return mlist\n mid = int(len(mlist) / 2)\n left = merge_sort(mlist[:mid])\n right = merge_sort(mlist[mid:])\n return merge(left, rig... | [
0,
1,
2,
3,
4
] |
def usage_list(self):
print('Available modules')
print('=================')
for module in sorted(self.list()):
if ('module' not in self.mods[module]):
self.import_module(module)
if (not self.mods[module]['module'].__doc__):
continue
text = self.mods[module]['m... | normal | {
"blob_id": "d0eb6ea2e816ac59ae93684edb38ff3a49909633",
"index": 762,
"step-1": "<mask token>\n",
"step-2": "def usage_list(self):\n print('Available modules')\n print('=================')\n for module in sorted(self.list()):\n if 'module' not in self.mods[module]:\n self.import_modu... | [
0,
1,
2
] |
import sys
sys.path.append("..") # Adds higher directory to python modules path.
from utils import npm_decorator
# num_node = 3
@ npm_decorator(3)
def scenario():
"""
1. Check each peer's genesis block
2. Generate new blocks on each peer
2.1. 2 blocks on peer #1
2.2. 4 blocks on peer #2
... | normal | {
"blob_id": "91cf1f4cf34ac9723be4863e81149c703adca27a",
"index": 3583,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@npm_decorator(3)\ndef scenario():\n \"\"\"\n 1. Check each peer's genesis block\n 2. Generate new blocks on each peer\n 2.1. 2 blocks on peer #1\n 2.2. 4 block... | [
0,
1,
2,
3,
4
] |
def _make_key(*args, **kwargs):
all_args = [str(arg) for arg in args]
all_args += [str(arg) + '=' + str(value) for arg, value in kwargs.items()]
return '|'.join(all_args)
class DoubleLinked:
def __init__(self, prv, nxt, key):
self.prv = prv
self.nxt = nxt
self.key = key
class... | normal | {
"blob_id": "9c251e0224979877b9ce244e4871fd4c403abb8e",
"index": 1583,
"step-1": "<mask token>\n\n\nclass LRUCache:\n\n def __init__(self, get_from_origin, max_size=1024):\n if max_size == 0:\n raise NotImplementedError()\n if max_size < 0:\n raise ValueError()\n sel... | [
10,
14,
16,
23,
24
] |
class HashTableEntry:
"""
Hash Table entry, as a linked list node.
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
"""
A hash table that with `capacity` buckets
that accepts string keys
Implement this.
... | normal | {
"blob_id": "7e58fe636e6d835d7857a49900bbc127b52f63d9",
"index": 6112,
"step-1": "<mask token>\n\n\nclass HashTable:\n <mask token>\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.storage = [None] * capacity\n self.numberOfItems = 0\n\n def fnv1(self, key):\n ... | [
6,
11,
13,
15,
16
] |
import sys
import array
import random
import math
import gameduino2.prep
import zlib
import struct
import gameduino as GD
from eve import align4
from PIL import Image
import numpy as np
import wave
import common
GLOWR = (128, 256)
GLOWR = (160, 400)
sys.path.append("/home/jamesb/git/gd2-asset/examples/nightstrike")
... | normal | {
"blob_id": "2471daad5969da29a20417a099a3ecd92fa036b4",
"index": 6393,
"step-1": "<mask token>\n\n\nclass Renderer(common.Branded):\n\n def __init__(self, eve):\n self.eve = eve\n self.t = 0\n\n def load(self):\n eve = self.eve\n eve.cc(open(\n '/home/jamesb/git/gd2-a... | [
4,
5,
6,
7,
8
] |
from django.http import request
from restapp.ExcelSheet import *
'''ApiHomeDict={}
class LoadDict():
e = ExcelSheetAll()
ApiHomeDict = e.apiHomeDict()
print ApiHomeDict
class ReturnApi:
def returnDict(self):
return ApiHomeDict'''
'''if "ApiDictionary" in request.session:
print... | normal | {
"blob_id": "ff924b803a875d3f6201baa2c1251a6c5b8cde61",
"index": 5903,
"step-1": "<mask token>\n",
"step-2": "from django.http import request\nfrom restapp.ExcelSheet import *\n<mask token>\n",
"step-3": "from django.http import request\r\nfrom restapp.ExcelSheet import *\r\n\r\n\r\n'''ApiHomeDict={}\r\nclas... | [
0,
1,
2
] |
from .base import BaseLevel
from map_objects import DefinedMap
from entity.monster import Daemon
from entity.weapons import Axe
class FinalLevel(BaseLevel):
def __init__(self):
lvl_map = DefinedMap('levels/demon_lair.xp')
super().__init__(lvl_map.width, lvl_map.height)
self.map = lvl_map
... | normal | {
"blob_id": "7ba8f0bd962413f6ff825df27330447b11360f10",
"index": 6089,
"step-1": "<mask token>\n\n\nclass FinalLevel(BaseLevel):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass FinalLevel(BaseLevel):\n\n def __init__(self):\n lvl_map = DefinedMap('levels/demon_lair.xp')\n ... | [
1,
2,
3,
4
] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras.layers import Dense, Input
from keras.layers import Conv2D, Flatten, Lambda
from keras.layers import Reshape, Conv2DTranspose
from keras.models import Model
from keras.losses import mse, binary_cross... | normal | {
"blob_id": "88343b9c5cac3510e8cea75ac5b11f517ddc164b",
"index": 5943,
"step-1": "<mask token>\n\n\ndef sampling(args):\n \"\"\"Reparameterization trick by sampling fr an isotropic unit Gaussian.\n # Arguments\n args (tensor): mean and log of variance of Q(z|X)\n # Returns\n z (tensor): sa... | [
2,
3,
4,
5,
6
] |
from typing import Set, Dict, Tuple
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top_secret'
# Определение константных величин
RULE: Dict[Tuple[str, str], str] = {('H', 'a'): 'S',
('H', 'b'): 'SE',
... | normal | {
"blob_id": "86ea1c46383b5a8790eb187163107f4100395ef3",
"index": 8962,
"step-1": "<mask token>\n\n\ndef finite_automate(word: str) ->str:\n \"\"\"Реализация конечного автомата для проверки символьных строк\"\"\"\n state: str = INITIAL_STATE\n for ind, char in enumerate(word):\n yield f'{word[ind:... | [
2,
3,
4,
5,
6
] |
import random
from . import WaiterInterface
class RandomIPv4Waiter(WaiterInterface):
"""
HostPortWaiter which generates random ipv4 adresses
"""
def __init__(self, options):
self.ports = options['ports']
self.limit_generate = options.get('limit_generate', -1)
def generator(self):
... | normal | {
"blob_id": "bd3b1263d7d657fe2edd3c7198f63821a3d1d1e5",
"index": 319,
"step-1": "<mask token>\n\n\nclass RandomIPv4Waiter(WaiterInterface):\n <mask token>\n <mask token>\n\n def generator(self):\n while self.limit_generate != 0:\n randomIPv4 = generateRandomIPv4()\n yield ra... | [
2,
4,
5,
6,
7
] |
import json
from bottle import request, response, route, get, run, default_app
app = application = default_app()
@route('/candidate/hired', method=['POST'])
def update_delete_handler():
response.content_type = 'application/json'
return json.dumps({"hired": True})
def main():
run(host='localhost', port... | normal | {
"blob_id": "50e759ff24cdb8fbb5a98d9381afb13ebc1a74f1",
"index": 7317,
"step-1": "<mask token>\n\n\n@route('/candidate/hired', method=['POST'])\ndef update_delete_handler():\n response.content_type = 'application/json'\n return json.dumps({'hired': True})\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n... | [
1,
2,
3,
4,
5
] |
from getMerriamWebster import searchMerriamWebster
from searchWikipedia import searchWikipedia
from synonyms import searchSynonyms
class Scraping:
def __init__(self, clues, answers, gridIndex):
self.clues = clues
self.domains = {"across": {}, "down":{}}
self.answers = answers
self.g... | normal | {
"blob_id": "138abb40fda0f19b4a74a294d5cd0dd326dc59ce",
"index": 7722,
"step-1": "<mask token>\n\n\nclass Scraping:\n\n def __init__(self, clues, answers, gridIndex):\n self.clues = clues\n self.domains = {'across': {}, 'down': {}}\n self.answers = answers\n self.gridIndex = gridIn... | [
4,
6,
9,
11,
12
] |
S = input()
T = []
sen = ["dream", "dreamer", "erase", "eraser"]
s_len = len(S)
while len(T) <= s_len:
| normal | {
"blob_id": "b874bb37fa59d9f1194c517bedbdbafae748786e",
"index": 5695,
"step-1": "S = input()\n\nT = []\nsen = [\"dream\", \"dreamer\", \"erase\", \"eraser\"]\ns_len = len(S)\n\n\nwhile len(T) <= s_len:\n ",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
from random import randint
#funções
def leialetra():
'''
=>Função para validar letras.
parm=msg: Recebe dados to tipo string sendo Ss ou Nn.
return: String de valor S.
'''
while True:
try:
msg = str(input('Deseja fazer uma pergunta? [s/n] ')).upper()[0]
e... | normal | {
"blob_id": "1fff681363c4c91c47c2818681a3f2f125dd8c83",
"index": 2022,
"step-1": "<mask token>\n\n\ndef leialetra():\n \"\"\"\n =>Função para validar letras.\n parm=msg: Recebe dados to tipo string sendo Ss ou Nn.\n return: String de valor S.\n \"\"\"\n while True:\n try:\n ... | [
2,
3,
4,
5,
6
] |
from flask import Flask, render_template, request
from distance import get_distance
app = Flask(__name__)
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
name = "World" if not name else name
return "Hello %s" % name
@app.route('/')
def index():
return render_template('index.html'... | normal | {
"blob_id": "05052e9ccbd076e71e9ec6148887ce7b82ed316d",
"index": 6256,
"step-1": "<mask token>\n\n\n@app.route('/hello')\n@app.route('/hello/<name>')\ndef hello(name=None):\n name = 'World' if not name else name\n return 'Hello %s' % name\n\n\n@app.route('/')\ndef index():\n return render_template('inde... | [
3,
4,
5,
6,
7
] |
'''
fibonacci(6) => [1, 1, 2, 3, 5, 8]
fibonacci(7) => [1, 1, 2, 3, 5, 8, 13]
'''
def fibonacci(n):
if n == 0:
return []
elif n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
lista = fibonacci(n-1)
suma = lista[len(lista)-1] + lista[len(lista)-2]
lista... | normal | {
"blob_id": "03062ea08bd6ad88376f7c2aa2c89d2194ed8b2e",
"index": 1074,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef fibonacci(n):\n if n == 0:\n return []\n elif n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n else:\n lista = fibonacci(n - 1)\n ... | [
0,
1,
2,
3,
4
] |
# This package includes different measures to evaluate topics
| normal | {
"blob_id": "3dcca85c8003b57ad37734bbbe171ab8cef0f56c",
"index": 1894,
"step-1": "# This package includes different measures to evaluate topics\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
1
]
} | [
1
] |
from sys import stdin
def get_time(d, sp, dists, i, d_old, sp_old):
if i == len(dists):
return 0
times = []
d_new = d[i]
sp_new = sp[i]
if d_new >= dists[i]:
res1 = get_time(d, sp, dists, i + 1, d_new - dists[i], sp_new)
if res1 is not None:
times.append(res1 + (... | normal | {
"blob_id": "3b99cc0eb163f4a94bc47429ad3627a6ecad4818",
"index": 2774,
"step-1": "from sys import stdin\n\ndef get_time(d, sp, dists, i, d_old, sp_old):\n if i == len(dists):\n return 0\n times = []\n d_new = d[i]\n sp_new = sp[i]\n if d_new >= dists[i]:\n res1 = get_time(d, sp, dist... | [
0
] |
import re
def parse_rule(rule):
elem_regex = re.compile("(\d+) (.*) bags?.*")
rule = rule[:-1]
color, inside = tuple(rule.split(" bags contain"))
result = []
for element in inside.split(","):
match = elem_regex.search(element)
if match:
result.append((match.gro... | normal | {
"blob_id": "730aaa0404a0c776ce4d3a351f292f90768b6867",
"index": 7781,
"step-1": "<mask token>\n\n\ndef get_neighbours(graph, v):\n return [color for color, _ in graph[v]]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_rule(rule):\n elem_regex = re.compile('(\\\\d+) (.*) bags?.*')\n rule... | [
1,
4,
5,
6,
7
] |
#!/usr/bin/python2
import requests ,optparse
def get_link():
parser=optparse.OptionParser()
parser.add_option("-l","--link",dest="url",help="direct link of file to download .pdf")
(url,argument)=parser.parse_args()
return url
def download(url):
try:
get_request=requests.get(url)
... | normal | {
"blob_id": "22ddae977afd2a1b0a729cf0d56783eaaca3b0a0",
"index": 9813,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_link():\n parser = optparse.OptionParser()\n parser.add_option('-l', '--link', dest='url', help=\n 'direct link of file to download .pdf')\n url, argument = pa... | [
0,
2,
3,
4,
6
] |
from collections import OrderedDict
import tcod.event
from components import Entity, PaperDoll, Brain
from components.enums import Intention
from engine import GameScene
from scenes.list_menu_scene import MenuAction, ListMenuScene
from systems.utilities import set_intention, retract_intention
def run(scene: GameS... | normal | {
"blob_id": "f1547e0893ce9c4661b546e49f3fc998745390d9",
"index": 4397,
"step-1": "<mask token>\n\n\ndef get_slots_query(scene: GameScene, entity: int):\n \"\"\"Return a query that resolves to entity's equipment slots and their equipped items.\"\"\"\n\n def query():\n paper_doll: PaperDoll = scene.cm... | [
2,
3,
4,
5,
6
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 13:34:46 2017
@author: Sven Geboers
"""
from math import pi,e
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def LevelToIntensity(NoiseLevelIndB):
I0 = 10.**(-12) #This is the treshold hearing intensity, matchin... | normal | {
"blob_id": "68a1d5a77abd19aece04bd560df121ceddccea42",
"index": 3179,
"step-1": "<mask token>\n\n\ndef LevelToIntensity(NoiseLevelIndB):\n I0 = 10.0 ** -12\n NoiseLevel = float(NoiseLevelIndB)\n Intensity = I0 * 10 ** (NoiseLevel / 10)\n return Intensity\n\n\ndef IntensityToLevel(Intensity):\n I0... | [
2,
3,
4,
5,
6
] |
"""""""""""""""
Write Data
"""""""""""""""
import json
from city import City
def load_json(file_name='data.json'):
with open(file_name, 'r') as json_fp:
json_data = json_fp.read()
data_arr = json.loads(json_data)
return data_arr
if __name__ == '__main__':
json_file = 'data.json'
... | normal | {
"blob_id": "63068a15d750abb29398d687495d6001ba17ab8a",
"index": 9435,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef load_json(file_name='data.json'):\n with open(file_name, 'r') as json_fp:\n json_data = json_fp.read()\n data_arr = json.loads(json_data)\n return data_arr... | [
0,
1,
2,
3,
4
] |
__author__ = 'Jager'
from char import Character
class Rouge (Character):
def special_attack1(self, opponent, hitdamage_callback, specatt_callback):
pass # hook method
def special_attack2(self, opponent, hitdamage_callback, specatt_callback):
pass # hook method
def heal(self, target... | normal | {
"blob_id": "36991c3191ba48b1b9dbd843e279f8fe124f1339",
"index": 73,
"step-1": "<mask token>\n\n\nclass Rouge(Character):\n\n def special_attack1(self, opponent, hitdamage_callback, specatt_callback):\n pass\n\n def special_attack2(self, opponent, hitdamage_callback, specatt_callback):\n pass... | [
5,
6,
7,
8,
9
] |
data = [] ##用來裝reviews.txt的留言
count = 0 ##計數目前檔案讀取到第幾筆
with open('reviews.txt', 'r') as f:
for line in f:
data.append(line)
count += 1
if count % 1000 == 0:
print(len(data))
total = len(data)
print('檔案讀取完了,總共有', len(data), '筆資料')
print(len(data)) #印出data串列的--項目數量
print(le... | normal | {
"blob_id": "835beebe452a252fb744a06d3e6ff221469af6bf",
"index": 6699,
"step-1": "data = [] ##用來裝reviews.txt的留言\ncount = 0 ##計數目前檔案讀取到第幾筆\n\nwith open('reviews.txt', 'r') as f:\n for line in f:\n data.append(line)\n count += 1\n if count % 1000 == 0:\n print(len(data))\ntotal... | [
0
] |
import grpc
import time
import json
import sys
import uuid
from arch.api.proto import inference_service_pb2
from arch.api.proto import inference_service_pb2_grpc
import threading
def run(address):
ths = []
with grpc.insecure_channel(address) as channel:
for i in range(1):
th = threading.T... | normal | {
"blob_id": "5430e1861a6244c25c00699323efa0921a5af940",
"index": 3709,
"step-1": "<mask token>\n\n\ndef run(address):\n ths = []\n with grpc.insecure_channel(address) as channel:\n for i in range(1):\n th = threading.Thread(target=send, args=(channel,))\n ths.append(th)\n ... | [
2,
3,
4,
5,
6
] |
import weakref
from enum import Enum
from functools import partial
from typing import TYPE_CHECKING
import inflection
if TYPE_CHECKING:
from stake.client import StakeClient
camelcase = partial(inflection.camelize, uppercase_first_letter=False)
__all__ = ["SideEnum"]
class SideEnum(str, Enum):
BUY = "B"
... | normal | {
"blob_id": "f13ccbfb27788deca0d4f4b58a4e9e8c7e8e0306",
"index": 1644,
"step-1": "<mask token>\n\n\nclass SideEnum(str, Enum):\n BUY = 'B'\n SELL = 'S'\n\n\nclass BaseClient:\n\n def __init__(self, client: 'StakeClient'):\n self._client = weakref.proxy(client)\n",
"step-2": "<mask token>\nif TY... | [
4,
5,
6,
7,
8
] |
from typing import List, Callable
#: A list of int
T = List[int]
C = Callable[[int], None] # a generic alias not having a doccomment
| normal | {
"blob_id": "aaee69d339cf1c14e54366633155ee57026e6487",
"index": 2071,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nT = List[int]\nC = Callable[[int], None]\n",
"step-3": "from typing import List, Callable\nT = List[int]\nC = Callable[[int], None]\n",
"step-4": "from typing import List, Callable\n\... | [
0,
1,
2,
3
] |
from django.contrib.auth.models import User
from django_filters import (
NumberFilter,
DateTimeFilter,
AllValuesFilter
)
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import permissions
from rest_framework.throttling import ScopedRateThrottle
fr... | normal | {
"blob_id": "2908d34165fac272c9571be623855a0613c952f3",
"index": 5433,
"step-1": "<mask token>\n\n\nclass GameList(ListCreateAPIView):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def perform_create(self, serializer):\n ... | [
18,
25,
26,
27,
28
] |
import sys
from PIL import Image
from pr_common import *
file_name = sys.argv[1]
saturation_color = sys.argv[2]
saturation_modifier = int(sys.argv[3])
img = getImage(file_name)
pixels = pixelValues(img)
for i in range(img.height):
for j in range(img.width):
pixel_val = pixels[i][j]
color_idx = No... | normal | {
"blob_id": "96ef95d8997eeab3d85a1bb6e4f8c86c9bfbb0a2",
"index": 4732,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(img.height):\n for j in range(img.width):\n pixel_val = pixels[i][j]\n color_idx = None\n if saturation_color == 'R':\n color_idx = 0\n ... | [
0,
1,
2,
3,
4
] |
from nltk.stem.porter import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
p_stemmer = PorterStemmer()
s_stemmer = SnowballStemmer(language="english")
print(s_stemmer.stem("writing"))
| normal | {
"blob_id": "67e6d39ef291e4bb30c0b6bab7b71d97c86b0ef1",
"index": 4108,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(s_stemmer.stem('writing'))\n",
"step-3": "<mask token>\np_stemmer = PorterStemmer()\ns_stemmer = SnowballStemmer(language='english')\nprint(s_stemmer.stem('writing'))\n",
"step-... | [
0,
1,
2,
3,
4
] |
import json
import paho.mqtt.client as mqtt
from datetime import datetime
import ssl
from collections import OrderedDict
import time
from tkinter import *
import numpy as np
MQTT_IP = 'emq'
MQTT_PORT = 8883
username = "spread_ICAM"
password = "spread_ICAM"
deviceType = "spread_ICAM"
version = "v1"
def on_connect(cli... | normal | {
"blob_id": "f3664f5f69207c3f2dcec96c90cd220003da0904",
"index": 4142,
"step-1": "<mask token>\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection re... | [
2,
3,
5,
6,
7
] |
# def test_categories:
# ["5S", "5H", "5D", "4S", "4H", "4D", "3D", "3S"]
import unittest
from poker import Hand, makeCard, Rank, count_ranks, RankCount, max_straight
class TestHand(unittest.TestCase):
# def test_heap_multiples(self):
# heaped_multiples = Hand.heap_multiples({"J":4, "2":3})
# prin... | normal | {
"blob_id": "5b8d1bd026e97bb7508a500048f940abf0253471",
"index": 9698,
"step-1": "<mask token>\n\n\nclass TestHand(unittest.TestCase):\n\n def test_max_straight(self):\n cards = map(makeCard, ['10S', '6S', '9S', '8S', '7S'])\n straight = max_straight(cards)\n self.assertEqual(straight, so... | [
5,
6,
7,
8,
9
] |
"""Utilties to access a column and one field of a column if the column is composite."""
from typing import TYPE_CHECKING, Optional
from greenplumpython.db import Database
from greenplumpython.expr import Expr
from greenplumpython.type import DataType
if TYPE_CHECKING:
from greenplumpython.dataframe import DataFra... | normal | {
"blob_id": "a52edeec62a6849bda7e5a5481fb6e3d7d9a4c6a",
"index": 8571,
"step-1": "<mask token>\n\n\nclass Column(Expr):\n \"\"\"\n Inherited from :class:`~expr.Expr`.\n\n Representation of a Python object :class:`~col.Column`.\n \"\"\"\n\n def __init__(self, name: str, dataframe: 'DataFrame') ->No... | [
6,
9,
10,
12,
13
] |
import micropython
# viper function taking and returning ints
@micropython.viper
def viper_int(x:int, y:int) -> int:
return x + y + 3
print(viper_int(1, 2))
# viper function taking and returning objects
@micropython.viper
def viper_object(x:object, y:object) -> object:
return x + y
print(viper_obj... | normal | {
"blob_id": "eec52695e5afcc21e5fed6453e96cc3a58e7c1df",
"index": 101,
"step-1": "<mask token>\n\n\n@micropython.viper\ndef viper_int(x: int, y: int) ->int:\n return x + y + 3\n\n\n<mask token>\n\n\n@micropython.viper\ndef viper_local(x: int) ->int:\n y = 4\n return x + y\n\n\n<mask token>\n\n\n@micropyt... | [
9,
10,
12,
14,
15
] |
#!/usr/bin/python
def sumbelow(n):
multiples_of_3 = set(range(0,n,3))
multiples_of_5 = set(range(0,n,5))
return sum(multiples_of_3.union(multiples_of_5))
#one linear:
# return sum(set(range(0,n,3)).union(set(range(0,n,5)))),
# or rather,
# return sum(set(range(0,n,3) + range(0,n,5)))
if __name__ == '__ma... | normal | {
"blob_id": "8dbc0b9b80aae4cb5c4101007afc50ac54f7a7e7",
"index": 5873,
"step-1": "#!/usr/bin/python\n\ndef sumbelow(n):\n multiples_of_3 = set(range(0,n,3))\n multiples_of_5 = set(range(0,n,5))\n return sum(multiples_of_3.union(multiples_of_5))\n\n#one linear:\n# return sum(set(range(0,n,3)).union(set(r... | [
0
] |
text = "I love Python Programming"
for word in text.split():
print(word) | normal | {
"blob_id": "fdc8f9ff9a0e2cd8ad1990948036d9e420fdc074",
"index": 4216,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor word in text.split():\n print(word)\n",
"step-3": "text = 'I love Python Programming'\nfor word in text.split():\n print(word)\n",
"step-4": "text = \"I love Python Programm... | [
0,
1,
2,
3
] |
# -*- coding:utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
import experiment
class Node(QtGui.QGraphicsEllipseItem):
def __init__(self,name):
super(Node, self).__init__()
self.__name = name
def getName(self):
... | normal | {
"blob_id": "edbb721784dff81e3e1ab5e0458a4080508807fe",
"index": 4335,
"step-1": "<mask token>\n\n\nclass Text(QtGui.QGraphicsTextItem):\n <mask token>\n\n def getName(self):\n return self.__name\n\n\nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n ... | [
18,
20,
23,
25,
32
] |
from random import randint
#given a list of names, cities and neigborhoods, generate a client table.
#------------------------MODEL------------------------------
#([cliente_id], [nome], [sexo], [telefone], [cpf], [cidade_nome], [cidade_bairro_nome], [cidade_bairro_cep])
class Employee:
def __init__(self, id, name ,s... | normal | {
"blob_id": "a9ce341ffe26ab6c476237030e23e6ae57b8fa33",
"index": 7560,
"step-1": "from random import randint\n\n#given a list of names, cities and neigborhoods, generate a client table.\n\n#------------------------MODEL------------------------------\n#([cliente_id], [nome], [sexo], [telefone], [cpf], [cidade_nom... | [
0
] |
class Day8MemoryManeuver:
def __init__(self, use_reference_count=False):
"""
Args:
use_reference_count (bool):
True: If an entry has child nodes, the meta data are referring to the results of
the child node
False: Sum all meta data up
... | normal | {
"blob_id": "84d096a51fa052ee210e975ab61c0cbbf05bc5ae",
"index": 8358,
"step-1": "class Day8MemoryManeuver:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Day8MemoryManeuver:\n <mask token>\n <mask token>\n\n def _solve(self, structure, pos):\n if pos >= len(structur... | [
1,
2,
3,
4,
5
] |
from pandas_datareader import data as pdr
from datetime import date
class YahooHelper:
"""
Class to fetch Yahoo data
"""
def __init__(self):
"""
Default constructor which initiates object
"""
pass
def get_data(self, symbol):
"""
Function to collect... | normal | {
"blob_id": "b4b4dad5cf630dc1a627e323ea63577583d1e1c3",
"index": 1551,
"step-1": "<mask token>\n\n\nclass YahooHelper:\n <mask token>\n\n def __init__(self):\n \"\"\"\n Default constructor which initiates object\n \"\"\"\n pass\n <mask token>\n\n def get_stock_data(symbol)... | [
4,
5,
6,
7,
8
] |
from mtots.parser import base
from mtots.parser import combinator
from mtots.parser.combinator import All
from mtots.parser.combinator import Any
from mtots.parser.combinator import AnyTokenBut
from mtots.parser.combinator import Forward
from mtots.parser.combinator import Peek
from mtots.parser.combinator import Requi... | normal | {
"blob_id": "f9edbef46494cc2993c6a633fe35406524dbbf67",
"index": 1199,
"step-1": "<mask token>\n",
"step-2": "from mtots.parser import base\nfrom mtots.parser import combinator\nfrom mtots.parser.combinator import All\nfrom mtots.parser.combinator import Any\nfrom mtots.parser.combinator import AnyTokenBut\nfr... | [
0,
1
] |
# Generated by Django 3.0.4 on 2020-04-04 11:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('product', '0003_cost'),
... | normal | {
"blob_id": "a4f2ca3155f2bb4c17be5bb56dd889abb5d20293",
"index": 3791,
"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 = [migrations.sw... | [
0,
1,
2,
3,
4
] |
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
ln=len(nums)
k=k%ln
nums[:]=nums+nums[:ln-k]
del nums[0:ln-k]
#menthod 2自己输入[1,2],k=... | normal | {
"blob_id": "a3ccd526b70db2061566274852a7fc0c249c165a",
"index": 6931,
"step-1": "class Solution(object):\n def rotate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n ln=le... | [
0
] |
#---------------------------------------------
# File name: phase2app.py
# Description: Launches GUI for Twitter User Timeline Sentiment Analysis program
# Author: Gilbert Yap (gilberty@bu.edu)
# Date: October 03, 2020
#---------------------------------------------
from PySide2.QtWidgets import QApplication, QDialog, ... | normal | {
"blob_id": "8cabacb64f3b193b957c61d6e1ca21f2046e52d1",
"index": 8199,
"step-1": "<mask token>\n\n\nclass Ui_Window(QDialog):\n\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n regex = QRegExp('\\\\w+')\n validator =... | [
9,
11,
12,
13,
14
] |
# -*- coding:utf-8 -*-
import datetime
import json
import os
import urllib
import requests
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import properties
from time import sleep
from appium import we... | normal | {
"blob_id": "2465a73d958d88dcd27cfac75a4e7b1fcd6a884e",
"index": 3389,
"step-1": "<mask token>\n\n\ndef logPrint(logstr):\n pyfileName = str(__file__).split('.py')[0].split('/')[-1]\n filepath = '.\\\\log\\\\' + pyfileName + '-runlog.log'\n now = str(datetime.datetime.now())\n logstr = now + ' ' + lo... | [
4,
5,
7,
8,
9
] |
from utils import *
from wordEmbedding import *
print("bat dau")
def predict(text, phobert, tokenizer):
model = load_model('model.h5')
X_test = word2vec(text, phobert, tokenizer)
x_test_tensor = tf.convert_to_tensor(X_test)
X_tests = []
X_tests.append(x_test_tensor)
X_tests = tf.convert_to_t... | normal | {
"blob_id": "d2c9ee64472c74767812d842d2c49eec962e28c6",
"index": 4451,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef predict(text, phobert, tokenizer):\n model = load_model('model.h5')\n X_test = word2vec(text, phobert, tokenizer)\n x_test_tensor = tf.convert_to_tensor(X_test)\n X_te... | [
0,
1,
2,
3,
4
] |
import base64
import string
def hexStringtoBytes(hexstring):
byteArray = bytes.fromhex(hexstring)
return byteArray
def xorBytes(bytes1, bytes2):
xored = bytes([x^bytes2[i] for i,x in enumerate(bytes1)])
return xored
def xorAgainstCharacter(byteArray, character):
str2 = [ord(character)] ... | normal | {
"blob_id": "a32fb683f8d46f901e8dcd2d075ace22ee81e076",
"index": 451,
"step-1": "<mask token>\n\n\ndef hexStringtoBytes(hexstring):\n byteArray = bytes.fromhex(hexstring)\n return byteArray\n\n\ndef xorBytes(bytes1, bytes2):\n xored = bytes([(x ^ bytes2[i]) for i, x in enumerate(bytes1)])\n return xo... | [
3,
4,
5,
6,
7
] |
import mechanicalsoup
from bs4 import BeautifulSoup
import re
import json
def extract_title(page):
return page.find("header").find("h1").contents[0]
def extract_colours(page):
color_list = page.find("ul")
return list(dict.fromkeys(re.findall("#\w+", str(color_list.contents))))
def get_colours_from_pa... | normal | {
"blob_id": "9fd33089a9dc919ef2fb2698059e60a24a0e05e6",
"index": 6118,
"step-1": "<mask token>\n\n\ndef extract_title(page):\n return page.find('header').find('h1').contents[0]\n\n\ndef extract_colours(page):\n color_list = page.find('ul')\n return list(dict.fromkeys(re.findall('#\\\\w+', str(color_list... | [
5,
6,
7,
8,
9
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.