code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
# -*- coding: utf-8 -*- ''' Created on 2014/07/24 @author: seigo ''' from google.appengine.api import users from google.appengine.ext import webapp from MyModel import HistoricalTable, PollRating, Government from datetime import datetime hts = [["2014/7/1","集団的自衛権行使容認の閣議決定","http://www.47news.jp/47topics/e/254919.ph...
normal
{ "blob_id": "b8957acb71d435a93b4397a24d3b5cf4b2a817f8", "index": 2602, "step-1": "<mask token>\n\n\nclass initDATA(webapp.RequestHandler):\n <mask token>\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri)...
[ 4, 5, 6, 7, 8 ]
def merge(items, temp, low, mid, high): i = low j = mid + 1 for k in range(low, high+1): if i > mid: # 왼쪽 리스트의 순회를 마쳤음 # 남은 오른쪽 리스트의 원소들은 모두 왼쪽 리스트 원소보다 작음 temp[k] = items[j] # 뒤에 나머지는 정렬되어있으니 그대로 넣기 j += 1 elif j > high: ...
normal
{ "blob_id": "9ab119b32ceac370b744658e5fa679292609373a", "index": 2517, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef merge_sort(items, temp, low, high):\n if high <= low:\n return None\n mid = low + (high - low) // 2\n merge_sort(items, temp, low, mid)\n merge_sort(items, temp...
[ 0, 1, 2, 3, 4 ]
def format_amount(a): return a.replace(",","").strip().replace("%","").replace("$","") def create_json(gdp, coords): # ------------ Split gdp data ------------ # line_list=gdp.split('\n') column_list = [x.split('\t') for x in line_list if x!=""] # ------------ Split coord data ------------ # line_list=coords.s...
normal
{ "blob_id": "1cbc37655e28ab3082fc31baf119cb2bab96379b", "index": 3661, "step-1": "def format_amount(a):\n return a.replace(',', '').strip().replace('%', '').replace('$', '')\n\n\n<mask token>\n", "step-2": "def format_amount(a):\n return a.replace(',', '').strip().replace('%', '').replace('$', '')\n\n\nd...
[ 1, 3, 4, 5, 6 ]
import krait from ctrl import ws krait.mvc.set_init_ctrl(ws.WsPageController())
normal
{ "blob_id": "da2b946238b429188fe3fa50286658d4b5cdbf41", "index": 5752, "step-1": "<mask token>\n", "step-2": "<mask token>\nkrait.mvc.set_init_ctrl(ws.WsPageController())\n", "step-3": "import krait\nfrom ctrl import ws\nkrait.mvc.set_init_ctrl(ws.WsPageController())\n", "step-4": null, "step-5": null, ...
[ 0, 1, 2 ]
def maths(num): int(num) if num % 5 == 0 and num % 3 == 0: print("bizzfizz") elif num % 3 == 0: print("fizz") elif num % 5 == 0: print("bizz") else: print(num) value=input("enter the value ") maths(int(value))
normal
{ "blob_id": "91f83adbe01e2d8070f9286031b77eae71beb83e", "index": 1107, "step-1": "<mask token>\n", "step-2": "def maths(num):\n int(num)\n if num % 5 == 0 and num % 3 == 0:\n print('bizzfizz')\n elif num % 3 == 0:\n print('fizz')\n elif num % 5 == 0:\n print('bizz')\n else:\...
[ 0, 1, 2, 3, 4 ]
"""Testing data storage functionality in gludb.simple (see simple_tests.py for testing of the rest of gludb.simple functionality)""" import unittest import datetime import time import gludb.config from gludb.versioning import VersioningTypes from gludb.data import orig_version from gludb.simple import DBObject, Fiel...
normal
{ "blob_id": "7383ae97d6a1368896d05d0cafc9846c24004701", "index": 2690, "step-1": "<mask token>\n\n\nclass DefaultStorageTesting(unittest.TestCase):\n\n def setUp(self):\n gludb.config.default_database(gludb.config.Database('sqlite',\n filename=':memory:'))\n SimpleStorage.ensure_table...
[ 16, 21, 24, 25, 28 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Check mean system norm errors in regression tests This script determines the pass/fail status of a regression test by comparing the "Mean System Norm" values output at each timestep against "gold values" from the reference file provided by the user. Success is deter...
normal
{ "blob_id": "d03669924233edf33fcb6645f5ed7ab118f54a95", "index": 7610, "step-1": "<mask token>\n\n\ndef load_norm_file(fname):\n \"\"\"Parse the norm file and return the mean system norms\"\"\"\n try:\n with open(fname, 'r') as fh:\n lines = fh.readlines()\n norms = [float(ll.s...
[ 5, 6, 7, 8, 9 ]
import sys from collections import deque t = int(sys.stdin.readline().rstrip()) for _ in range(t): n, m = map(int, sys.stdin.readline().split()) q = deque(map(int, sys.stdin.readline().split())) count = 0 while q: highest = max(q) doc = q.popleft() m -= 1 if doc != highes...
normal
{ "blob_id": "a571abd88184c8d8bb05245e9c3ce2e4dabb4c09", "index": 615, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _ in range(t):\n n, m = map(int, sys.stdin.readline().split())\n q = deque(map(int, sys.stdin.readline().split()))\n count = 0\n while q:\n highest = max(q)\n ...
[ 0, 1, 2, 3 ]
import itertools def permutations(string): return list("".join(p) for p in set(itertools.permutations(string)))
normal
{ "blob_id": "3d49d03dbc38ee37eadd603b4b464b0e2e1a33d5", "index": 5280, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef permutations(string):\n return list(''.join(p) for p in set(itertools.permutations(string)))\n", "step-3": "import itertools\n\n\ndef permutations(string):\n return list('...
[ 0, 1, 2, 3 ]
from PIL import Image from pdf2image import convert_from_path import glob from pathlib import Path import shutil, os from docx import Document import fnmatch import re import shutil def find_files_ignore_case(which, where='.'): '''Returns list of filenames from `where` path matched by 'which' shell patter...
normal
{ "blob_id": "a9876c61578a53f29865062c0915db622aaaba72", "index": 6916, "step-1": "<mask token>\n\n\ndef crop_image_center(file, crop_left, crop_right, crop_top, crop_bottom):\n img = Image.open(file)\n x, y = img.size\n box = (crop_left, crop_top, x - crop_left - crop_right, y - crop_top -\n crop...
[ 4, 6, 7, 8, 9 ]
#downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py import os, openpyxl, time, shutil from selenium import webdriver from selenium.webdriver.common.keys import Keys wb = openpyxl.load_workbook('ProjectSummary.xlsx') sheet = wb.active browser = webdri...
normal
{ "blob_id": "6e9fd8ee2a187888df07c9dd1c32fe59a111c869", "index": 8823, "step-1": "<mask token>\n\n\ndef pdfToFolder(projectName):\n os.chdir('/home/gmclaughlin/Downloads')\n if projectName.find('DEM') != -1:\n shutil.move('/home/gmclaughlin/Downloads/Detail Report - Basic.pdf',\n \n ...
[ 1, 2, 3, 4, 5 ]
import hashlib import json import logging import os import urllib.parse import uuid from datetime import datetime import pytz from celery import states as celery_states from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager ...
normal
{ "blob_id": "32e904a39d03d3166369420b49db0b9b118110a3", "index": 4179, "step-1": "<mask token>\n\n\nclass ContentKind(models.Model):\n <mask token>\n\n def __str__(self):\n return self.kind\n\n\nclass FileFormat(models.Model):\n extension = models.CharField(primary_key=True, max_length=40, choice...
[ 65, 102, 158, 169, 216 ]
import osfrom setuptools import setup def read(fname): with open(fname) as fhandle: return fhandle.read() def readMD(fname): # Utility function to read the README file. full_fname = os.path.join(os.path.dirname(__file__), fname) if 'PANDOC_PATH' in os.environ: import pandoc pandoc.core.PANDOC_PATH = os.enviro...
normal
{ "blob_id": "7b18c967cf50d87b089dc22f3fbe6d40d708483f", "index": 8441, "step-1": "import osfrom setuptools import setup\ndef read(fname): with open(fname) as fhandle: return fhandle.read()\ndef readMD(fname): # Utility function to read the README file. full_fname = os.path.join(os.path.dirname(__file__), fnam...
[ 0 ]
from collections import defaultdict def solve(n, seq): flag = True # slot = [0] * (n + 10) freq = defaultdict() # refer to next free slot i = 1 p = len(seq) j = 0 while j < p: c = seq[j] if i > n: flag = False break if c in freq.keys(): ...
normal
{ "blob_id": "89b03bb5ca86e426459e23866f86f8770e4a1613", "index": 3420, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef solve(n, seq):\n flag = True\n freq = defaultdict()\n i = 1\n p = len(seq)\n j = 0\n while j < p:\n c = seq[j]\n if i > n:\n flag = Fals...
[ 0, 2, 3, 4, 5 ]
""" Writes day of the week and time to a file. Script written for crontab tutorial. Author: Jessica Yung 2016 """ import time filename = "record_time.txt" # Records time in format Sun 10:00:00 current_time = time.strftime('%a %H:%M:%S') # Append output to file. 'a' is append mode. with open(filename, 'a') as hand...
normal
{ "blob_id": "1f0695f0e9745912d8ee3a87e6c9b1272e9ebbae", "index": 218, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open(filename, 'a') as handle:\n handle.write(str(current_time))\n handle.write('\\n')\n", "step-3": "<mask token>\nfilename = 'record_time.txt'\ncurrent_time = time.strftime(...
[ 0, 1, 2, 3, 4 ]
""" Batch viewset Viewset to batch serializer """ # Django Rest Framework from rest_framework import viewsets # Inventory models from apps.inventory.models import Batch # Inventory serializers from apps.inventory.serializers import BatchSerializer class BatchViewSet(viewsets.ModelViewSet): """ Batch views...
normal
{ "blob_id": "3d0fe0c11e62a03b4701efb19e1c15272ccc985e", "index": 3315, "step-1": "<mask token>\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n <mask token>\n <mask token>\n <mask token>\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic ...
[ 2, 3, 4, 5, 6 ]
# USAGE # python predict_video.py --model model/activity.model --label-bin model/lb.pickle --input example_clips/lifting.mp4 --output output/lifting_128avg.avi --size 128 # python predict_video.py --model model/road_activity.model --label-bin model/rd.pickle --input example_clips/fire_footage.mp4 --ou # tput output/fir...
normal
{ "blob_id": "ccfcc5b644d592090786ceb35a85124c9d3275ad", "index": 5719, "step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return render_template('Main_page.html')\n\n\n@app.route('/prediction.html')\ndef predict():\n return render_template('prediction.html')\n\n\n@app.route('/About_us.html')\ndef...
[ 4, 5, 6, 7, 8 ]
#! /usr/bin/python2 # Copyright 2007 John Kasunich and Jeff Epler # # modified by Rudy du Preez to fit with the kinematics component pumakins.c # Note: DH parameters in pumakins halfile should bet set to # A2=400, A3=50, D3=100, D4=400, D6=95 # # z | # ...
normal
{ "blob_id": "ae83a0e1ebf1190ab55459563bc7b86d240de89a", "index": 4146, "step-1": "<mask token>\n", "step-2": "<mask token>\nc.newpin('joint1', hal.HAL_FLOAT, hal.HAL_IN)\nc.newpin('joint2', hal.HAL_FLOAT, hal.HAL_IN)\nc.newpin('joint3', hal.HAL_FLOAT, hal.HAL_IN)\nc.newpin('joint4', hal.HAL_FLOAT, hal.HAL_IN)\...
[ 0, 1, 2, 3, 4 ]
from django import forms from django.conf import settings class SurveyFeedback(forms.Form): CHOICES = [('Very Satisfied', 'Very Satisfied'), ('Satisfied', 'Satisfied'), ('Neither', 'Neither'), ('Dissatisfied', 'Dissatisfied'), ('Very Dissatisfied', 'Very Dissatisfied')] radioFeedback = forms.C...
normal
{ "blob_id": "a9b7abaaaa811cf12a15def1f2dd21f95bac3d62", "index": 6310, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass SurveyFeedback(forms.Form):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass SurveyFeedback(forms.Form):\n CHOICES = [('Very Sat...
[ 0, 1, 2, 3 ]
from cancion import * class NodoLista: def __init__(self, cancion, s, a): self.elemento = cancion self.siguiente = s self.anterior = a
normal
{ "blob_id": "1fb3904d48905ade8f83b6e052057e80302ec5a7", "index": 4253, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass NodoLista:\n <mask token>\n", "step-3": "<mask token>\n\n\nclass NodoLista:\n\n def __init__(self, cancion, s, a):\n self.elemento = cancion\n self.siguien...
[ 0, 1, 2, 3 ]
def solution(citations): # 사이테이션을 정렬 citations.sort() # for i in range(len(citations)): if citations[i] >= len(citations) - i: return len(citations)-i print(solution([3,0,6,1,5]))
normal
{ "blob_id": "0b3d6339faf9d66d4e1338599e4784fac0f63d3f", "index": 5310, "step-1": "<mask token>\n", "step-2": "def solution(citations):\n citations.sort()\n for i in range(len(citations)):\n if citations[i] >= len(citations) - i:\n return len(citations) - i\n\n\n<mask token>\n", "step-...
[ 0, 1, 2, 3 ]
import pyttsx3 import pyglet import time import logging import os from gtts import gTTS ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) class GoogleTTS: def utter_voice_message(self, message): try: # Google Text-to-Speech API - needs internet connectivity #filename = ROOT_D...
normal
{ "blob_id": "9ed674513bebe65ece538e9ce2b3945bb0c532cc", "index": 1357, "step-1": "<mask token>\n\n\nclass GoogleTTS:\n <mask token>\n\n def check_google_connection(self):\n try:\n message = 'Hallo'\n filename = 'temp_voice.mp3'\n tts = gTTS(text=message, lang='de')\n...
[ 5, 7, 8, 9, 10 ]
from django.db import models from .data import REGISTER_TYPE_CHOICES from .data import ENTRANCE_TYPE from .data import EXPENSE_TYPE class EstheticHouse(models.Model): name = models.CharField( verbose_name='nombre', max_length=512, unique=True, ) def __str__(self): return ...
normal
{ "blob_id": "df25b51010fdbcbf1a8949a7a755a3a982bbf648", "index": 6352, "step-1": "<mask token>\n\n\nclass Employee(models.Model):\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n ordering = ['name']\n verbose_name = 'Em...
[ 7, 8, 18, 19, 20 ]
import paho.mqtt.client as paho import RPi.GPIO as GPIO import json, time, math import clearblade from clearblade import auth from clearblade import Client from urlparse import urlparse #Fill init values systemKey = ______ secretKey = ______ userName = _______ userPW = _______ edgeIP = "http://_______:9000" auth = au...
normal
{ "blob_id": "299d13fbcdb75673026db1e3a0352c8b19d453c1", "index": 6314, "step-1": "import paho.mqtt.client as paho\nimport RPi.GPIO as GPIO\nimport json, time, math\nimport clearblade\nfrom clearblade import auth\nfrom clearblade import Client\nfrom urlparse import urlparse\n\n#Fill init values\nsystemKey = _____...
[ 0 ]
# -*- coding: utf-8 -*- """Template parser for Faker""" from datetime import datetime from jinja2 import Template from faker import Faker from faker.providers.internet import Provider as InternetProvider from ..providers.file_data_source_provider import FileDataSourceProvider from ..providers.numbers_provider import Nu...
normal
{ "blob_id": "38f9cddfde4787ead2314fc70c1f4d91a3da9687", "index": 1307, "step-1": "<mask token>\n\n\nclass TemplateParser:\n <mask token>\n <mask token>\n\n def __init__(self, template=None, providers=None, date_generator=None):\n self.fake = Faker()\n self.fake.add_provider(FileDataSourceP...
[ 3, 4, 6, 7, 8 ]
# encoding: utf-8 # -*- coding: utf-8 -*- """ The flask application package. """ #parse arguments from flask import Flask from flask_cors import CORS import argparse parser = argparse.ArgumentParser() parser.add_argument('-t', '--testing', action='store_true') #to use the testing database parser.add_argument('-i', ...
normal
{ "blob_id": "e403a84ec2a3104cb908933f6949458cccc791c3", "index": 4737, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('-t', '--testing', action='store_true')\nparser.add_argument('-i', '--init', action='store_true')\nparser.add_argument('-r', '--reinit', action='store_true')\n<mask to...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ...
normal
{ "blob_id": "923a433a3a04a8538b43d162d17d379daab4698a", "index": 7753, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nasync def sound(cube):\n sound = bytearray()\n sound.append(2)\n sound.append(9)\n sound.append(255)\n await cube.write_gatt_char(TOIO_SOUND_UUID, sound)\n\n\nasync def...
[ 0, 1, 2, 3, 4 ]
''' syntax of if-elif-else if <condition> : code to be executed in this condition elif <new condition> : cdode tbd some code else : code runs in the else condigtion this can all be multiline code ''' a = 3 b = 2 if a == b : print "Values are equal" elif a < b : print "a is less than b" else: print "b...
normal
{ "blob_id": "d7ce6efa72c9b65d3dd3ce90f9d1f2dd8a889d26", "index": 444, "step-1": "\n'''\nsyntax of if-elif-else\n\nif <condition> :\n\tcode to be\n\texecuted in\n\tthis condition\nelif <new condition> :\n\tcdode tbd\n\tsome code\nelse :\n\tcode runs in the else condigtion\n\tthis can all be multiline code\n\n'''\...
[ 0 ]
#!/usr/bin/env python3 import operator from functools import reduce import music21 def get_top_line(piece): top_part = piece.parts[0] if len(top_part.voices) > 0: top_part = top_part.voices[0] # replace all chords with top note of chord for item in top_part.notes: if isinstance(item...
normal
{ "blob_id": "92ee66565eb1d0e3cd8fa1ec16747f15e0d92be8", "index": 2885, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_notes(piece):\n part = piece.parts[0]\n measures = filter(lambda x: isinstance(x, music21.stream.Measure), part\n .elements)\n notes = reduce(operator.add, map...
[ 0, 1, 2, 3, 4 ]
def ip_address(address): new_address = "" split_address = address.split(".") seprator = "[.]" new_address = seprator.join(split_address) return new_address if __name__ == "__main__": ipaddress = ip_address("192.168.1.1") print(ipaddress)
normal
{ "blob_id": "7ef62e5545930ab13312f8ae1ea70a74386d8bfa", "index": 1231, "step-1": "<mask token>\n", "step-2": "def ip_address(address):\n new_address = ''\n split_address = address.split('.')\n seprator = '[.]'\n new_address = seprator.join(split_address)\n return new_address\n\n\n<mask token>\n"...
[ 0, 1, 2, 3 ]
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if not head: return head fh = List...
normal
{ "blob_id": "c234031fa6d43c19515e27c5b12f8e8338f24a1c", "index": 6412, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def insertionSortList(self, head):\n if not head:\n return head\n fh = ListNode(0)\n fh.next = ...
[ 0, 1, 2, 3 ]
from xml.dom import minidom import simplejson as json import re camel_split = re.compile(r'(^[a-z]+|[A-Z][a-z]+|[a-z0-9]+)') def get_items(xml): for obj_node in xml.getElementsByTagName('item'): obj = dict(obj_node.attributes.items()) if 'name' in obj: obj['title'] = (' '.join(camel_sp...
normal
{ "blob_id": "69a3471ee8d2c317264b667d6ae0f9b500c6222f", "index": 6497, "step-1": "from xml.dom import minidom\nimport simplejson as json\nimport re\n\ncamel_split = re.compile(r'(^[a-z]+|[A-Z][a-z]+|[a-z0-9]+)')\n\ndef get_items(xml):\n for obj_node in xml.getElementsByTagName('item'):\n obj = dict(obj...
[ 0 ]
from abc import ABCMeta, abstractmethod __author__ = 'Alexiy' class Protocol: """base protocol class""" __metaclass__ = ABCMeta FAIL = 'Failed' @abstractmethod def execute(self, command): """"execute command method""" class LocalProtocol(Protocol): """simple protocol for using bots ...
normal
{ "blob_id": "8d1067a9bb0629276ef27de91f63cf2370a44e24", "index": 1369, "step-1": "<mask token>\n\n\nclass Protocol:\n <mask token>\n <mask token>\n <mask token>\n\n @abstractmethod\n def execute(self, command):\n \"\"\"\"execute command method\"\"\"\n\n\nclass LocalProtocol(Protocol):\n ...
[ 6, 7, 8, 11 ]
import struct class H264Packet: UNKNOWN_TYPE, I_HDR, P_HDR, B_HDR, I_DATA, P_DATA, B_DATA = range(7) def __init__(self, packet): self.packet = packet self.type = None self.data = None if len(packet) > 3: (self.type,) = struct.unpack('H', packet[0:2]) self.data = packet[2:] def serialize(self): r...
normal
{ "blob_id": "ff1db5981a0163df1dfb44869a3d4af2be03c10a", "index": 2745, "step-1": "<mask token>\n\n\nclass H264Packet:\n <mask token>\n\n def __init__(self, packet):\n self.packet = packet\n self.type = None\n self.data = None\n if len(packet) > 3:\n self.type, = struc...
[ 4, 5, 6, 7, 8 ]
import time import numpy as np import matplotlib.pyplot as plt import cv2 import matplotlib.image as mpimg import random import skimage import scipy from PIL import Image def readimg(dirs, imgname): img = cv2.imread(dirs + imgname) img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) return img def readimg_color(d...
normal
{ "blob_id": "e08ab06be0957e5e173df798742abc493eac84d0", "index": 6006, "step-1": "<mask token>\n\n\ndef readimg(dirs, imgname):\n img = cv2.imread(dirs + imgname)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n return img\n\n\ndef readimg_color(dirs, imgname):\n img = cv2.imread(dirs + imgname)\n ...
[ 9, 11, 14, 15, 16 ]
import falcon import json from sqlalchemy.exc import SQLAlchemyError from db import session import model import util class AchievementGrant(object): def on_post(self, req, resp): """ Prideleni achievementu Format dat: { "users": [ id ], "task": (null|id),...
normal
{ "blob_id": "89ec04280ecfdfcba1923e2742e31d34750f894f", "index": 4536, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass AchievementGrant(object):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass AchievementGrant(object):\n\n def on_post(self, req, resp):\n \"\"\"\n Prid...
[ 0, 1, 2, 3, 4 ]
# Time :O(N) space: O(1) def swap(arr, start, end): while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 def rotation(arr, k, n): k = k % n swap(arr, 0, k-1) print(arr) swap(arr, k, n-1) print(arr) swap(arr, 0, n-1) print(arr) if _...
normal
{ "blob_id": "2180146da7ea745f5917ee66fd8c467437b5af4c", "index": 6761, "step-1": "<mask token>\n", "step-2": "def swap(arr, start, end):\n while start < end:\n arr[start], arr[end] = arr[end], arr[start]\n start += 1\n end -= 1\n\n\n<mask token>\n", "step-3": "def swap(arr, start, end...
[ 0, 1, 2, 3, 4 ]
from math import degrees, sqrt, sin, cos, atan, radians from pygame import Surface, draw from pygame.sprite import Sprite from constants import ARROW_MAX_SPEED, FLOOR_Y from game_types import Radian, Degree class Arrow(Sprite): def __init__(self, color, screen, character, click_position): Sprite.__in...
normal
{ "blob_id": "359db73de2c2bb5967723dfb78f98fb84b337b9d", "index": 343, "step-1": "<mask token>\n\n\nclass Arrow(Sprite):\n\n def __init__(self, color, screen, character, click_position):\n Sprite.__init__(self)\n self.color = color\n self.screen = screen\n self.character = character...
[ 9, 10, 11, 13, 14 ]
# # romaO # www.fabiocrameri.ch/colourmaps from matplotlib.colors import LinearSegmentedColormap cm_data = [[0.45137, 0.22346, 0.34187], [0.45418, 0.22244, 0.3361], [0.45696, 0.22158, 0.33043], [0.45975, 0.2209, 0.32483], ...
normal
{ "blob_id": "5082182af5a08970568dc1ab7a53ee5337260687", "index": 45, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n import numpy as np\n try:\n from viscm import viscm\n viscm(romaO_map)\n except ImportError:\n ...
[ 0, 1, 2, 3, 4 ]
import unittest import ConvertListToDict as cldf class MyDictTestCase(unittest.TestCase): def test_Dict(self): # Testcase1 (len(keys) == len(values)) actualDict1 = cldf.ConvertListsToDict([1, 2, 3],['a','b','c']) expectedDict1 = {1: 'a', 2: 'b', 3: 'c'} self.assertEqual(actualDict1,...
normal
{ "blob_id": "3421c3b839721694945bdbb4f17183bceaed5296", "index": 786, "step-1": "<mask token>\n\n\nclass MyDictTestCase(unittest.TestCase):\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass MyDictTestCase(unittest.TestCase):\n\n def test_Dict(self):\n actualDict1 = cldf.Conve...
[ 1, 2, 3, 4, 5 ]
#Calculadora mediante el terminal numero1 = 0 numero2 = 0 #Preguntamos los valores operacion = input("¿Qué operación quiere realizar (Suma / Resta / Division / Multiplicacion)?: ").upper() numero1 = int(input("Introduzca el valor 1: ")) numero2 = int(input("Introduzca el valor 2: ")) #Realizamos las operaciones ...
normal
{ "blob_id": "5d618acc0962447554807cbb9d3546cd4e0b3572", "index": 3005, "step-1": "<mask token>\n", "step-2": "<mask token>\nif operacion == 'SUMA':\n resultado = numero1 + numero2\nelif operacion == 'RESTA':\n resultado = numero1 - numero2\nelif operacion == 'DIVISION':\n resultado = numero1 / numero2...
[ 0, 1, 2, 3 ]
# 5.2 Training a convnet from scratch on a "small dataset" (p.131) # Preprocessing (p.133) # Copying images to train, validation and test directories import os, shutil # The path to the directory where the original dataset was uncompressed original_dataset_dir = 'E:/train/' # The directory where we will store our sma...
normal
{ "blob_id": "8340872f03c1bf7c1aee0c437258ac8e44e08bb8", "index": 7313, "step-1": "<mask token>\n", "step-2": "<mask token>\nos.mkdir(base_dir)\n<mask token>\nos.mkdir(train_dir)\n<mask token>\nos.mkdir(validation_dir)\n<mask token>\nos.mkdir(test_dir)\n<mask token>\nos.mkdir(train_cats_dir)\n<mask token>\nos.m...
[ 0, 1, 2, 3, 4 ]
""" Contains different comparator classes for model output data structures. """ import copy def tuple_to_string(tuptup): """ Converts a tuple to its string representation. Uses different separators (;, /, |) for different depths of the representation. Parameters ---------- tuptup : list ...
normal
{ "blob_id": "9c935e9ef298484d565256a420b867e800c3df55", "index": 3243, "step-1": "<mask token>\n\n\nclass NVCComparator:\n \"\"\" NVC response comparator. Performs the evaluation based on NVC and non-NVC classes.\n\n \"\"\"\n\n @staticmethod\n def compare(obj_a, obj_b):\n \"\"\" Compares two r...
[ 3, 6, 7, 10, 12 ]
#!/usr/bin/env python kube_description= \ """ Compute Server """ kube_instruction= \ """ Not instructions yet """ # # Standard geni-lib/portal libraries # import geni.portal as portal import geni.rspec.pg as PG import geni.rspec.emulab as elab import geni.rspec.igext as IG import geni.urn as URN # # PhantomNet ext...
normal
{ "blob_id": "ff7a865822a4f8b343ab4cb490c24d6d530b14e1", "index": 934, "step-1": "<mask token>\n", "step-2": "<mask token>\npc.verifyParameters()\n<mask token>\ntour.Description(IG.Tour.TEXT, kube_description)\ntour.Instructions(IG.Tour.MARKDOWN, kube_instruction)\nrspec.addTour(tour)\npc.printRequestRSpec(rspe...
[ 0, 1, 2, 3, 4 ]
from django.db import models class FoodCategory(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, default='') class Meta: db_table = 'kitchenrock_category' def __str__(self): return self.name
normal
{ "blob_id": "9bb1fc4df80d183c70d70653faa3428964b93a94", "index": 9494, "step-1": "<mask token>\n\n\nclass FoodCategory(models.Model):\n <mask token>\n <mask token>\n\n\n class Meta:\n db_table = 'kitchenrock_category'\n <mask token>\n", "step-2": "<mask token>\n\n\nclass FoodCategory(models....
[ 1, 2, 3, 4 ]
#!/usr/bin/python L=['ABC','ABC'] con1=[] for i in range (0,len(L[1])): #con.append(L[1][i]) con=[] for j in range (0, len(L)): print(L[j][i]) con.append(L[j][i]) con1.append(con) con2=[] for k in range (0,len(con1)): if con1[k].count('A')==2: con2.append('a') elif con1[k].count('B')...
normal
{ "blob_id": "beb9fe8e37a4f342696a90bc624b263e341e4de5", "index": 5459, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(0, len(L[1])):\n con = []\n for j in range(0, len(L)):\n print(L[j][i])\n con.append(L[j][i])\n con1.append(con)\n<mask token>\nfor k in range(0, len...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class ItemCrawlSpider(CrawlSpider): name = 'auction_crwal' allowed_domains = ['itempage3.auction.co.kr'] def __init__(self, keyword=None, *args, **kwargs): super(Item...
normal
{ "blob_id": "cba12d076ed8cba84501983fda9bdce8312f2618", "index": 6337, "step-1": "<mask token>\n\n\nclass ItemCrawlSpider(CrawlSpider):\n <mask token>\n <mask token>\n\n def __init__(self, keyword=None, *args, **kwargs):\n super(ItemCrawlSpider, self).__init__(*args, **kwargs)\n keyword.re...
[ 2, 3, 4, 5, 6 ]
# Generated by Django 3.1.2 on 2021-07-02 05:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('asset', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='balance', name='title', ), ]
normal
{ "blob_id": "257f18db95e069c037341d2af372269e988b0a80", "index": 536, "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 = [('asset', '000...
[ 0, 1, 2, 3, 4 ]
# adventofcode.com # day19 from collections import defaultdict INPUTFILE = 'input/input19' TEST = False TESTCASE = ('HOH', ['H => HO\n', 'H => OH\n', 'O => HH\n'], ['OHOH', 'HOOH', 'HHHH', 'HOHO']) def find_idx(string, substring): """ iterator that returns the index of the next occurence of substring wr...
normal
{ "blob_id": "e6fa1202d829fb553423998cdbad13684405437c", "index": 8483, "step-1": "# adventofcode.com\n# day19\n\nfrom collections import defaultdict\n\nINPUTFILE = 'input/input19'\n\nTEST = False\nTESTCASE = ('HOH', ['H => HO\\n', 'H => OH\\n', 'O => HH\\n'], ['OHOH', 'HOOH', 'HHHH', 'HOHO'])\n\ndef find_idx(str...
[ 0 ]
import time class SequenceHeuristic(object): def __init__(self, minChanges, minDuration, noMotionDelay): self._minChanges = minChanges self._minDuration = minDuration self._noMotionDelay = noMotionDelay self._duration = 0 def isValid(self, image, data): numOfChanges...
normal
{ "blob_id": "e07bd4cd13209bff8bc1119a619a2954abd52592", "index": 1515, "step-1": "<mask token>\n\n\nclass SequenceHeuristic(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SequenceHeuristic(object):\n\n def __init__(self, minChanges, minDuration, noMotionDelay):\n ...
[ 1, 2, 3, 4, 5 ]
# coding=utf-8 import datetime from django.http import JsonResponse from django.shortcuts import render, redirect from models import * from hashlib import sha1 from user_decorators import user_login from df_goods.models import GoodsInfo # Create your views here. def register(request): context={'title':'注册','top':'0...
normal
{ "blob_id": "1ef40d4162ca1b1bd6a5a5010485c78eb9d8d736", "index": 9621, "step-1": "<mask token>\n\n\ndef register(request):\n context = {'title': '注册', 'top': '0'}\n return render(request, 'df_user/register.html', context)\n\n\ndef login(request):\n context = {'title': '登录', 'top': '0'}\n return rende...
[ 6, 7, 9, 11, 12 ]
"""" articulo cliente venta ventadet """ class Articulo: def __init__(self,cod,des,pre,stoc): self.codigo=cod self.descripcion = des self.precio=pre self.stock=stoc class ventaDetalle: def __init__(self,pro,pre,cant): self.producto=pro sel...
normal
{ "blob_id": "f70f66926b9e2bf8b387d481263493d7f4c65397", "index": 516, "step-1": "<mask token>\n\n\nclass ventaDetalle:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ventaDetalle:\n\n def __init__(self, pro, pre, cant):\n self.producto = pro\n self.precio = pre\n self.cantidad...
[ 1, 2, 3, 4, 5 ]
# 1장 말뭉치와 워드넷 - 외부 말뭉치 다운로드, 로드하고 액세스하기 from nltk.corpus import CategorizedPlaintextCorpusReader from random import randint # 말뭉치 읽기 reader = CategorizedPlaintextCorpusReader(r'/workspace/NLP_python/tokens', r'.*\.txt', cat_pattern=r'(\w+)/*') print(reader.categories()) print(reader.fileids()) # 샘플 문서 출력 # pos, neg 카...
normal
{ "blob_id": "81cec5c1f28e92bf8e4adc2e2c632e072ed1f901", "index": 5765, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(reader.categories())\nprint(reader.fileids())\n<mask token>\nprint(fileP)\nprint(fileN)\nfor w in reader.words(fileP):\n print(w + ' ', end='')\n if w is '.':\n print()...
[ 0, 1, 2, 3, 4 ]
from platypush.message.response import Response class CameraResponse(Response): pass # vim:sw=4:ts=4:et:
normal
{ "blob_id": "4c38d0487f99cdc91cbce50079906f7336e51482", "index": 5462, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass CameraResponse(Response):\n pass\n", "step-3": "from platypush.message.response import Response\n\n\nclass CameraResponse(Response):\n pass\n", "step-4": "from platypu...
[ 0, 1, 2, 3 ]
# encoding=UTF-8 # This file serves the project in production # See http://wsgi.readthedocs.org/en/latest/ from __future__ import unicode_literals from moya.wsgi import Application application = Application( "./", ["local.ini", "production.ini"], server="main", logging="prodlogging.ini" )
normal
{ "blob_id": "cb0be932813a144cfb51b3aa2f6e0792e49c4945", "index": 3021, "step-1": "<mask token>\n", "step-2": "<mask token>\napplication = Application('./', ['local.ini', 'production.ini'], server=\n 'main', logging='prodlogging.ini')\n", "step-3": "from __future__ import unicode_literals\nfrom moya.wsgi i...
[ 0, 1, 2, 3 ]
#Main program: #reads IMU data from arduino uart #receives PS3 Controller input #Mantains Controller input frequency with CST #!/usr/bin/env python from map import mapControllerToDeg from map import constrain from map import wrap_180 from map import motorOutputLimitHandler from uart1 import IMUDevice import socket fro...
normal
{ "blob_id": "5626e5a4a448630fbbbc92a67ae08f3ed24e1b9e", "index": 4417, "step-1": "#Main program:\n#reads IMU data from arduino uart\n#receives PS3 Controller input\n#Mantains Controller input frequency with CST\n\n#!/usr/bin/env python\nfrom map import mapControllerToDeg\nfrom map import constrain\nfrom map impo...
[ 0 ]
from unittest import TestCase from ch4.array_to_btree import to_btree from ch4.is_subtree import is_subtree class IsSubtreeTest(TestCase): def test_should_be_subtree(self): container = to_btree([1, 2, 3, 4, 5, 6]) contained = to_btree([1, 3, 2]) self.assertTrue(is_subtree(container, conta...
normal
{ "blob_id": "51f7faaad29379daa58875c7b35d9ccf569c8766", "index": 6801, "step-1": "<mask token>\n\n\nclass IsSubtreeTest(TestCase):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass IsSubtreeTest(TestCase):\n <mask token>\n\n def test_should_not_be_subtree(self):\n containe...
[ 1, 2, 3, 4 ]
#!/usr/bin/env python ########################################################################### # 1) connect to the MQTT broker # 2) subscribe to the available data streams # 3) log to google sheets # 4) notify on critical events on the telegram channel ###############################################################...
normal
{ "blob_id": "0295d6ba962d099e76110c7a0e39748e3163e300", "index": 5541, "step-1": "<mask token>\n\n\ndef getUTC_TIME():\n return datetime.datetime.utcnow()\n\n\ndef pushSample(sample, topic):\n global client\n client.publish(topic, str(sample))\n\n\n<mask token>\n\n\ndef on_connect(client, userdata, flag...
[ 13, 15, 16, 17, 18 ]
from pybrain3.datasets import SupervisedDataSet inputDataSet = SupervisedDataSet(35, 20) #Creating new DataSet #A inputDataSet.addSample(( #Adding first sample to dataset -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1,...
normal
{ "blob_id": "a2569ccd509fa755f4cad026f483bcf891c6fb41", "index": 8120, "step-1": "<mask token>\n", "step-2": "<mask token>\ninputDataSet.addSample((-1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1,\n 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1), (\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 0, 1, 2, 3, 4 ]
from framework import * from pebble_game import * from constructive_pebble_game import * from nose.tools import ok_ import numpy as np # initialise the seed for reproducibility np.random.seed(102) fw_2d = create_framework([0,1,2,3], [(0,1), (0,3), (1,2), (1,3), (2,3)], [(2,3), (4,4), (5,2), (1,1)]) # a 3d fw constric...
normal
{ "blob_id": "4e31619efcaf6eeab3b32116b21e71de8202aee2", "index": 8646, "step-1": "<mask token>\n", "step-2": "<mask token>\nok_(is_inf_rigid(fw_2d, 2))\nok_(not is_inf_rigid(fw_3d, 3))\nok_(is_inf_rigid(fw_1d, 1))\n<mask token>\nprint(len(rand_fw.nodes))\ndraw_framework(rand_fw)\n<mask token>\nprint(R)\nprint(...
[ 0, 1, 2, 3, 4 ]
import numpy from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.cross_validation import cross_val_score lag = 10 print "Loading train_data..." train_data = numpy.loadtxt("../KddJavaToolChain/train_timelines_final.csv", delimiter=",") print...
normal
{ "blob_id": "68d37421b71d595510a1439c06cc31d00c23c277", "index": 1125, "step-1": "import numpy\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.cross_validation import cross_val_score\n\nlag = 10\n\nprint \"Loading train_data...\"\ntrain_...
[ 0 ]
#print 'g' class Client: def __init__(self, mechanize, WEBSERVICE_IP,WEBSERVICE_PORT, FORM_INPUT_PATH, dat , data_id = 'data', rasp_id_id = 'rasp_id',password = 'pass'): self.WEBSERVICE_PORT = WEBSERVICE_PORT self.mechanize = mechanize self.WEBSERVICE_IP = WEBSERVICE_IP self.FORM_INPUT_P...
normal
{ "blob_id": "3366d1d4ecc4cc9f971dff0c8adfbadc5511cc9e", "index": 5403, "step-1": "#print 'g'\nclass Client:\n def __init__(self, mechanize, WEBSERVICE_IP,WEBSERVICE_PORT, FORM_INPUT_PATH, dat , data_id = 'data', rasp_id_id = 'rasp_id',password = 'pass'):\n self.WEBSERVICE_PORT = WEBSERVICE_PORT\n ...
[ 0 ]
# -*- coding: utf-8 -*- from euler.baseeuler import BaseEuler from os import path, getcwd def get_name_score(l, name): idx = l.index(name) + 1 val = sum([(ord(c) - 64) for c in name]) return idx * val class Euler(BaseEuler): def solve(self): fp = path.join(getcwd(), 'euler/resources/names.t...
normal
{ "blob_id": "40d08bfa3286aa30b612ed83b5e9c7a29e9de809", "index": 6540, "step-1": "<mask token>\n\n\nclass Euler(BaseEuler):\n\n def solve(self):\n fp = path.join(getcwd(), 'euler/resources/names.txt')\n with open(fp, 'r') as f:\n names = sorted([name for name in f.read().replace('\"',...
[ 3, 4, 5, 6, 7 ]
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from django.contrib import admin from accounts.models import (UserProfile) admin.site.register(UserProfile) admin.site.unregister(User) class CustomUserAdmin(UserAdmin): list_display = ('username', ...
normal
{ "blob_id": "c95eaa09241428f725d4162e0e9f6ed3ce6f8fdd", "index": 6709, "step-1": "<mask token>\n\n\nclass CustomUserAdmin(UserAdmin):\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass CustomUserAdmin(UserAdmin):\n list_display = 'username', 'email', 'is_staff', 'is...
[ 1, 2, 3, 4, 5 ]
import pygame import time import math from pygame.locals import * from pygux.widgets.widget import Widget, hlBox from pygux.colours import Colours class Sprite(Widget): def __init__(self, x, y, w, h, image=None, callback=None, **kw): """Sprite widget """ Widget.__init__(self, x, y, w, h, ...
normal
{ "blob_id": "0003d104a4dcd5a5b2357016cbc0317738c2cd3c", "index": 2007, "step-1": "<mask token>\n\n\nclass Sprite(Widget):\n\n def __init__(self, x, y, w, h, image=None, callback=None, **kw):\n \"\"\"Sprite widget\n \"\"\"\n Widget.__init__(self, x, y, w, h, **kw)\n if image:\n ...
[ 3, 4, 5, 6 ]
from tkinter import * from tkinter.scrolledtext import ScrolledText def load(): with open(filename.get()) as file: # delete every between line 1 char 0 to END # INSERT is the current insertion point contents.delete('1.0', END) contents.insert(INSERT, file.read()) def save(): with open(filename.g...
normal
{ "blob_id": "fcf4cb5c47e4aa51d97b633ecdfec65246e82bd8", "index": 9011, "step-1": "<mask token>\n\n\ndef load():\n with open(filename.get()) as file:\n contents.delete('1.0', END)\n contents.insert(INSERT, file.read())\n\n\ndef save():\n with open(filename.get(), 'w') as file:\n file.wr...
[ 2, 3, 4, 5, 6 ]
import sys from pypregel import Pypregel from pypregel.vertex import Vertex, Edge from pypregel.reader import Reader from pypregel.writer import Writer from pypregel.combiner import Combiner class PageRankVertex(Vertex): def compute(self): if self.superstep() >= 1: s = 0 while sel...
normal
{ "blob_id": "6db7189d26c63ca9f9667045b780ec11994bac28", "index": 788, "step-1": "<mask token>\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n ...
[ 7, 9, 10, 12, 13 ]
""" Package with a facade to the several expansion strategies. """ from acres.resolution import resolver __all__ = ['resolver']
normal
{ "blob_id": "e31267871453d87aee409f1c751c36908f7f151a", "index": 804, "step-1": "<mask token>\n", "step-2": "<mask token>\n__all__ = ['resolver']\n", "step-3": "<mask token>\nfrom acres.resolution import resolver\n__all__ = ['resolver']\n", "step-4": "\"\"\"\nPackage with a facade to the several expansion ...
[ 0, 1, 2, 3 ]
#!/usr/bin/python3 """takes in a URL and an email address, sends a POST request to the passed URL with the email as a parameter, and finally displays the body of the response. """ import requests import sys if __name__ == "__main__": url_arg = sys.argv[1] email = sys.argv[2] params = {'email': email} ...
normal
{ "blob_id": "0d9c50e55df5aa5614bd5a9679729cf7fa69c5df", "index": 1461, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n url_arg = sys.argv[1]\n email = sys.argv[2]\n params = {'email': email}\n response = requests.post(url_arg, data=params)\n print(response.text)...
[ 0, 1, 2, 3 ]
import numpy as np import random from math import inf class Particle: """ Represents a particle of the Particle Swarm Optimization algorithm. """ def __init__(self, lower_bound, upper_bound): """ Creates a particle of the Particle Swarm Optimization algorithm. :param lower_bou...
normal
{ "blob_id": "096df1db4d8673ae7886a1b2022148c92f64a23e", "index": 1725, "step-1": "<mask token>\n\n\nclass ParticleSwarmOptimization:\n <mask token>\n\n def __init__(self, hyperparams, lower_bound, upper_bound):\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n self.nu...
[ 5, 7, 9, 12, 13 ]
import datetime import json import re import time import discord from utils.ext import standards as std, checks, context, logs DISCORD_INVITE = '(discord(app\.com\/invite|\.com(\/invite)?|\.gg)\/?[a-zA-Z0-9-]{2,32})' EXTERNAL_LINK = '((https?:\/\/(www\.)?|www\.)[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6})' EVE...
normal
{ "blob_id": "10c9566503c43e806ca89e03955312c510092859", "index": 5346, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef findWord(word):\n return re.compile('\\\\b({0})\\\\b'.format(word), flags=re.IGNORECASE).search\n\n\nasync def managePunishment(ctx, punishment, reason):\n await ctx.message...
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- help_txt = """ :help, show this help menu. :help [command] for detail :dict [word], only find translation on dict.cn :google [sentence], only find translation on google api :lan2lan [sentence], translate from one language to another language :add [word], add new word to yo...
normal
{ "blob_id": "3fadb91bd2367819a540f687530f4b48ed878423", "index": 9149, "step-1": "<mask token>\n", "step-2": "help_txt = \"\"\"\n:help, show this help menu. :help [command] for detail\n:dict [word], only find translation on dict.cn\n:google [sentence], only find translation on google api\n:lan2lan [sentence], ...
[ 0, 1, 2 ]
# Generated by Django 2.1 on 2018-12-05 00:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('PleniApp', '0006_auto_20181203_1144'), ] operations = [ migrations.CreateModel( name='Comment', ...
normal
{ "blob_id": "ccb6973910dba5897f6a12be23c74a35e848313b", "index": 4005, "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 = [('PleniApp', ...
[ 0, 1, 2, 3, 4 ]
import numpy as np from sklearn.metrics import mutual_info_score def mimic_binary(max_iter=100, fitness_func=None, space=None): assert fitness_func is not None assert space is not None idx = np.random.permutation(np.arange(len(space))) pool = space[idx[:int(len(space)/2)]] # randomly sample 50% of th...
normal
{ "blob_id": "360e661d8538a8f40b7546a54e9a9582fa64bd67", "index": 700, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef mutual_info(parent, child):\n parent = [int(x) for x in parent]\n child = [int(x) for x in child]\n return mutual_info_score(parent, child)\n", "step-3": "<mask token>\n...
[ 0, 1, 2, 3, 4 ]
from setuptools import setup, find_packages __version__ = '2.0' setup( name='sgcharts-pointer-generator', version=__version__, python_requires='>=3.5.0', install_requires=[ 'tensorflow==1.10.0', 'pyrouge==0.1.3', 'spacy==2.0.12', 'en_core_web_sm==2.0.0', 'sgchar...
normal
{ "blob_id": "e52b01cc7363943f5f99b1fa74720c6447b1cfae", "index": 6266, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='sgcharts-pointer-generator', version=__version__,\n python_requires='>=3.5.0', install_requires=['tensorflow==1.10.0',\n 'pyrouge==0.1.3', 'spacy==2.0.12', 'en_core_web_...
[ 0, 1, 2, 3, 4 ]
import data import sub_vgg19 import time import tensorflow as tf model_syn = sub_vgg19.vgg19_syn model_asy = sub_vgg19.vgg19_asy train_x = data.train_x train_y = data.train_y test_x = data.test_x test_y = data.test_y def input_fn(images, labels, epochs, batch_size): data = tf.data.Dataset.from_tensor_slices((ima...
normal
{ "blob_id": "ef6f91af5f500745fdcc23947a7e1764061c608c", "index": 2368, "step-1": "<mask token>\n\n\ndef input_fn(images, labels, epochs, batch_size):\n data = tf.data.Dataset.from_tensor_slices((images, labels))\n data = data.repeat(epochs).batch(batch_size)\n return data\n\n\n<mask token>\n", "step-2...
[ 1, 2, 3, 4, 5 ]
import json import decimal import threading import websocket from time import sleep from supervisor.core.utils.math import to_nearest def find_item_by_keys(keys, table, match_data): for item in table: matched = True for key in keys: if item[key] != match_data[key]: matc...
normal
{ "blob_id": "ea4ec2e605ab6e8734f7631fe298c93467908b5f", "index": 9582, "step-1": "<mask token>\n\n\nclass TrailingShell:\n <mask token>\n\n def __init__(self, order, offset: int, tick_size: float, test=True,\n init_ws=True):\n self.tick_size = tick_size\n self.exited = False\n s...
[ 14, 15, 16, 18, 25 ]
# 백준 문제(2021.5.22) # 10039번) 상현이가 가르치는 아이폰 앱 개발 수업의 수강생은 원섭, 세희, 상근, 숭, 강수이다. # 어제 이 수업의 기말고사가 있었고, 상현이는 지금 학생들의 기말고사 시험지를 채점하고 있다. # 기말고사 점수가 40점 이상인 학생들은 그 점수 그대로 자신의 성적이 된다. # 하지만, 40점 미만인 학생들은 보충학습을 듣는 조건을 수락하면 40점을 받게 된다. # 보충학습은 거부할 수 없기 때문에, 40점 미만인 학생들은 항상 40점을 받게 된다. # 학생 5명의 점수가 주어졌을 때, 평균 점수를 구하는 프로그램을 작성...
normal
{ "blob_id": "4a13a0d7aa2371d7c8963a01b7cc1b93f4110d5e", "index": 5356, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(5):\n score = int(input())\n if score < 40:\n score = 40\n result += score\nprint(result // 5)\n", "step-3": "result = 0\nfor i in range(5):\n score = ...
[ 0, 1, 2, 3 ]
# encoding=utf8 from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException from selenium.webdriver.support.select import Select import time import threading import random import ...
normal
{ "blob_id": "ae775e25179546156485e15d05491e010cf5daca", "index": 9360, "step-1": "<mask token>\n\n\nclass BookRoomThread(threading.Thread):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask ...
[ 3, 8, 15, 17, 18 ]
# Generated by Django 3.0 on 2020-05-04 16:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('game_skeleton', '0001_initial'), ('contenttypes', '0002_remove_content_type_name'), ('clas...
normal
{ "blob_id": "a718d82713503c4ce3d94225ff0db04991ad4094", "index": 9744, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
import pandas as pd def _get_site_name(f,i): data_file = f +"\\"+"new_desc_sele_data.csv" site_name=pd.read_csv(data_file)["SITE_ID"][i] return site_name def _get_site_DD_dataset_csv(f,i): '''获取经过全部数据集(经过全部的特征选择)''' site_path=_get_site_folder(f,i) data_path=site_path+"\\data_confirm.csv" ...
normal
{ "blob_id": "c034fba0b9204545b00ba972a17e63cf9c20854e", "index": 3930, "step-1": "<mask token>\n\n\ndef _get_site_name(f, i):\n data_file = f + '\\\\' + 'new_desc_sele_data.csv'\n site_name = pd.read_csv(data_file)['SITE_ID'][i]\n return site_name\n\n\n<mask token>\n\n\ndef _get_version_res_folder(f, ve...
[ 3, 4, 6, 7, 8 ]
import glob import os import partition import pickle import matplotlib.pyplot as plt import numpy as np from Cluster import fishermans_algorithm import argparse parser = argparse.ArgumentParser() plt.ion() parser.add_argument("--fish", help="flag for using fisherman's algorithm") parser.add_argument("--heat", help="...
normal
{ "blob_id": "805bc144a4945b46b398853e79ded17370ada380", "index": 3940, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.ion()\nparser.add_argument('--fish', help=\"flag for using fisherman's algorithm\")\nparser.add_argument('--heat', help='flag for using heatmap')\nparser.add_argument('--object', help...
[ 0, 1, 2, 3, 4 ]
import numpy def CALCB1(NVAC,KGAS,LGAS,ELECEN,ISHELL,L1): # IMPLICIT #real*8(A-H,O-Z) # IMPLICIT #integer*8(I-N) #CHARACTER*6 # SCR=""#(17) # SCR1=""#(17) #COMMON/GENCAS/ global ELEV#[17,79] global NSDEG#(17) global AA#[17] global BB#[17] global SCR,SCR1 #COMMON/MIXC/ global PRSH#(6,3,17,17) global ESH#(6...
normal
{ "blob_id": "09698649510348f92ea3b83f89ffa1c844929b8f", "index": 3332, "step-1": "<mask token>\n\n\ndef CALCB2(NVAC, KGAS, LGAS, ELECEN, ISHELL, L1):\n global ELEV\n global NSDEG\n global AA\n global BB\n global SCR, SCR1\n global PRSH\n global ESH\n global AUG\n global RAD\n global...
[ 3, 4, 5, 6, 7 ]
import collections def range(state): ran = state["tmp"]["analysis"]["range"] rang = { key : [ state["rank"][i] for i in val & ran ] for key, val in state["tmp"]["analysis"]["keys"].items() if val & ran } for item in state["tmp"]["items"]: item.setdefault("rank", 0) item_keys = set(item.keys()) rang_...
normal
{ "blob_id": "51868f26599c5878f8eb976d928c30d0bf61547d", "index": 9701, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef range(state):\n ran = state['tmp']['analysis']['range']\n rang = {key: [state['rank'][i] for i in val & ran] for key, val in\n state['tmp']['analysis']['keys'].items(...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python # -*- coding: utf-8 -*- import optparse import logging from pyspark import SparkContext from pyspark import SparkConf logger = logging.getLogger(__name__) def create_context(appName): """ Creates Spark HiveContext """ logger.info("Creating Spark context - may take some while") ...
normal
{ "blob_id": "d4b432735a112ccb293bf2f40929846b4ce34cd0", "index": 9348, "step-1": "<mask token>\n\n\ndef create_context(appName):\n \"\"\"\n Creates Spark HiveContext\n \"\"\"\n logger.info('Creating Spark context - may take some while')\n conf = SparkConf()\n conf.set('spark.hadoop.validateOutp...
[ 4, 5, 6, 7, 8 ]
import mmap; import random; def shuffle(): l_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; random.shuffle(l_digits); return "".join(l_digits); with open("hello.txt", "r+") as f: map = mmap.mmap(f.fileno(), 1000); l_i = 0; for l_digit in shuffle(): map[l_i] = l_digit; ...
normal
{ "blob_id": "b0468e58c4d0387a92ba96e8fb8a876ece256c78", "index": 6507, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef shuffle():\n l_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n random.shuffle(l_digits)\n return ''.join(l_digits)\n\n\n<mask token>\n", "step-3": "<mask ...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python from setuptools import setup, find_packages import os EXTRAS_REQUIRES = dict( test=[ 'pytest>=2.2.4', 'mock>=0.8.0', 'tempdirs>=0.0.8', ], dev=[ 'ipython>=0.13', ], ) # Tests always depend on all other requirements, except dev for k,v in EX...
normal
{ "blob_id": "f531af47431055866db72f6a7181580da461853d", "index": 6780, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor k, v in EXTRAS_REQUIRES.iteritems():\n if k == 'test' or k == 'dev':\n continue\n EXTRAS_REQUIRES['test'] += v\n<mask token>\nwith open(path) as fp:\n long_description...
[ 0, 1, 2, 3, 4 ]
import math import numpy as np import cv2 from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn import metrics from scipy.spatial.distance import cdist if (__name__ == "__main__"): cap = cv2.VideoCapture('dfd1.mp4') mog = cv2.createBackgroundSubtractorMOG2(detectSha...
normal
{ "blob_id": "28a0ae0492fb676044c1f9ced7a5a4819e99a8d9", "index": 8890, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n cap = cv2.VideoCapture('dfd1.mp4')\n mog = cv2.createBackgroundSubtractorMOG2(detectShadows=0)\n count = 0\n while True:\n list = []\n ...
[ 0, 1, 2, 3 ]
# -*-coding:utf-8 -* # Copyright (c) 2011-2015, Intel Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, thi...
normal
{ "blob_id": "3c2873add66172a5ed038949c31d514dcd5f26b3", "index": 7152, "step-1": "# -*-coding:utf-8 -*\n\n# Copyright (c) 2011-2015, Intel Corporation\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following condit...
[ 0 ]
from django.shortcuts import render from django_filters.rest_framework import DjangoFilterBackend from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http import JsonResponse, Http404 from .serializers import * from .models import * from .filter import * from r...
normal
{ "blob_id": "e0c6fb414d87c0a6377538089226e37b044edc70", "index": 8383, "step-1": "<mask token>\n\n\n@csrf_exempt\ndef TBGRApi(request, tbgrno=0):\n if request.method == 'GET':\n tbgrs = TBGR.objects.all()\n tbgrs_serializer = TBGRSerializer(tbgrs, many=True)\n return JsonResponse(tbgrs_se...
[ 3, 4, 5, 7, 8 ]
import random import numpy as np import os import torch class Agent: def __init__(self): self.model = torch.load(__file__[:-8] + "/agent.pkl") def act(self, state): state = torch.tensor(state) with torch.no_grad(): return self.model(state.unsqueeze(0)).max(1)[1].it...
normal
{ "blob_id": "50a4084dd3028acc2e6788e77794c100efcb3fac", "index": 132, "step-1": "<mask token>\n\n\nclass Agent:\n\n def __init__(self):\n self.model = torch.load(__file__[:-8] + '/agent.pkl')\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Agent:\n\n def __init__(self):\...
[ 2, 3, 4, 5, 6 ]
import pytest import gadget @pytest.mark.parametrize('invalid_line', [ 'beginningGDG::', 'beginning::end', 'nothing', ]) def test_parse_invalid_line(invalid_line): assert gadget.parse_log_line(invalid_line) is None
normal
{ "blob_id": "0dd361239d85ed485594ac0f5e7e2168f0684544", "index": 915, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@pytest.mark.parametrize('invalid_line', ['beginningGDG::',\n 'beginning::end', 'nothing'])\ndef test_parse_invalid_line(invalid_line):\n assert gadget.parse_log_line(invalid_lin...
[ 0, 1, 2, 3 ]
#!/usr/bin/python """ Create a 1024-host network, and run the CLI on it. If this fails because of kernel limits, you may have to adjust them, e.g. by adding entries to /etc/sysctl.conf and running sysctl -p. Check util/sysctl_addon. This is a copy of tree1024.py that is using the Containernet constructor. Containernet...
normal
{ "blob_id": "9c3ca2fa43c6a34d7fe06517812a6d0bf5d6dbe1", "index": 4029, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n setLogLevel('info')\n network = TreeContainerNet(depth=2, fanout=100, switch=OVSSwitch)\n network.run(CLI, network)\n", "step-3": "<mask token>\nfr...
[ 0, 1, 2, 3 ]
# # purpose: setup file to install the compiled-language python libraries # usage: python setup.py config_fc --f90flags="-O2 -fopenmp" install --prefix=$PWD # from numpy.distutils.core import Extension c_array_sqrt = Extension (name = "c_array_sqrt_omp", sources = ["./src/c_array_sqrt_omp....
normal
{ "blob_id": "c24bf42cfeaa1fb8ac188b9e08146762e0e86fed", "index": 1542, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name='array-sqrt-openmp', description=\n 'Illustration of Python extensions using OpenMP', author=...
[ 0, 1, 2, 3, 4 ]
from django.contrib.auth.models import User from django.test import Client from django.utils.timezone import localdate from pytest import fixture from operations.models import ToDoList @fixture def user(db): return User.objects.create( username='test', email='saidazimovaziza@gmail.com', password=...
normal
{ "blob_id": "347d468f15dee8a8219d201251cedffe21352f7c", "index": 8813, "step-1": "<mask token>\n\n\n@fixture\ndef authenticated_author_client(user, client: Client) ->Client:\n token = Token.objects.get_or_create(user=user)[0].key\n client.defaults['HTTP_AUTHORIZATION'] = f'Token {token}'\n print(client)...
[ 1, 2, 3, 4, 5 ]
def findOrder(numCourses,prerequisites): d={} for i in prerequisites: if i[0] not in d: d[i[0]]=[i[1]] if i[1] not in d: d[i[1]]=[] else: d[i[0]].append(i[1]) res=[] while d: for i in range(numCourses): if d[i] == []: res.append(d[i]) tmp=d[i] del d[i] for j in d: if tmp i...
normal
{ "blob_id": "75b13f4985fcf26fb9f7fb040554b52b13c1806d", "index": 4848, "step-1": "def findOrder(numCourses,prerequisites):\n\td={}\n\tfor i in prerequisites:\n\t\tif i[0] not in d:\n\t\t\td[i[0]]=[i[1]]\n\t\t\tif i[1] not in d:\n\t\t\t\td[i[1]]=[]\n\t\telse:\n\t\t\td[i[0]].append(i[1])\n\tres=[]\n\twhile d:\n\t\...
[ 0 ]
from jabberbot import JabberBot, botcmd import datetime import logging import sys import time; from config import username, password, chatroom, adminuser class SystemInfoJabberBot(JabberBot): @botcmd def serverinfo( self, mess, args): """Displays information about the server""" version = open(...
normal
{ "blob_id": "c9872fb536fd6552e2a5353566305555808747f7", "index": 1777, "step-1": "<mask token>\n\n\nclass SystemInfoJabberBot(JabberBot):\n\n @botcmd\n def serverinfo(self, mess, args):\n \"\"\"Displays information about the server\"\"\"\n version = open('/proc/version').read().strip()\n ...
[ 4, 5, 6, 7, 9 ]
#17219 tot, inp = map(int, input().split()) ID_dict = {} for _ in range(tot): id, pw = map(str, input().split()) ID_dict[id] = pw for _ in range(inp): print(ID_dict[input()])
normal
{ "blob_id": "cf7556034020d88ddb6b71b9f908c905e2f03cdb", "index": 4076, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _ in range(tot):\n id, pw = map(str, input().split())\n ID_dict[id] = pw\nfor _ in range(inp):\n print(ID_dict[input()])\n", "step-3": "tot, inp = map(int, input().split())...
[ 0, 1, 2, 3 ]
from eventnotipy import app import json json_data = open('eventnotipy/config.json') data = json.load(json_data) json_data.close() username = data['dbuser'] password = data['password'] host = data['dbhost'] db_name = data['database'] email_host = data['email_host'] email_localhost = data['email_localhost'] sms_host = da...
normal
{ "blob_id": "1f0680c45afb36439c56a1d202537261df5f9afc", "index": 5895, "step-1": "<mask token>\n", "step-2": "<mask token>\njson_data.close()\n<mask token>\n", "step-3": "<mask token>\njson_data = open('eventnotipy/config.json')\ndata = json.load(json_data)\njson_data.close()\nusername = data['dbuser']\npass...
[ 0, 1, 2, 3 ]
print('\n----------------概率与统计--------------------') import numpy as np import scipy import sympy as sym import matplotlib.pyplot as plt import sklearn.datasets as sd iris = sd.load_iris() x1 = np.random.random([10000]) # 均匀分布 x2 = np.random.normal(2, 1, [10000]) # 正态分布 x3 = np.random.normal(5, 1, [10000]) # 正态分布 #...
normal
{ "blob_id": "1ab5c6a56ac229c5a9892a9848c62a9a19a0dda7", "index": 3360, "step-1": "<mask token>\n\n\ndef conv(dt1, dt2):\n return np.mean((dt1 - np.mean(dt1)) * (dt2 - np.mean(dt2)))\n\n\n<mask token>\n\n\ndef rho(p1, p2):\n return conv(p1, p2) / np.std(p1) / np.std(p2)\n\n\n<mask token>\n", "step-2": "pr...
[ 2, 4, 5, 6, 7 ]