code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
from flask import request, Flask import ldap3 app = Flask(__name__) @app.route("/normal") def normal(): """ A RemoteFlowSource is used directly as DN and search filter """ unsafe_dc = request.args['dc'] unsafe_filter = request.args['username'] dn = "dc={}".format(unsafe_dc) search_filte...
normal
{ "blob_id": "b51591de921f6e153c1dd478cec7fad42ff4251a", "index": 749, "step-1": "<mask token>\n\n\n@app.route('/direct')\ndef direct():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter =...
[ 1, 2, 3, 4, 5 ]
from .. import CURRENT_NAME from ..cmd import call_cmd from .config import Configurator from .config import USER_INI from icemac.install.addressbook._compat import Path import argparse import os import pdb # noqa: T002 import sys def update(stdin=None): """Update the current address book installation.""" cur...
normal
{ "blob_id": "f5274f5d838d484ca0c1cc5a5192a2fd698cf827", "index": 9432, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef update(stdin=None):\n \"\"\"Update the current address book installation.\"\"\"\n curr_path = Path.cwd() / CURRENT_NAME\n if not curr_path.exists():\n print('ERROR...
[ 0, 1, 2, 3, 4 ]
import types import qt cfg = qt.cfgman cfg.remove_cfg('protocols') cfg.remove_cfg('samples') cfg.remove_cfg('setup') cfg.add_cfg('protocols') cfg.add_cfg('samples') cfg.add_cfg('setup') cfg['samples']['current'] = 'hans-sil13' cfg['protocols']['current'] = 'hans-sil13-default' print 'updating msmt params for {}'.for...
normal
{ "blob_id": "3f20438b0dd2ae8de470e5456dbb764eabf69645", "index": 8092, "step-1": "import types\nimport qt\ncfg = qt.cfgman\n\ncfg.remove_cfg('protocols')\ncfg.remove_cfg('samples')\ncfg.remove_cfg('setup')\ncfg.add_cfg('protocols')\ncfg.add_cfg('samples')\ncfg.add_cfg('setup')\n\ncfg['samples']['current'] = 'han...
[ 0 ]
from project import db from project.models import User, Recipe, Association, Ingre, Recipe_ingre user=User.query.filter_by(username="xiaofan").first() recipe=Recipe.query.filter_by(recipename="Jerry").first() recipes = Recipe.query.filter(Recipe.users.any(username="xiaofan")).all() if recipe not in recipes: us...
normal
{ "blob_id": "07f8fd305e2311c0e37a785da0a826b8ea4e78ba", "index": 4154, "step-1": "<mask token>\n", "step-2": "<mask token>\nif recipe not in recipes:\n user.add_recipes([recipe])\n db.session.commit()\n", "step-3": "<mask token>\nuser = User.query.filter_by(username='xiaofan').first()\nrecipe = Recipe....
[ 0, 1, 2, 3, 4 ]
import weakref from soma.controller import Controller from soma.functiontools import SomaPartial from traits.api import File, Undefined, Instance class MatlabConfig(Controller): executable = File(Undefined, output=False, desc='Full path of the matlab executable') def load_module(capsul_...
normal
{ "blob_id": "4a8e8994ec8734664a5965b81da9d146d8504f8d", "index": 6096, "step-1": "<mask token>\n\n\nclass MatlabConfig(Controller):\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass MatlabConfig(Controller):\n executable = File(Undefined, output=False, desc=\n 'Full path of t...
[ 1, 4, 5, 6, 7 ]
#!/bin/python import numpy as np import os from sklearn.svm.classes import SVC import pickle import sys # Apply the SVM model to the testing videos; Output the score for each video if __name__ == '__main__': if len(sys.argv) != 5: print("Usage: {0} model_file feat_dir feat_dim output_file".format(sys.ar...
normal
{ "blob_id": "385dccfab4d7c37d10d968658b51e231691a7b49", "index": 1556, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n if len(sys.argv) != 5:\n print('Usage: {0} model_file feat_dir feat_dim output_file'.format(\n sys.argv[0]))\n print('model_file -...
[ 0, 1, 2, 3 ]
from django.http import HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView from pos.service.sumup import API_URL, create_checkout from pos.models.sumup import SumUpAPIKey, SumUpOnline from pos.forms import RemotePayForm from pos.models.user import User class Remote...
normal
{ "blob_id": "731d2891bbc29879fd8900a11077c93550e4e88d", "index": 4251, "step-1": "<mask token>\n\n\nclass RemotePayView(TemplateView):\n template_name = 'remotepay/pay.djhtml'\n\n\n<mask token>\n\n\ndef pay_callback(request, checkoutid):\n t = SumUpOnline.objects.get(transaction_id=checkoutid)\n if t.st...
[ 3, 4, 7, 8, 9 ]
class Circle(): def __init__(self, radius, color="white"): self.radius = radius self.color = color c1 = Circle(10, "black") print("半径:{}, 色: {}".format(c1.radius, c1.color))
normal
{ "blob_id": "6ce50552571594c7be77ac0bf3b5274f2f39e545", "index": 5086, "step-1": "class Circle:\n <mask token>\n\n\n<mask token>\n", "step-2": "class Circle:\n\n def __init__(self, radius, color='white'):\n self.radius = radius\n self.color = color\n\n\n<mask token>\n", "step-3": "class C...
[ 1, 2, 3, 4, 5 ]
""" Generates a temperature celsius to fahrenheit conversion table AT 11-10-2018 """ __author__ = "Aspen Thompson" header = "| Celsius | Fahrenheit |" line = "-" * len(header) print("{0}\n{1}\n{0}".format(line, header)) for i in range(-10, 31): print("| {:^7} | {:^10.10} |".format(i, i * 1.8 + 32))
normal
{ "blob_id": "591d0a166af5b8d0bed851c2f56ecc3da4f3a5eb", "index": 4367, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('{0}\\n{1}\\n{0}'.format(line, header))\nfor i in range(-10, 31):\n print('| {:^7} | {:^10.10} |'.format(i, i * 1.8 + 32))\n", "step-3": "<mask token>\n__author__ = 'Aspen Thom...
[ 0, 1, 2, 3 ]
from django.conf import settings from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from fish.labinterface.models import * from registration import signals from registration.forms import RegistrationForm from registration.models import RegistrationProfile from labinterfac...
normal
{ "blob_id": "201279c0cba2d52b6863204bfadb6291a0065f60", "index": 3961, "step-1": "<mask token>\n\n\nclass CustomRegistrationBackend(object):\n <mask token>\n\n def activate(self, request, activation_key):\n activated = RegistrationProfile.objects.activate_user(activation_key)\n if activated:\...
[ 5, 6, 7, 8, 9 ]
# inserting logical unit ids for splitting texts into logical chunks import re import os splitter = "#META#Header#End#" def logical_units(file): ar_ra = re.compile("^[ذ١٢٣٤٥٦٧٨٩٠ّـضصثقفغعهخحجدًٌَُلإإشسيبلاتنمكطٍِلأأـئءؤرلاىةوزظْلآآ]+$") with open(file, "r", encoding="utf8") as f1: book = f1.read() ...
normal
{ "blob_id": "5c001303962315afe2512eb307376f6f7a883cf9", "index": 6831, "step-1": "<mask token>\n\n\ndef process_all(folder):\n exclude = ['OpenITI.github.io', 'Annotation', '_maintenance', 'i.mech']\n for root, dirs, files in os.walk(folder):\n dirs[:] = [d for d in dirs if d not in exclude]\n ...
[ 1, 3, 4, 5, 6 ]
def solve(bt): if len(bt) == n: print(*bt, sep="") exit() for i in [1, 2, 3]: if is_good(bt + [i]): solve(bt + [i]) def is_good(arr): for i in range(1, len(arr)//2+1): if arr[-i:] == arr[-(i*2):-i]: return False return True if __name__ == "__main__": n = int(input()) sol...
normal
{ "blob_id": "65d5cee6899b0b75474e3898459bf2cfa8b3635b", "index": 1042, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef is_good(arr):\n for i in range(1, len(arr) // 2 + 1):\n if arr[-i:] == arr[-(i * 2):-i]:\n return False\n return True\n\n\n<mask token>\n", "step-3": "de...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- ############################################################################# # # Copyright (C) 2019-Antti Kärki. # Author: Antti Kärki. # # You can modify it under the terms of the GNU AFFERO # GENERAL PUBLIC LICENSE (AGPL v3), Version 3. # # This program is distributed ...
normal
{ "blob_id": "96131e3d6c67c0ee4ff7f69d4ffedcbf96470f14", "index": 7069, "step-1": "<mask token>\n\n\nclass rocker_connection:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass rocker_connection:\n\n @api.multi\n def create_connection(self):\n _database_record = self\n _datasource = _d...
[ 1, 2, 3, 4, 5 ]
def missing_value_count_and_percent(df): """ Return the number and percent of missing values for each column. Args: df (Dataframe): A dataframe with many columns Return: df (Dataframe): A dataframe with one column showing number of missing values, one column showing percentage of ...
normal
{ "blob_id": "88c304f224ab60062582abbfa1146a651e1233e6", "index": 183, "step-1": "def missing_value_count_and_percent(df):\n \"\"\"\n Return the number and percent of missing values for each column. \n\n Args:\n df (Dataframe): A dataframe with many columns\n \n Return:\n df (Datafram...
[ 0 ]
# -*- coding: utf-8 -*- """ @author: chris Modified from THOMAS MCTAVISH (2010-11-04). mpiexec -f ~/machinefile -enable-x -n 96 python Population.py --noplot """ from __future__ import with_statement from __future__ import division import sys sys.path.append('../NET/sheff/weasel/') sys.path.append('../NET/sheffprk/...
normal
{ "blob_id": "06ea697989f8f9ac539559690dcfd7aa73151e0f", "index": 2700, "step-1": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: chris\n\nModified from THOMAS MCTAVISH (2010-11-04).\n\nmpiexec -f ~/machinefile -enable-x -n 96 python Population.py --noplot\n\"\"\"\n\nfrom __future__ import with_statement\nfrom __futur...
[ 0 ]
import re import random import requests from bs4 import BeautifulSoup import js2py from fake_useragent import UserAgent def _get_request_key(session): res = session.post("https://spys.one/en/socks-proxy-list/") soup = BeautifulSoup(res.text, 'html.parser') return soup.find("input", {"name": "xx0"}).get("v...
normal
{ "blob_id": "647dde6e3288ded29336062b78baacc3a92908a7", "index": 478, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ProxyScrapper:\n\n def __init__(self):\n self._proxies = []\n\n def refresh(self):\n session = requests.Session()\n session.headers['User-Agent'] = Use...
[ 0, 4, 5, 7, 8 ]
a=[1,2,3,4,5] max=0 for i in a: if i>=max: max=i elif i<=min: min=i print max print min
normal
{ "blob_id": "65da68d33aa382ed6deeff3c66a063ee299c2567", "index": 1448, "step-1": "a=[1,2,3,4,5]\nmax=0\nfor i in a:\n\tif i>=max:\n\t\tmax=i\n\telif i<=min:\n\t\tmin=i\nprint max\nprint min\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- #from setup_env import * #from mmlibrary import * from astropy.coordinates import SkyCoord import astropy.units as u from mmlibrary import * import numpy as np import lal from scipy.special import logsumexp import cpnest, cpnest.model # Oggetto per test: GW170817 #GW =...
normal
{ "blob_id": "fa5468741e9884f6c8bcacaf9d560b5c93ee781a", "index": 8906, "step-1": "<mask token>\n\n\nclass completeness(cpnest.model.Model):\n\n def __init__(self, catalog):\n self.names = ['z', 'h', 'om', 'ol']\n self.bounds = [[0.001, 0.012], [0.5, 1.0], [0.04, 1.0], [0.0, 1.0]]\n self.o...
[ 2, 9, 13, 15, 16 ]
# -*- coding: utf-8 -*- import json import os import io import shutil import pytest from chi_annotator.algo_factory.common import TrainingData from chi_annotator.task_center.config import AnnotatorConfig from chi_annotator.task_center.data_loader import load_local_data from chi_annotator.task_center.model import Inte...
normal
{ "blob_id": "192c44540018b9e1ab857bdbfba6fdb39bb74431", "index": 8769, "step-1": "<mask token>\n\n\nclass TestTrainer(object):\n <mask token>\n\n @classmethod\n def teardown_class(cls):\n \"\"\" teardown any state that was previously setup with a call to\n setup_class.\n \"\"\"\n ...
[ 10, 12, 13, 14, 16 ]
import json import os import time import urllib.request import pandas as pd from lib.db.dbutils import ( check_blacklisted, check_ticker_exists, get_db, update_blacklisted, ) def get_data(url, delay=20): while True: df = json.loads(urllib.request.urlopen(url).read()) if df.get("N...
normal
{ "blob_id": "3c8e6a93c4d5616b9199cf473d298bfa2dc191af", "index": 9971, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef grab_a_ticker(symbol='MSFT', apiKey=None):\n if apiKey is None:\n apiKey = os.environ.get('API_KEY')\n if not check_ticker_exists(symbol) and not check_blacklisted(sy...
[ 0, 1, 2, 3, 4 ]
Ylist = ['yes', 'Yes', 'Y', 'y'] Nlist = ['no', 'No', 'N', 'n'] America = ['America', 'america', 'amer', 'rica'] TRW = ['1775', 'The Revolutionary war', 'the Revolutionary war', 'the revolutionary war', 'The Revolutionary War', 'trw', 'Trw', 'TRW'] TCW = ['1861', 'The civil war', 'The civil War', 'The Civil...
normal
{ "blob_id": "6e07dcc3f3b8c7fbf8ce8d481b9612e7496967bd", "index": 8316, "step-1": "<mask token>\n", "step-2": "Ylist = ['yes', 'Yes', 'Y', 'y']\nNlist = ['no', 'No', 'N', 'n']\nAmerica = ['America', 'america', 'amer', 'rica']\nTRW = ['1775', 'The Revolutionary war', 'the Revolutionary war',\n 'the revolution...
[ 0, 1, 2 ]
# coding=utf-8 from __future__ import print_function import os import sys os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' basedir = os.getcwd() os.chdir(os.path.dirname(os.path.abspath(__file__))) sys.path.append('trainer') sys.path.append('downloader') from gen.gen_captcha import gen_dataset, load_templates, candidates fr...
normal
{ "blob_id": "8e34b5e15c5b6107d6841e7b567abf967c631f1b", "index": 7440, "step-1": "<mask token>\n\n\ndef show_im(dataset):\n data = np.uint8(dataset[0]).reshape((30, 96)) * 255\n im = Image.fromarray(data)\n im.show()\n\n\ndef test_model(captcha):\n im = Image.open(os.path.join(basedir, 'downloader', ...
[ 2, 3, 4, 5, 6 ]
from app01 import models from rest_framework.views import APIView # from api.utils.response import BaseResponse from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination from api.serializers.course import DegreeCourseSerializer # 查询所有学位课程 class DegreeCourseView(APIView):...
normal
{ "blob_id": "2b3f8b1ac4735785683c00f6e6ced85d201de53f", "index": 8567, "step-1": "<mask token>\n\n\nclass DegreeCourseDetailView(APIView):\n\n def get(self, request, pk, *args, **kwargs):\n response = {'code': 100, 'data': None, 'error': None}\n try:\n degree_course = models.DegreeCou...
[ 2, 3, 4, 5, 6 ]
from django.contrib.auth.models import User from rest_framework.serializers import ModelSerializer from app_calendar.models import Holiday, Country, Event, User class CountrySerializer(ModelSerializer): class Meta: model = Country fields = '__all__' class UserSerializer(ModelSerializer): ...
normal
{ "blob_id": "5b366b0f6813f686600df9da4a17f190f034a10c", "index": 2046, "step-1": "<mask token>\n\n\nclass EventSerializer(ModelSerializer):\n\n\n class Meta:\n model = Event\n fields = '__all__'\n\n\nclass HolidaySerializerRead(ModelSerializer):\n country = CountrySerializer()\n\n\n class ...
[ 4, 5, 6, 7 ]
""" 时间最优 思路: 将和为目标值的那 两个 整数定义为 num1 和 num2 创建一个新字典,内容存在数组中的数字及索引 将数组nums转换为字典, 遍历字典, num1为字典中的元素(其实与数组总的元素一样), num2 为 target减去num1, 判定num2是否在字典中,如果存在,返回字典中num2的值(也就是在数组nums中的下标)和 i(也就是num1在数组中的下标) 如果不存在,设置字典num1的值为i """ def two_sum(nums, target): dct = {} for i, num1 in enumerate(nums): ...
normal
{ "blob_id": "dac8dbb0eba78d4f8dfbe3284325735324a87dc2", "index": 8674, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef two_sum(nums, target):\n dct = {}\n for i, num1 in enumerate(nums):\n num2 = target - num1\n if num2 in dct:\n return [dct[num2], i]\n dct[nu...
[ 0, 1, 2, 3 ]
from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [path('', views.PostList.as_view(), name='blog_index'), path( '<slug:slug>/', views.post_detail, name='post_detail'), path( 'tag/<slug:slug>/', views.TagIndexView.as_view(),...
normal
{ "blob_id": "09ea684cfb6f0a521d3bdadf977d9385636bdc83", "index": 7150, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('', views.PostList.as_view(), name='blog_index'), path(\n '<slug:slug>/', views.post_detail, name='post_detail'), path(\n 'tag/<slug:slug>/', views.TagIndexView....
[ 0, 1, 2 ]
import socket import time import sys def main(): if len(sys.argv) != 2: print("usage : %s port") sys.exit() port = int(sys.argv[1]) count = 0 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socke...
normal
{ "blob_id": "68b9f7317f7c6dcda791338ee642dffb653ac694", "index": 4804, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n if len(sys.argv) != 2:\n print('usage : %s port')\n sys.exit()\n port = int(sys.argv[1])\n count = 0\n sock = socket.socket(socket.AF_INET, soc...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # encoding: utf-8 """ plot: regularization on x axis, number of k_best features on y Created by on 2012-01-27. Copyright (c) 2012. All rights reserved. """ import sys import os import json import numpy as np import pylab as plt import itertools as it from master.libs import plot_lib as plib ...
normal
{ "blob_id": "c5bbfa1a86dbbd431566205ff7d7b941bdceff58", "index": 1233, "step-1": "<mask token>\n", "step-2": "<mask token>\nreload(plib)\nreload(rdl)\n<mask token>\nplt.rcParams.update(params)\n<mask token>\nif not os.path.exists(outpath):\n os.mkdir(outpath)\nplt.close('all')\n<mask token>\nif config['plot...
[ 0, 1, 2, 3, 4 ]
import os import numpy as np from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Flatten, concatenate from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Activation from keras.layers.normalization import BatchNormalization from keras.optimizers import SGD from keras....
normal
{ "blob_id": "ebc050544da69837cc2b8977f347380b94474bab", "index": 576, "step-1": "<mask token>\n\n\ndef _build(_input, *nodes):\n x = _input\n for node in nodes:\n if callable(node):\n x = node(x)\n elif isinstance(node, list):\n x = [_build(x, branch) for branch in node]...
[ 1, 2, 3, 4, 5 ]
#n = int(input()) #s = input() n, m = map(int, input().split()) #s, t = input().split() #n, m, l = map(int, input().split()) #s, t, r = input().split() #a = map(int, input().split()) #a = input().split() a = [int(input()) for _ in range(n)] #a = [input() for _ in range(n)] #t = input() #m = int(input()) #p, q = map(in...
normal
{ "blob_id": "a09bc84a14718422894127a519d67dc0c6b13bc9", "index": 746, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(n - 1):\n if a[i + 1] - a[i] < m:\n ans += a[i + 1] - a[i]\n else:\n ans += m\nprint(ans)\n", "step-3": "n, m = map(int, input().split())\na = [int(inp...
[ 0, 1, 2, 3 ]
import os from os.path import join import json import pandas as pd import time import numpy as np import torch def str2bool(v): # convert string to boolean type for argparser input if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower(...
normal
{ "blob_id": "a9302dbf724f9548411fbf2959f36b4cc5742ff8", "index": 4999, "step-1": "<mask token>\n\n\ndef str_or_none(v):\n if v is None:\n return None\n if v.lower() == 'none':\n return None\n else:\n return v\n\n\n<mask token>\n\n\ndef name2dic(s):\n return {x.split('-')[0]: x.sp...
[ 5, 8, 9, 12, 13 ]
''' Условие Дано два числа a и b. Выведите гипотенузу треугольника с заданными катетами. ''' import math a = int(input()) b = int(input()) print(math.sqrt(a * a + b * b))
normal
{ "blob_id": "c0348fc5f51e6f7a191fea6d0e3cb84c60b03e22", "index": 597, "step-1": "'''\nУсловие\nДано два числа a и b. Выведите гипотенузу треугольника с заданными катетами.\n'''\nimport math\na = int(input())\nb = int(input())\nprint(math.sqrt(a * a + b * b))", "step-2": null, "step-3": null, "step-4": nul...
[ 0 ]
#!/usr/bin/env python3 import cgitb import sys from auth import is_admin cgitb.enable() sys.stdout.write('Content-Type: application/octet-stream\n\n') sys.stdout.write('yes' if is_admin() else 'no') sys.stdout.flush()
normal
{ "blob_id": "be9972d899a167a8ca2728960e55cda538793cc5", "index": 1576, "step-1": "<mask token>\n", "step-2": "<mask token>\ncgitb.enable()\nsys.stdout.write('Content-Type: application/octet-stream\\n\\n')\nsys.stdout.write('yes' if is_admin() else 'no')\nsys.stdout.flush()\n", "step-3": "import cgitb\nimport...
[ 0, 1, 2, 3 ]
# Generated by Django 3.2.7 on 2021-10-01 06:43 from django.db import migrations import django_resized.forms import event.models.event import event.models.event_agenda class Migration(migrations.Migration): dependencies = [ ('event', '0009_auto_20211001_0406'), ] operations = [ migratio...
normal
{ "blob_id": "d0a053faccecddc84a9556aec3dff691b171df96", "index": 9977, "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 = [('event', '00...
[ 0, 1, 2, 3, 4 ]
a,b,c,d=map(int,input().split()) ans=0 if a>=0: if c>=0: ans=b*d elif d>=0: ans=b*d else: ans=a*d elif b>=0: if c>=0: ans=b*d elif d>=0: ans=max(b*d,a*c) else: ans=a*c else: if c>=0: ans=b*c elif d>=0: ans=a*c else: ...
normal
{ "blob_id": "be37a7596850050af58f735e60bdf13594715caf", "index": 4928, "step-1": "<mask token>\n", "step-2": "<mask token>\nif a >= 0:\n if c >= 0:\n ans = b * d\n elif d >= 0:\n ans = b * d\n else:\n ans = a * d\nelif b >= 0:\n if c >= 0:\n ans = b * d\n elif d >= 0:...
[ 0, 1, 2, 3 ]
#This script reads through a Voyager import log and outputs duplicate bib IDs as well as the IDs of bibs, mfhds, and items created. #import regular expressions and openpyxl import re import openpyxl # prompt for file names fname = input("Enter input file, including extension: ") fout = input("Enter output file, witho...
normal
{ "blob_id": "fc06d8a26a99c16a4b38ad0b4bbb28a1dc522991", "index": 6902, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith fh as f:\n lines = f.readlines()\n n_lines = len(lines)\n for i, line in enumerate(lines):\n line = line.rstrip()\n if line.startswith('\\tBibID & rank') and n...
[ 0, 1, 2, 3, 4 ]
from .settings import * # Heroku Configurations # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default': dj_database_url.config()} # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # loading local_se...
normal
{ "blob_id": "8bb86cae3387a0d4ce5987f3e3c458c8298174e0", "index": 7342, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n from .local_settings import *\nexcept Exception as e:\n pass\n<mask token>\n", "step-3": "<mask token>\nDATABASES = {'default': dj_database_url.config()}\nSECURE_PROXY_SSL_...
[ 0, 1, 2, 3, 4 ]
K = input() mat = "".join(raw_input() for i in xrange(4)) print ("YES", "NO")[max(mat.count(str(i)) for i in xrange(1, 10)) > K*2]
normal
{ "blob_id": "879f7503f7f427f92109024b4646d1dc7f15d63d", "index": 2153, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('YES', 'NO')[max(mat.count(str(i)) for i in xrange(1, 10)) > K * 2]\n", "step-3": "K = input()\nmat = ''.join(raw_input() for i in xrange(4))\nprint('YES', 'NO')[max(mat.count(str...
[ 0, 1, 2, 3 ]
from typing import Any, Optional from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware from scene_manager.loader.loader import Loader from scene_manager.utils import content_type_checker class ScenesMiddleware(BaseMiddleware): def __init__(self, *, loader: Optional[Loader] = None, ...
normal
{ "blob_id": "11db76cba3dd76cad0d660a0e189d3e4c465071b", "index": 8836, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ScenesMiddleware(BaseMiddleware):\n <mask token>\n\n async def on_post_process_message(self, message: types.Message, results:\n tuple, data: dict):\n if data...
[ 0, 1, 2, 3, 4 ]
''' Encontrar el valor mas alto el mas rapido, el mas lento para eso son los algoritmos de optimizacion Para eso debemos pensar en una funcion que queramos maximizar o minimizar Se aplican mas que todo para empresas como despegar, en donde se pueden generar buenas empresas Empresas a la optimizacion...
normal
{ "blob_id": "7163be250ae3a22931de037cb6896c2e6d5f00a8", "index": 584, "step-1": "<mask token>\n", "step-2": "'''\n Encontrar el valor mas alto el mas rapido, el mas lento\n para eso son los algoritmos de optimizacion\n Para eso debemos pensar en una funcion que queramos maximizar o minimizar\n Se a...
[ 0, 1 ]
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from .. import _utilities import typing # Export this package's modules as members: from .authority import * from .ca_pool import * fro...
normal
{ "blob_id": "4ca4d4bd684802b056417be4ee3d7d10e8f5dc85", "index": 8842, "step-1": "<mask token>\n", "step-2": "from .. import _utilities\nimport typing\nfrom .authority import *\nfrom .ca_pool import *\nfrom .ca_pool_iam_binding import *\nfrom .ca_pool_iam_member import *\nfrom .ca_pool_iam_policy import *\nfro...
[ 0, 1, 2 ]
import flask import flask_sqlalchemy app = flask.Flask(__name__) app.config.from_pyfile('settings.py') db = flask_sqlalchemy.SQLAlchemy(app)
normal
{ "blob_id": "2ed0ae48e8fec2c92effcbb3e495a1a9f4636c27", "index": 6777, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.config.from_pyfile('settings.py')\n<mask token>\n", "step-3": "<mask token>\napp = flask.Flask(__name__)\napp.config.from_pyfile('settings.py')\ndb = flask_sqlalchemy.SQLAlchemy(app...
[ 0, 1, 2, 3 ]
import re import datetime from django import forms from django.utils.translation import ugettext as _ from vcg.util.forms import mobile_number_validation from vcg.company_management.models import ConfigurationContact, ConfigurationLogo, ConfigurationHomepage, ConfigurationLocation class ConfigurationContactForm(for...
normal
{ "blob_id": "f6f1cd95e4aaa5e434c3cf3cff0d46b45fc7b830", "index": 6190, "step-1": "<mask token>\n\n\nclass ConfigurationContactForm(forms.ModelForm):\n\n\n class Meta:\n model = ConfigurationContact\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def clean_phone_number_ext...
[ 11, 13, 15, 16, 18 ]
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.views.generic import TemplateView from django.core.context_processors import csrf from django.template import RequestContext from django.views.generic import DetailView, ListView , CreateView , UpdateView , DeleteView , FormView , View ...
normal
{ "blob_id": "8a3694f96203ae8d1e306e1c9a5a47bfe26abeb1", "index": 5178, "step-1": "<mask token>\n\n\nclass ListContact(ListView):\n model = Contact\n", "step-2": "<mask token>\n\n\nclass AddContact(CreateView):\n model = Contact\n success_url = reverse_lazy('home')\n\n\nclass ListContact(ListView):\n ...
[ 2, 4, 5, 6, 8 ]
from django.db import models import eav from django.utils import timezone class RiskType(models.Model): """A model class used for storing data about risk types """ name = models.CharField(max_length=255) created = models.DateTimeField(default=timezone.now) modified = models.DateTimeField(auto_...
normal
{ "blob_id": "635b75bc12718bccdfb9d04a54476c93fa4685ce", "index": 4661, "step-1": "<mask token>\n\n\nclass RiskType(models.Model):\n <mask token>\n name = models.CharField(max_length=255)\n created = models.DateTimeField(default=timezone.now)\n modified = models.DateTimeField(auto_now=True)\n\n\n c...
[ 3, 4, 5, 6, 7 ]
NUM_CLASSES = 31 AUDIO_SR = 16000 AUDIO_LENGTH = 16000 LIBROSA_AUDIO_LENGTH = 22050 EPOCHS = 25 categories = { 'stop': 0, 'nine': 1, 'off': 2, 'four': 3, 'right': 4, 'eight': 5, 'one': 6, 'bird': 7, 'dog': 8, 'no': 9, 'on': 10, 'seven': 11, 'cat': 12, 'left': 1...
normal
{ "blob_id": "6a9e18cde94258b01a37f459eceaac58118b4976", "index": 5813, "step-1": "<mask token>\n", "step-2": "NUM_CLASSES = 31\nAUDIO_SR = 16000\nAUDIO_LENGTH = 16000\nLIBROSA_AUDIO_LENGTH = 22050\nEPOCHS = 25\ncategories = {'stop': 0, 'nine': 1, 'off': 2, 'four': 3, 'right': 4,\n 'eight': 5, 'one': 6, 'bir...
[ 0, 1, 2 ]
""" Utilities used by other modules. """ import csv import datetime import hashlib import json import re import string import subprocess import uuid import xml.etree.ElementTree as ET from alta import ConfigurationFromYamlFile from pkg_resources import resource_filename from ..__details__ import __appname__ from appd...
normal
{ "blob_id": "b16c847912944e0563492d35768b5b5bf3a506c7", "index": 1569, "step-1": "<mask token>\n\n\nclass IEMRunInfoReader:\n \"\"\"\n Illumina Experimental Manager RunInfo xml reader.\n \"\"\"\n\n def __init__(self, f):\n self.xml_file = f\n self.tree = ET.parse(self.xml_file)\n ...
[ 25, 27, 28, 36, 38 ]
# -*- coding: utf-8 -*- import pytest from bravado.client import ResourceDecorator from bravado.client import SwaggerClient def test_resource_exists(petstore_client): assert type(petstore_client.pet) == ResourceDecorator def test_resource_not_found(petstore_client): with pytest.raises(AttributeError) as ex...
normal
{ "blob_id": "5ee1d8ef7ec4b191e0789ceb9c6dd2d58af526a0", "index": 7875, "step-1": "<mask token>\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(AttributeError) as excinfo:\n petstore_client.foo\n assert 'foo not found' in str(excinfo.value)\n\n\n@pytest.fixture\ndef client_tag...
[ 2, 3, 4, 5, 6 ]
""" Stirng - Liste - Dosya - Fonksiyon yazıyoruz. - Bu fonksiyon iki parametre alacak. (dosya, string) 1. sorun : Dosyanın içinde string var ise True döndürecek yok ise False 2. sorun : Dosyanın içinde string bulunursa ilk bulunduğu konumu return edecek 3. sorun : Dosyanın içerisinde yazdığımız strinng kaç k...
normal
{ "blob_id": "0d3cc85cd18ee197b24c8b01b71afe82110bfad2", "index": 3487, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef fonkString(text, string):\n if string in text:\n print('TRUE')\n print(text.index(string), '. sirada ilk', string, 'bulundu')\n print(text.count(string), '...
[ 0, 1, 2, 3 ]
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.contenttypes.models import ContentType from User.forms import EditProfileForm from User import forms from django.db.models import Q from django.contrib import messages from django.urls import reverse from django.http import HttpRespons...
normal
{ "blob_id": "e9fab2bb49cfda00b8cfedafab0009f691d11ec9", "index": 9924, "step-1": "<mask token>\n\n\ndef post_create(request):\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n user = request.POST.get('user')\n title = request.POST.get('title')\n ...
[ 5, 6, 7, 8, 10 ]
#!/usr/bin/env python # coding=utf-8 operators = ['-', '~', '++', '--', '*', '!', '/', '*', '%', '+', '-', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '='] types = ['int ', 'double ', 'float ', 'char '] toDelete = types + ['struct '] toRepleace = [('printf(', 'print('), ('++', ' += 1'), ('--', ' -= 1')...
normal
{ "blob_id": "082e3350c5827ff2ca909084f2d6a206ae21a7e6", "index": 3240, "step-1": "<mask token>\n\n\ndef isChar(c):\n return c > 'a' and c < 'z' or c > 'A' and c < 'Z'\n\n\ndef isOperator(c):\n return c in operators\n\n\ndef isDefun(line):\n return '(' in line and ')' in line and sum([(i in line) for i i...
[ 10, 12, 15, 16, 17 ]
from translit import convert_input def openfile(name): f = open(name, 'r', encoding = 'utf-8') text = f.readlines() f.close() return text def makedict(text): A = [] for line in text: if 'lex:' in line: a = [] a.append(line[6:].replace('\n','')) ...
normal
{ "blob_id": "29e54a9ec0d65965645ac4aabf8c247a8857a25f", "index": 3778, "step-1": "<mask token>\n\n\ndef openfile(name):\n f = open(name, 'r', encoding='utf-8')\n text = f.readlines()\n f.close()\n return text\n\n\ndef makedict(text):\n A = []\n for line in text:\n if 'lex:' in line:\n ...
[ 5, 6, 7, 8, 9 ]
import sys, os class Extractor: def __init__(self, prefix=''): self.variables = {} self.prefix = os.path.basename(prefix) ''' Returns the variable name if a variable with the value <value> is found. ''' def find_variable_name(self, value): for var, val in self.v...
normal
{ "blob_id": "dffcaf47ec8e0daa940e7047f11681ef3eabc772", "index": 8591, "step-1": "<mask token>\n\n\nclass Extractor:\n\n def __init__(self, prefix=''):\n self.variables = {}\n self.prefix = os.path.basename(prefix)\n <mask token>\n\n def find_variable_name(self, value):\n for var, v...
[ 4, 6, 7, 8, 9 ]
import time if __name__ == '__main__': for i in range(10): print('here %s' % i) time.sleep(1) print('TEST SUCEEDED')
normal
{ "blob_id": "a159f9f9cc06bb9d22f84781fb2fc664ea204b64", "index": 6856, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n for i in range(10):\n print('here %s' % i)\n time.sleep(1)\n print('TEST SUCEEDED')\n", "step-3": "import time\nif __name__ == '__main__...
[ 0, 1, 2 ]
import discord import requests import math from keys import GITHUB_DISCORD_TOKEN, GITHUB_FORTNITE_API_KEY client = discord.Client() # Constant DISCORD_TOKEN = GITHUB_DISCORD_TOKEN FORTNITE_API_KEY = GITHUB_FORTNITE_API_KEY LIST = ['Verified'] VERIFIED = 4 # Return the current season squad K/D of the fortnite player...
normal
{ "blob_id": "6c6a49dfced680fe034cbbc2fa28d57d2aa1273e", "index": 8973, "step-1": "<mask token>\n\n\ndef get_ratio(username):\n try:\n print(username)\n link = 'https://api.fortnitetracker.com/v1/profile/pc/' + username\n response = requests.get(link, headers={'TRN-Api-Key': FORTNITE_API_K...
[ 1, 2, 3, 4, 5 ]
"""Module containing class `Station`.""" from zoneinfo import ZoneInfo import datetime from vesper.util.named import Named class Station(Named): """Recording station.""" def __init__( self, name, long_name, time_zone_name, latitude=None, longitude=None, elevation=None...
normal
{ "blob_id": "ad09880b9e06a129b9623be2a086ebcc8dc55c2c", "index": 9079, "step-1": "<mask token>\n\n\nclass Station(Named):\n <mask token>\n\n def __init__(self, name, long_name, time_zone_name, latitude=None,\n longitude=None, elevation=None):\n super().__init__(name)\n self._long_name ...
[ 6, 7, 9, 10, 11 ]
import csv import glob import random import sys from math import ceil, floor from os.path import basename, exists, dirname, isfile import numpy as np import keras from keras import Model, Input, regularizers from keras.layers import TimeDistributed, LSTMCell, Reshape, Dense, Lambda, Dropout, Concatenate from keras.cal...
normal
{ "blob_id": "c925bed2f4d8120e156caebbe8e6bf9d6a51ee37", "index": 3330, "step-1": "<mask token>\n\n\nclass VideoClassifier:\n\n def __init__(self, train_mode='late_fusion', video_model_path=None,\n time_step=16, base_path='/user/vlongobardi/AFEW/aligned/',\n feature_name='emobase2010_100', stride...
[ 7, 11, 13, 14, 18 ]
#!/usr/bin/env python from distutils.core import setup setup( name='RBM', version='0.0.1', description='Restricted Boltzmann Machines', long_description='README', install_requires=['numpy','pandas'], )
normal
{ "blob_id": "fab7ee8a7336ba2c044adce4cc8483af78b775ba", "index": 1827, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='RBM', version='0.0.1', description=\n 'Restricted Boltzmann Machines', long_description='README',\n install_requires=['numpy', 'pandas'])\n", "step-3": "from distutils...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python import psycopg2 DBNAME = "news" query1 = """ select title, count(*) as numOfViews from articles,log where concat('/article/', articles.slug) = log.path group by title order by numOfViews desc limit 3; """ query2 = """ select authors.name, count(*) as numOfViews from articles, authors, log where...
normal
{ "blob_id": "612a3d168a09fc26530b95d258cbb4de6728419d", "index": 3721, "step-1": "<mask token>\n\n\ndef fileWrite(content):\n \"\"\" write result to result.txt \"\"\"\n file = open('./result.txt', 'w')\n file.write(content)\n file.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_d...
[ 1, 2, 5, 6, 7 ]
def getGC(st): n = 0 for char in st: if char == 'C' or char == 'G': n += 1 return n while True: try: DNA = input() ln = int(input()) maxLen = 0 subDNA = '' for i in range(len(DNA) - ln + 1): sub = DNA[i:i + ln] if getG...
normal
{ "blob_id": "afe63f94c7107cf79e57f695df8543e0786a155f", "index": 6556, "step-1": "<mask token>\n", "step-2": "def getGC(st):\n n = 0\n for char in st:\n if char == 'C' or char == 'G':\n n += 1\n return n\n\n\n<mask token>\n", "step-3": "def getGC(st):\n n = 0\n for char in st...
[ 0, 1, 2 ]
from django.contrib import admin from .models import Sport from .models import Action admin.site.register(Sport) admin.site.register(Action)
normal
{ "blob_id": "ab38371ee3941e214344497b7e56786908a9b3d1", "index": 2236, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.site.register(Sport)\nadmin.site.register(Action)\n", "step-3": "from django.contrib import admin\nfrom .models import Sport\nfrom .models import Action\nadmin.site.register(Sport...
[ 0, 1, 2 ]
import logging from pathlib import Path import numpy as np import torch import re import json from helpers import init_helper, data_helper, vsumm_helper, bbox_helper from modules.model_zoo import get_model logger = logging.getLogger() def evaluate(model, val_loader, nms_thresh, device): model.eval() stats ...
normal
{ "blob_id": "dd3419f42a3b1aafd1d4f5d88189fb3c6bd0c67e", "index": 4233, "step-1": "<mask token>\n\n\ndef evaluate(model, val_loader, nms_thresh, device):\n model.eval()\n stats = data_helper.AverageMeter('fscore', 'diversity')\n json_file = []\n with torch.no_grad():\n for test_key, seq, gt, cp...
[ 4, 5, 7, 8, 10 ]
# Author: Sam Erickson # Date: 2/23/2016 # # Program Description: This program gives the integer coefficients x,y to the # equation ax+by=gcd(a,b) given by the extended Euclidean Algorithm. def extendedEuclid(a,b): """ Preconditions - a and b are both positive integers. Posconditions - The equation for ax...
normal
{ "blob_id": "36e5b0f40b8016f39120f839766db0ac518c9bed", "index": 4712, "step-1": "<mask token>\n", "step-2": "def extendedEuclid(a, b):\n \"\"\"\n Preconditions - a and b are both positive integers.\n Posconditions - The equation for ax+by=gcd(a,b) has been returned where\n x and y ...
[ 0, 1, 2 ]
# -*- coding: utf-8 -*- """Labeled entry widget. The goal of these widgets is twofold: to make it easier for developers to implement dialogs with compound widgets, and to naturally standardize the user interface presented to the user. """ import logging import seamm_widgets as sw import tkinter as tk import tkinter....
normal
{ "blob_id": "111186f1d45b9cf3bf9065c7fa83a8f3f796bbe1", "index": 5841, "step-1": "<mask token>\n\n\nclass LabeledEntry(sw.LabeledWidget):\n <mask token>\n\n @property\n def value(self):\n return self.get()\n <mask token>\n\n def show(self, *args):\n \"\"\"Show only the specified subw...
[ 5, 6, 8, 9, 11 ]
from __future__ import print_function import os import shutil import pymake import flopy # set up paths dstpth = os.path.join('temp') if not os.path.exists(dstpth): os.makedirs(dstpth) mp6pth = os.path.join(dstpth, 'Modpath_7_1_000') expth = os.path.join(mp6pth, 'examples') exe_name = 'mp7' srcpth = os.path.join(...
normal
{ "blob_id": "ddaba7a8b53072da36224dd4618696ebf0e9a4e4", "index": 1015, "step-1": "<mask token>\n\n\ndef compile_code():\n if os.path.isdir(mp6pth):\n shutil.rmtree(mp6pth)\n url = 'https://water.usgs.gov/ogw/modpath/Modpath_7_1_000.zip'\n pymake.download_and_unzip(url, pth=dstpth)\n pth = os.p...
[ 7, 8, 9, 11, 12 ]
# Generated by Django 3.0.10 on 2020-12-19 15:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ("wagtailadmin", "0001_create_admin_access_permissions"), ] operations = [ migrations.CreateModel( name="Admi...
normal
{ "blob_id": "52a4213a1729e25f96faebc5fd4f299017446c5a", "index": 6370, "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 ]
from django.urls import reverse from django.utils.translation import get_language from drf_dynamic_fields import DynamicFieldsMixin from geotrek.api.v2.serializers import AttachmentSerializer from mapentity.serializers import MapentityGeojsonModelSerializer from rest_framework import serializers as rest_serializers fro...
normal
{ "blob_id": "dfd5915428dc8f15fb61c5d81f22dfecfe29af15", "index": 6409, "step-1": "<mask token>\n\n\nclass SpeciesSerializer(TranslatedModelSerializer, PictogramSerializerMixin):\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n model = sensitivity_models.Species\n fields ...
[ 10, 11, 12, 13, 16 ]
import os , sys , time print(""" ███████████████████████████████ █ █ █═╬═════════════════════════╬═█ █ ║░░░░░░░░░░░░░░░░░░░░░░░░░║ █ █ ║░░░░Wi-fi Fucker Tool░░░░║ █ █ ║░░░░░░░░░░░░░░░░░░░░░░░░░║ █ █ ║░░░░░coded by arda6░░░░░░║ █ █ ║░░░░░░░░░░░░░░░░░...
normal
{ "blob_id": "15eb205e6bd36844fdfc8c05efbc3a3d584c122d", "index": 7238, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(\n \"\"\"\n\n ███████████████████████████████\n █ █\n █═╬═════════════════════════╬═█\n █ ║░░░░░░░░░░░░░░░░░░░░░░░░░║ █\n █ ║░░░░Wi-fi ...
[ 0, 1, 2, 3, 4 ]
""" Data pre-processing """ import os import corenlp import numpy as np import ujson as json from tqdm import tqdm from collections import Counter from bilm import dump_token_embeddings import sys sys.path.append('../..') from LIB.utils import save def process(json_file, outpur_dir, exclude_titles=None, include_titl...
normal
{ "blob_id": "0c37806f0a7c0976711edd685fd64d2616147cb6", "index": 4623, "step-1": "<mask token>\n\n\ndef process(json_file, outpur_dir, exclude_titles=None, include_titles=None):\n \"\"\"\n :param json_file: original data in json format\n :param outpur_dir: the output directory of pre-processed data\n ...
[ 5, 6, 7, 8, 9 ]
import seaborn as sns tips = sns.load_dataset('iris') sns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')
normal
{ "blob_id": "274af2a0b758472ca4116f1dfa47069647babf57", "index": 8543, "step-1": "<mask token>\n", "step-2": "<mask token>\nsns.violinplot(x='species', y='sepal_length', data=tips, palette='rainbow')\n", "step-3": "<mask token>\ntips = sns.load_dataset('iris')\nsns.violinplot(x='species', y='sepal_length', d...
[ 0, 1, 2, 3 ]
import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x...
normal
{ "blob_id": "e221553f866de8b3e175197a40982506bf8c1ef9", "index": 205, "step-1": "<mask token>\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.n...
[ 3, 4, 5, 6, 7 ]
#!/usr/bin/env python from setuptools import setup, find_packages #if sys.argv[-1] == 'publish': # os.system('python setup.py sdist upload') # sys.exit() with open('bace/__init__.py') as fid: for line in fid: if line.startswith('__version__'): VERSION = line.strip().split()[-1][1:-1] ...
normal
{ "blob_id": "d28571214805df766c2cc2f45a6b5bea88d7ac18", "index": 9371, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('bace/__init__.py') as fid:\n for line in fid:\n if line.startswith('__version__'):\n VERSION = line.strip().split()[-1][1:-1]\n break\nwith open...
[ 0, 1, 2, 3, 4 ]
from multiprocessing import Process, Queue def f(q): for i in range(0,100): print("come on baby") q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() for j in range(0, 2000): if j == 1800: print(q.get()) ...
normal
{ "blob_id": "c7258d77db2fe6e1470c972ddd94b2ed02f48003", "index": 3390, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef f(q):\n for i in range(0, 100):\n print('come on baby')\n q.put([42, None, 'hello'])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef f(q):\n for i in rang...
[ 0, 1, 2, 3, 4 ]
import os import pprint import math import sys import datetime as dt from pathlib import Path import RotateCipher import ShiftCipher import TranspositionCipher def process_textfile( string_path: str, encryption_algorithm: str, algorithm_key: float, output_folderpath: str = str( ...
normal
{ "blob_id": "5dccd015a90927e8d2a9c0ea4b11b24bfd4bb65e", "index": 5690, "step-1": "<mask token>\n\n\ndef manual_test():\n dict_processedtext = process_textfile(string_path=\n 'C:\\\\Users\\\\Rives\\\\Downloads\\\\Quizzes\\\\Quiz 0 Overwrite Number 1.txt',\n encryption_algorithm='rotate', algorith...
[ 2, 3, 4, 5, 6 ]
#!/usr/bin/python # ~~~~~============== HOW TO RUN ==============~~~~~ # 1) Configure things in CONFIGURATION section # 2) Change permissions: chmod +x bot.py # 3) Run in loop: while true; do ./bot.py; sleep 1; done from __future__ import print_function import sys import socket import json import time # ~~~~~==...
normal
{ "blob_id": "56c5c515de8490f2e3516563e037c375aba03667", "index": 3221, "step-1": "<mask token>\n\n\ndef connect():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((exchange_hostname, port))\n return s.makefile('rw', 1)\n\n\ndef write_to_exchange(exchange, obj):\n json.dump(obj, ex...
[ 5, 8, 9, 10, 16 ]
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from kneed import KneeLocator #Create a panda data frame from the csv file df = pd.read_csv('ClusterPlot.csv', usecols=['V1','V2']) #Convert the panda data frame to a NumPy array arr = df.to_numpy() #Code used t...
normal
{ "blob_id": "09417014963172fc71b4268aafdec1405c04f34d", "index": 3472, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(1, 11):\n km = KMeans(n_clusters=i, init='random', n_init=10, max_iter=300, tol=\n 0.0001, random_state=0)\n km.fit(arr)\n distortions.append(km.inertia_)\n...
[ 0, 1, 2, 3, 4 ]
a, b = map(int, input().split()) def mult(a, b): if a > 9 or b > 9 or a < 1 or b < 1: print(-1) else: print(a * b) mult(a, b)
normal
{ "blob_id": "991fa5f9c83a1821e62f7baacbc56a4d31982312", "index": 3681, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef mult(a, b):\n if a > 9 or b > 9 or a < 1 or b < 1:\n print(-1)\n else:\n print(a * b)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef mult(a, b):\n ...
[ 0, 1, 2, 3 ]
import os, datetime import urllib from flask import (Flask, flash, json, jsonify, redirect, render_template, request, session, url_for) import util.database as db template_path=os.path.dirname(__file__)+"/templates" file="" if template_path!="/templates": app = Flask("__main__",tem...
normal
{ "blob_id": "5c20eefe8111d44a36e69b873a71377ee7bfa23d", "index": 6768, "step-1": "<mask token>\n\n\n@app.route('/')\ndef home():\n if 'username' in session:\n id_num = db.search_user_list(session['username'], is_usrname=True)[0][2\n ]\n finavail = db.search_finance_list(id_num)\n ...
[ 14, 15, 16, 18, 19 ]
from connect_to_elasticsearch import * # returns the name of all indices in the elasticsearch server def getAllIndiciesNames(): indicies = set() for index in connect_to_elasticsearch().indices.get_alias( "*" ): indicies.add( index ) print( index ) return indicies
normal
{ "blob_id": "23c75840efd9a8fd68ac22d004bfe3b390fbe612", "index": 2314, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef getAllIndiciesNames():\n indicies = set()\n for index in connect_to_elasticsearch().indices.get_alias('*'):\n indicies.add(index)\n print(index)\n return in...
[ 0, 1, 2, 3 ]
import urllib2 import urllib import json import gzip from StringIO import StringIO service_url = 'https://babelfy.io/v1/disambiguate' lang = 'EN' key = '' filehandle = open('triples/triples2.tsv') # the triples and the sentences where the triples were extracted filehandle_write = open('triples/disambiguated_triples...
normal
{ "blob_id": "cd9f94d55eb13f5fc9959546e89a0af8ab2ea0db", "index": 6147, "step-1": "import urllib2\nimport urllib\nimport json\nimport gzip\n\nfrom StringIO import StringIO\n\nservice_url = 'https://babelfy.io/v1/disambiguate'\nlang = 'EN'\nkey = ''\n\nfilehandle = open('triples/triples2.tsv') # the triples and t...
[ 0 ]
import scrapy from kingfisher_scrapy.base_spiders import BigFileSpider from kingfisher_scrapy.util import components, handle_http_error class France(BigFileSpider): """ Domain France Swagger API documentation https://doc.data.gouv.fr/api/reference/ """ name = 'france' # SimpleSpi...
normal
{ "blob_id": "369bffa21b5b8c0ca1d93da3aa30a38e2f4c82cc", "index": 9451, "step-1": "<mask token>\n\n\nclass France(BigFileSpider):\n <mask token>\n <mask token>\n <mask token>\n\n def start_requests(self):\n url = (\n 'https://www.data.gouv.fr/api/1/datasets/donnees-essentielles-de-la...
[ 3, 4, 5, 6, 7 ]
# coding: utf-8 # 2021/5/29 @ tongshiwei import logging def get_logger(): _logger = logging.getLogger("EduNLP") _logger.setLevel(logging.INFO) _logger.propagate = False ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('[%(name)s, %(levelname)s] %(message)s')) ch.setLevel(logging....
normal
{ "blob_id": "41f71589d3fb9f5df218d8ffa0f608a890c73ad2", "index": 8486, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_logger():\n _logger = logging.getLogger('EduNLP')\n _logger.setLevel(logging.INFO)\n _logger.propagate = False\n ch = logging.StreamHandler()\n ch.setFormatter(...
[ 0, 1, 2, 3, 4 ]
from flask import Flask app = Flask(__name__) import orderapi, views, models, processing if __name__=="__main__": orderapi.app.debug = True orderapi.app.run(host='0.0.0.0', port=34203) views.app.debug = True views.app.run(host='0.0.0.0', port=42720)
normal
{ "blob_id": "3218a9e82cd19bab1680079aee5f09a97992629e", "index": 6038, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n orderapi.app.debug = True\n orderapi.app.run(host='0.0.0.0', port=34203)\n views.app.debug = True\n views.app.run(host='0.0.0.0', port=42720)\n", ...
[ 0, 1, 2, 3, 4 ]
import requests import os from bs4 import BeautifulSoup from urllib.parse import urljoin CURRENT_DIR = os.getcwd() DOWNLOAD_DIR = os.path.join(CURRENT_DIR, 'malware_album') os.makedirs(DOWNLOAD_DIR, exist_ok=True) url = 'http://old.vision.ece.ucsb.edu/~lakshman/malware_images/album/' class Extractor(object): "...
normal
{ "blob_id": "a53d7b4c93fa49fb0162138d4a262fe7a5546148", "index": 5215, "step-1": "<mask token>\n\n\nclass Extractor(object):\n \"\"\"docstring for Parser\"\"\"\n\n def __init__(self, html, base_url):\n self.soup = BeautifulSoup(html, 'html5lib')\n self.base_url = base_url\n\n def get_album...
[ 9, 10, 11, 13, 14 ]
#ERP PROJECT import pyrebase import smtplib config = { "apiKey": "apiKey", "authDomain": "erproject-dd24e-default-rtdb.firebaseapp.com", "databaseURL": "https://erproject-dd24e-default-rtdb.firebaseio.com", "storageBucket": "erproject-dd24e-default-rtdb.appspot.com" } firebase = pyrebase.initialize_app(conf...
normal
{ "blob_id": "3e7e6d7a0137d91dc7437ff91a39d7f8faad675e", "index": 7075, "step-1": "<mask token>\n\n\ndef j():\n global i\n import pandas as pd\n st1.update({i: st})\n data = pd.DataFrame(st1)\n print(data)\n data.to_csv('student.csv')\n fa1.update({i: fa})\n data1 = pd.DataFrame(fa1)\n ...
[ 1, 2, 3, 4, 5 ]
import pandas as pd import numpy as np df = pd.DataFrame([['Hospital1', '2019-10-01'], ['Hospital2', '2019-10-01'], ['Hospital3', '2019-10-01'], ['Hospital1', '2019-10-01'], ['Hospital2', '2019-10-02'], ['Hospital3', '2019-10-02'], ['Hospital2', '2019-10-03'], ['Hospital2', '2019-10-04'], ['Hospital3', '201...
normal
{ "blob_id": "8d8f1f0dbb76b5c536bd1a2142bb61c51dd75075", "index": 9573, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(pd.pivot_table(df, values='Date', index='Hospital_Name', aggfunc=np.size)\n )\nprint(df2.sum())\n", "step-3": "<mask token>\ndf = pd.DataFrame([['Hospital1', '2019-10-01'], ['H...
[ 0, 1, 2, 3 ]
no_list = {"tor:", "getblocktemplate", " ping ", " pong "} for i in range(1, 5): with open("Desktop/"+str(i)+".log", "r") as r: with open("Desktop/"+str(i)+"-clean.log", "a+") as w: for line in r: if not any(s in line for s in no_list): w.write(line)
normal
{ "blob_id": "f14a8d0d51f0baefe20b2699ffa82112dad9c38f", "index": 6582, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(1, 5):\n with open('Desktop/' + str(i) + '.log', 'r') as r:\n with open('Desktop/' + str(i) + '-clean.log', 'a+') as w:\n for line in r:\n ...
[ 0, 1, 2, 3 ]
from floppy.node import Node, Input, Output, Tag, abstractNode @abstractNode class StringNode(Node): Tag('StringOperations') class StringAppend(StringNode): """ Creates a new node which combines two strings. These can be seperated by a delimiter. :param nodeClass: subclass object of 'Node'. :ret...
normal
{ "blob_id": "1bb151171bbbb899456324056be3634e87b5c8fb", "index": 3494, "step-1": "<mask token>\n\n\nclass StringAppend(StringNode):\n <mask token>\n Input('First', str)\n Input('Second', str)\n Input('Delimiter', str, optional=True, default='')\n Output('Joined', str)\n <mask token>\n\n\nclass ...
[ 4, 5, 6, 8 ]
class Point: def __init__(self,x,y): self.x=x self.y=y def __str__(self): return "({0},{1})".format(self.x,self.y) def __add__(self, other): self.x=self.x+other.x self.y=self.y+other.y return Point(self.x,self.y) p1=Point(1,2) p2=Point(3,4) p...
normal
{ "blob_id": "1bebd3c18742f5362d2e5f22c539f6b13ad58d2a", "index": 2873, "step-1": "class Point:\n <mask token>\n\n def __str__(self):\n return '({0},{1})'.format(self.x, self.y)\n\n def __add__(self, other):\n self.x = self.x + other.x\n self.y = self.y + other.y\n return Poin...
[ 3, 4, 5, 6, 7 ]
#! /usr/bin/env python3 import common, os, shutil, sys def main(): os.chdir(common.root) shutil.rmtree('shared/target', ignore_errors = True) shutil.rmtree('platform/build', ignore_errors = True) shutil.rmtree('platform/target', ignore_errors = True) shutil.rmtree('tests/target', ignore_errors = True) shut...
normal
{ "blob_id": "2305d0b7ec0d9e08e3f1c0cedaafa6ed60786e50", "index": 7359, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n os.chdir(common.root)\n shutil.rmtree('shared/target', ignore_errors=True)\n shutil.rmtree('platform/build', ignore_errors=True)\n shutil.rmtree('platform/ta...
[ 0, 1, 2, 3, 4 ]
total = totmil = cont = menor = 0 barato = ' ' print('-' * 40) print('LOJA SUPER BARATÃO') print('-' * 40) while True: produto = str(input('Nome do Produto: ')) preco = float(input('Preço: ')) cont += 1 total += preco if preco > 1000: totmil += 1 if cont == 1 or preco < menor: ba...
normal
{ "blob_id": "35b24ffa14f8b3c2040d5becc8a35721e86d8b3d", "index": 345, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('-' * 40)\nprint('LOJA SUPER BARATÃO')\nprint('-' * 40)\nwhile True:\n produto = str(input('Nome do Produto: '))\n preco = float(input('Preço: '))\n cont += 1\n total += ...
[ 0, 1, 2 ]
import json from flask import Flask, request, jsonify from lib.chess_utils import run_game def create_app(): app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/process_game', methods=['POST']) def process_game(): move_sequence = json.load...
normal
{ "blob_id": "60ca8b1d7307a9d8183e3617f238efcfb9d707dd", "index": 1950, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef create_app():\n app = Flask(__name__)\n\n @app.route('/')\n def hello_world():\n return 'Hello, World!'\n\n @app.route('/process_game', methods=['POST'])\n d...
[ 0, 1, 2, 3 ]
from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags from datetime import datetime, timedelta def sendmail(subject, template, to, context): template_str = 'app/' + template + '.html' html_msg = render_to_string(template_str, {'data...
normal
{ "blob_id": "0349a8a4841b024afd77d20ae18810645fad41cd", "index": 4883, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sendmail(subject, template, to, context):\n template_str = 'app/' + template + '.html'\n html_msg = render_to_string(template_str, {'data': context})\n plain_msg = strip_...
[ 0, 1, 2 ]
from rest_framework import filters from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from apis.models import Contact, Address, InvoicePosition, Country, Invoice from apis.serializers import ContactSerializer, AddressS...
normal
{ "blob_id": "43bad38d209b5c326cb9f17ba1ae135d06320e97", "index": 145, "step-1": "<mask token>\n\n\nclass InvoicePositionViewSet(ModelViewSet):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass CountryListView(ListAPIView):\n queryset = Country.objects.all()\n serializer_class = CountrySerial...
[ 5, 6, 9, 11, 12 ]
from django.shortcuts import render from .models import Recipe, Author def index(request): recipes_list = Recipe.objects.all() return render(request, "index.html", {"data": recipes_list, "title": "Recipe Box"}) def recipeDetail(request, recipe_id): recipe_detail = Recipe.objects.filter...
normal
{ "blob_id": "f0f8ad7b65707bcf691847ccb387e4d026b405b5", "index": 6395, "step-1": "<mask token>\n\n\ndef authorDetail(request, author_id):\n author = Author.objects.filter(id=author_id).first()\n recipes = Recipe.objects.filter(author=author_id)\n return render(request, 'author_detail.html', {'recipes': ...
[ 1, 2, 3, 4, 5 ]
from urllib.parse import quote from top_model import db from top_model.ext.flask import FlaskTopModel from top_model.filesystem import ProductPhotoCIP from top_model.webstore import Product, Labo from unrest import UnRest class Hydra(FlaskTopModel): def __init__(self, *args, **kwargs): super().__init__(*...
normal
{ "blob_id": "de3a4053b5b0d4d2d5c2dcd317e64cf9b4faeb75", "index": 562, "step-1": "<mask token>\n\n\nclass Hydra(FlaskTopModel):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.config['CLIENT_ID'] = 4\n self.config['BASE_IMAGE_URL'\n ] = 'https...
[ 3, 6, 7, 8, 9 ]
#!/usr/bin/env python #------------------------------------------------------------------------------- # # Circle finder. # # Rowan Leeder # #------------------------------------------------------------------------------- # # Listens on the 'scan' and 'base_scan' topics. These are the pioneers SICK # topic and Stage's ...
normal
{ "blob_id": "3ac02308959749b8cd264e660c3d6334fd385fd4", "index": 1114, "step-1": "#!/usr/bin/env python\n#-------------------------------------------------------------------------------\n#\n# Circle finder.\n#\n# Rowan Leeder\n#\n#-------------------------------------------------------------------------------\n#...
[ 0 ]
""" Pattern matching problem Boyer Moore algorithm First is my attempt, below is the code provided in the book Idea: Optimize brute force approach using 2 heuristics: - Looking-Glass: start searches from last character of the pattern and work backwards - Character-Jump: During testing of a pattern P, a mismatch in T[i...
normal
{ "blob_id": "c418b9b6903ebdad204a3a55f2384a94a3be0d09", "index": 5561, "step-1": "<mask token>\n\n\ndef find_boyer_moore2(T, P):\n \"\"\" return lowest index of T at which the substring P begins or -1\"\"\"\n n, m = len(T), len(P)\n if m == 0:\n return 0\n last = {}\n for k in range(m):\n ...
[ 1, 2, 3, 4, 5 ]
#usage: #crawl raw weibo text data from sina weibo users(my followees) #in total, there are 20080 weibo tweets, because there is uplimit for crawler # -*- coding: utf-8 -*- import weibo APP_KEY = 'your app_key' APP_SECRET = 'your app_secret' CALL_BACK = 'your call back url' def run(): token = "your access token got...
normal
{ "blob_id": "8a04166e091e2da348928598b2356c8ad75dd831", "index": 5889, "step-1": "#usage:\n#crawl raw weibo text data from sina weibo users(my followees)\n#in total, there are 20080 weibo tweets, because there is uplimit for crawler\n\n# -*- coding: utf-8 -*-\nimport weibo\n\nAPP_KEY = 'your app_key'\nAPP_SECRET...
[ 0 ]
alunos = list() while True: nome = str(input('Nome: ')) nota1 = float(input('Nota 1: ')) nota2 = float(input('Nota 2: ')) media = (nota1+nota2)/2 alunos.append([nome, [nota1, nota2], media]) pergunta = str(input('Quer continuar [S/N]? ')).upper()[0] if pergunta == 'N': break print('-...
normal
{ "blob_id": "8dcd4914c58a7ecafdfdd70b698ef3b7141386a6", "index": 2632, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n nome = str(input('Nome: '))\n nota1 = float(input('Nota 1: '))\n nota2 = float(input('Nota 2: '))\n media = (nota1 + nota2) / 2\n alunos.append([nome, [nota1,...
[ 0, 1, 2, 3 ]