code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
from collections import deque
from etaprogress.eta import ETA
def test_linear_slope_1():
eta = ETA(100)
eta._timing_data = deque([(10, 10), (20, 20), (30, 30), (40, 40)])
getattr(eta, '_calculate')()
assert 100 == eta.eta_epoch
assert 1.0 == eta.rate
assert 1.0 == eta.rate_unstable
def test_... | normal | {
"blob_id": "810017cd5814fc20ebcdbdf26a32ea1bcfc88625",
"index": 2164,
"step-1": "<mask token>\n\n\ndef test_linear_slope_2():\n eta = ETA(100)\n eta._timing_data = deque([(10, 20), (20, 40), (30, 60), (40, 80)])\n getattr(eta, '_calculate')()\n assert 50 == eta.eta_epoch\n assert 2.0 == eta.rate\... | [
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-07-21 12:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | normal | {
"blob_id": "722739086d2777085fdbfdbddef205aaf025580d",
"index": 4291,
"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 = [('user', '000... | [
0,
1,
2,
3,
4
] |
# content of conftest.py
import pytest
import sys
sys.path.insert(1, '../Generic')
import PQ9Client
def pytest_configure(config):
print("pytest_configure")
def pytest_collection_modifyitems(session, config, items):
print("sono qui", items)
def pytest_ignore_collect(path, config):
print(path)
... | normal | {
"blob_id": "ad88685e3f1cd5e0ddb42a5982a05ff8ee7b8111",
"index": 1586,
"step-1": "<mask token>\n\n\ndef pytest_addoption(parser):\n print('Option ')\n parser.addoption('--destination', action='store', help=\n 'subsystem address', dest='destination')\n\n\n@pytest.fixture\ndef destination(request):\n ... | [
2,
5,
6,
7,
9
] |
from django.db import models
# Create your models here.
class Glo_EstadoPlan(models.Model):
descripcion_estado = models.CharField(max_length=100)
def __str__(self):
return '{}'.format(self.descripcion_estado) | normal | {
"blob_id": "b0a51877b59e14eefdd662bac468e8ce12343e6b",
"index": 3885,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Glo_EstadoPlan(models.Model):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Glo_EstadoPlan(models.Model):\n descripcion_estado = models.CharFie... | [
0,
1,
3,
4,
5
] |
import knn
datingDataMat,datingLabels = knn.file2matrix('datingTestSet2.txt')
normMat,ranges,minVals = knn.autoNorm(datingDataMat)
print normMat
print ranges
print minVals | normal | {
"blob_id": "f28222625e28939b34b1b5c21d28dbf9c49c6374",
"index": 8635,
"step-1": "import knn\n\ndatingDataMat,datingLabels = knn.file2matrix('datingTestSet2.txt')\nnormMat,ranges,minVals = knn.autoNorm(datingDataMat)\n\nprint normMat\nprint ranges\nprint minVals",
"step-2": null,
"step-3": null,
"step-4": ... | [
0
] |
from ROOT import *
gSystem.Load("libAnalysis")
import sys
import argparse
parser = argparse.ArgumentParser(description="Python script to process and merge showers.")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", help="Turn on verbose output",
action="store_tru... | normal | {
"blob_id": "d57b91bf41f031e3362dabdef8c67a0da04fe577",
"index": 7540,
"step-1": "from ROOT import *\ngSystem.Load(\"libAnalysis\")\nimport sys\n\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Python script to process and merge showers.\")\ngroup = parser.add_mutually_exclusive_group()\ngroup... | [
0
] |
#LIBRERIAS
import cv2
import numpy as np
#FUNCION: recibe una imagen y te devuelve las coordenadas de las caras
def face_detector(img, face_cascade, eye_cascade, face_f):
#variables face_f
xf = face_f[0]
yf = face_f[1]
wf = face_f[2]
hf = face_f[3]
#variables img
xi = 0
yi = 0
... | normal | {
"blob_id": "1df3a5dc8ed767e20d34c2836eed79872a21a016",
"index": 9948,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef face_detector(img, face_cascade, eye_cascade, face_f):\n xf = face_f[0]\n yf = face_f[1]\n wf = face_f[2]\n hf = face_f[3]\n xi = 0\n yi = 0\n wi = img.shape[... | [
0,
1,
2,
3
] |
'''
Функція replace() може використовуватися для заміни будь-якого слова у рядку іншим словом.
Прочитайте кожен рядок зі створеного у попередньому завданні файлу learning_python.txt і замініть слово Python назвою іншої мови,
наприклад C при виведенні на екран. Це завдання написати в окремій функції.
'''
def reader():... | normal | {
"blob_id": "6d80a89a47b68fd8d81739787897355671ca94e9",
"index": 5815,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef reader():\n with open('possibilities.txt', 'r') as file1:\n file_lines = [x.strip() for x in file1.readlines()]\n for e in file_lines:\n n = e.replace(... | [
0,
1,
2,
3
] |
from django.core.validators import RegexValidator
from django.db import models
from .image import Image
class AffiliatedStoreManager(models.Manager):
def get_queryset(self):
return super().get_queryset() \
.select_related('icon') \
.select_related('icon__image_type')
def fin... | normal | {
"blob_id": "e2b439974b66e45a899605bc7234850783c3dfb0",
"index": 2231,
"step-1": "<mask token>\n\n\nclass AffiliatedStoreManager(models.Manager):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass AffiliatedStore(models.Model):\n\n\n class Meta:\n db_table = 'affiliated_store'\n object... | [
5,
6,
7,
9,
10
] |
import flask
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
import pickle
from recent_earnings_tickers import ok_tickers
import re
#---------- Model ----------------#
#with open('/Users/samfunk/ds/metis/project_mcnulty/code/REPLACE_WITH_MODEL_PICKLE', 'rb') as f:
#PREDICTOR =... | normal | {
"blob_id": "3be1947ead65f8e8a9bf73cc8cae2c7d69d8b756",
"index": 1641,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef home_page():\n with open('/Users/samfunk/ds/metis/project_mcnulty/stock_page.html', 'r'\n ) as viz_file:\n return viz_file.read()\n\n\n<mask token>\n",
"step-2": "<mask toke... | [
1,
3,
4,
5,
6
] |
from os import wait
import cv2
import numpy as np
import math
import sys
import types
import operator
## orb 및 bf matcher 선언
orb = cv2.cv2.ORB_create(
nfeatures=5000,
scaleFactor=1.2,
nlevels=8,
edgeThreshold=31,
... | normal | {
"blob_id": "73e7e43e9cfb3c0884480809bc03ade687d641d6",
"index": 733,
"step-1": "<mask token>\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.\n format(seq_num))\n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = f... | [
1,
2,
3,
4,
5
] |
import os
import random
import argparse
from vapory import *
from data import colors, object_types
class Torus(POVRayElement):
""""""
def render_scene(filename, object_type, color, location, rotation):
assert (object_type in object_types)
assert (color in colors)
color = colors[color]
size = ... | normal | {
"blob_id": "f8972067fa88e7e74e05cdcc7bdec184116dec4a",
"index": 7771,
"step-1": "<mask token>\n\n\nclass Torus(POVRayElement):\n \"\"\"\"\"\"\n\n\ndef render_scene(filename, object_type, color, location, rotation):\n assert object_type in object_types\n assert color in colors\n color = colors[color]... | [
3,
4,
5,
6,
7
] |
# Author: Charse
# py 列表的使用
import copy
name = ["111", "222", "333", "444", "555"]
# 从列表中取得元素
print(name[0], name[2]) # 111 333
print(name[1:3]) # 切片 ['222', '333']
print(name[:3]) # ['111', '222', '333'] 与下标从0开始是一样的
print(name[0:3]) # ['111', '222', '333']
print(name[-2:]) # ['444', '555'] 与name
# 往列表中添加... | normal | {
"blob_id": "d517c1e2eb4d37a2584f1603c704efce6834df92",
"index": 7443,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(name[0], name[2])\nprint(name[1:3])\nprint(name[:3])\nprint(name[0:3])\nprint(name[-2:])\nname.append('666')\nname.insert(1, '999')\nprint(name)\n<mask token>\nprint(name)\nname.pop... | [
0,
1,
2,
3,
4
] |
import datetime
import logging
import os
from functools import lru_cache
from authlib.jose import JsonWebKey, jwt
from flask import g, request, jsonify
from lorem_ipsum.model import User, AppContext
import lorem_ipsum
from lorem_ipsum.model import Permission, BlacklistToken
LOGGER = logging.getLogger('lorem-ipsum')
... | normal | {
"blob_id": "97d4387c7bfd141b5a7019b221adb550105d4351",
"index": 604,
"step-1": "<mask token>\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = a... | [
10,
12,
17,
19,
21
] |
# Copyright (c) 2008 Johns Hopkins University.
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without written
# agreement is hereby granted, provided that the above copyright
# notice, the (updated) modification history ... | normal | {
"blob_id": "f614287a2a118484b67f2b16e429a3335416d186",
"index": 3738,
"step-1": "# Copyright (c) 2008 Johns Hopkins University.\n# All rights reserved.\n#\n# Permission to use, copy, modify, and distribute this software and its\n# documentation for any purpose, without fee, and without written\n# agreement is h... | [
0
] |
from web3.auto.infura import w3
import json
import os
with open("contract_abi.json") as f:
info_json = json.load(f)
abi = info_json
mycontract = w3.eth.contract(address='0x091FDeb7990D3E00d13c31b81841d56b33164AD7', abi=abi)
myfilter = mycontract.events.currentResponderState.createFilter(fromBlock=16147303)
#myfilt... | normal | {
"blob_id": "8921c0a17e90f7113d1e0be630a15fc9d74d1780",
"index": 8519,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('contract_abi.json') as f:\n info_json = json.load(f)\n<mask token>\nprint(abi)\nprint(myfilter)\n",
"step-3": "<mask token>\nwith open('contract_abi.json') as f:\n info... | [
0,
1,
2,
3,
4
] |
width,height = int(input("Width? ")), int(input("Height? "))
on_row = 0
while on_row <= height:
if on_row == 0 or on_row == height:
print("*"*width)
else:
stars = "*" + " "*(width-2) + "*"
print(stars)
on_row += 1
# height = 0
# width = 0
# while True:
# try:
# height... | normal | {
"blob_id": "63e96b41906f49f557529a0815da7314d74f6c33",
"index": 6216,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile on_row <= height:\n if on_row == 0 or on_row == height:\n print('*' * width)\n else:\n stars = '*' + ' ' * (width - 2) + '*'\n print(stars)\n on_row +=... | [
0,
1,
2,
3
] |
from bottle import response,request,route,run
from json import dumps
import ConfigParser
import pickle
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.cross_... | normal | {
"blob_id": "f0b5ad49fc47adc54fb16a151b4a0ed563f53a42",
"index": 9482,
"step-1": "from bottle import response,request,route,run\nfrom json import dumps\nimport ConfigParser\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import ... | [
0
] |
#!/usr/bin/env python2.7
from __future__ import print_function, division
import numpy as np
import matplotlib
import os
#checks if there is a display to use.
if os.environ.get('DISPLAY') is None:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import dtk
import sys
import ti... | normal | {
"blob_id": "3acbb37809462ee69ff8792b4ad86b31dba5d630",
"index": 3821,
"step-1": "<mask token>\n\n\ndef load_clusters(file_name):\n if file_name not in load_clusters._cache:\n cluster_data = ClusterData()\n cluster_data.load_file(file_name)\n else:\n cluster_data = load_clusters._cache... | [
5,
6,
7,
8,
9
] |
from multiprocessing import Pool
from pathlib import Path
import os
import re
import json
import string
import math
import GLOBALS
stopWords = {"a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't",
"as", "at", "be", "because", "been", "before", "being", "bel... | normal | {
"blob_id": "19f17044d48c8cc0f9d366cde7edc846ff343462",
"index": 2598,
"step-1": "<mask token>\n\n\ndef search(query, finalIndexPath):\n listOfDicts = list()\n queryList = set()\n tempList = query.strip().lower().replace(\"'\", '').split(' ')\n for word in tempList:\n if word not in stopWords:... | [
4,
5,
6,
7,
8
] |
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
#loading data from CSV
training_data_df = pd.read_csv("sales_data_training.csv")
test_data_df = pd.read_csv("sales_data_test.csv")
#scaler
scaler = MinMaxScaler(feature_range=(0,1))
#scale both inputs and outputs
scaled_training = scaler.fit_transfor... | normal | {
"blob_id": "050e2207ac7331444d39305869c4b25bcbc53907",
"index": 244,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\n 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}'\n .format(scaler.scale_[8], scaler.min_[8]))\n<mask token>\nscaled_training_df.to_csv('... | [
0,
1,
2,
3,
4
] |
import vobject
import glob
import sys
vobj=vobject.readOne(open("Nelson.vcf"))
print vobj.contents
def main(args):
suma = 0
titulos = ['nombre del archivo', 'Total', 'subtotoal', 'rfc', 'fecha', 'ivaTrasladado', 'isrTrasladado', 'ivaRetenido', 'isrRetenido']
import csv
out = csv.writer(open("out.csv"... | normal | {
"blob_id": "a1115766c5f17abc1ba90a3314cb5b9c4aab73d6",
"index": 8169,
"step-1": "import vobject\nimport glob\nimport sys\n\nvobj=vobject.readOne(open(\"Nelson.vcf\"))\nprint vobj.contents\n\n\ndef main(args):\n suma = 0\n titulos = ['nombre del archivo', 'Total', 'subtotoal', 'rfc', 'fecha', 'ivaTrasladad... | [
0
] |
#encoding:UTF-8
from numpy import *
#----------------------------------------------------------------------
def differences(a, b):
""""""
c = a[a!=b]
d = b[a!=b]
nums = nonzero(a!=b)[0]
return concatenate((mat(nums), c, d)).T | normal | {
"blob_id": "67a76f1f1dad4b7e73359f04ca8f599c8d32dc92",
"index": 2900,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef differences(a, b):\n \"\"\"\"\"\"\n c = a[a != b]\n d = b[a != b]\n nums = nonzero(a != b)[0]\n return concatenate((mat(nums), c, d)).T\n",
"step-3": "from numpy ... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
#------------------------------------------------------------------------------
# imsrg_pairing.py
#
# author: H. Hergert
# version: 1.5.0
# date: Dec 6, 2016
#
# tested with Python v2.7
#
# Solves the pairing model for four particles in a basis of four doubly
# degenerate states by me... | normal | {
"blob_id": "0eb86fc64b74c79cace838e2d71ed92533123229",
"index": 9910,
"step-1": "<mask token>\n\n\ndef ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B):\n dim = len(basph2B)\n Gamma_ph = np.zeros((dim, dim))\n for i1, (a, b) in enumerate(basph2B):\n for i2, (c, d) in enumerate(basph2B):\n ... | [
17,
18,
20,
21,
29
] |
import unittest
from dispatcher.task import *
from mock import *
class TestTask(unittest.TestCase):
def test_init(self):
task_attr = ['filename=C:\\Users\\kcheng\\PycharmProjects\\first_project\\dummy_task2.py',
'frequency=1D', 'time=09:45', 'description=invalid time']
task = T... | normal | {
"blob_id": "86c053b7d4c752182965755ad5b6ba6937ce6f86",
"index": 5984,
"step-1": "<mask token>\n\n\nclass TestTask(unittest.TestCase):\n <mask token>\n\n def test_init_bad_invalid_filename(self):\n task_attr = [\n 'filename=C:\\\\Users\\\\kcheng\\\\PycharmProjects\\\\first_project\\\\sadf... | [
2,
5,
6,
7,
10
] |
import os
import json
from google.appengine.ext import webapp
from generic import JsonRpcService
class ViewService(JsonRpcService):
def json_create(self):
return "Hello, World!"
| normal | {
"blob_id": "1b091d139635e90fb53b3fecc09bb879514c7b38",
"index": 7352,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass ViewService(JsonRpcService):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass ViewService(JsonRpcService):\n\n def json_create(self):\n return 'Hello, World!... | [
0,
1,
2,
3,
4
] |
# load the dependencies
from airflow import DAG
from datetime import date, timedelta, datetime
# default_args are the default arguments applied to the DAG and all inherited tasks
DAG_DEFAULT_ARGS = {
'owner': 'airflow',
'depends_on_past': False,
'retries': 1,
'retry_delay': timedelta(minutes=1)
}
with DAG('twitte... | normal | {
"blob_id": "436cc06778bf9ac9e04a897f4a4db90c595d943c",
"index": 5969,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith DAG('twitter_dag_v1', start_date=datetime(2018, 10, 1),\n schedule_interval='@daily', default_args=DAG_DEFAULT_ARGS, catchup=False\n ) as dag:\n None\n",
"step-3": "<mask ... | [
0,
1,
2,
3,
4
] |
print(1)
print(2)
print("Jenkins")
print("Jenkins2")
print("Jenkins3")
print("Jenkins44")
print("Jenkins55khlk")
print("3333333")
print("44444444")
print("jhjhj")
| normal | {
"blob_id": "77a82f99ab10e3d53e3f8466d43b67e8b87c1588",
"index": 2418,
"step-1": "<mask token>\n",
"step-2": "print(1)\nprint(2)\nprint('Jenkins')\nprint('Jenkins2')\nprint('Jenkins3')\nprint('Jenkins44')\nprint('Jenkins55khlk')\nprint('3333333')\nprint('44444444')\nprint('jhjhj')\n",
"step-3": "print(1)\npr... | [
0,
1,
2
] |
__author__ = "Yong Peng"
__version__ = "1.0"
import time
import re
import getpass
from netmiko import (
ConnectHandler,
NetmikoTimeoutException,
NetmikoAuthenticationException,
)
with open('./device_list.txt','r') as f:
device_list = [i.strip() for i in f.readlines() if len(i.strip()) != 0] # rea... | normal | {
"blob_id": "31a0c9a143a06ac86c8e8616fb273a0af844a352",
"index": 6895,
"step-1": "<mask token>\n\n\ndef send_show_command(device, commands):\n OutputPath = 'c:/script/output/' + str(device['host']) + '.txt'\n result = open(OutputPath, 'w')\n flag = True\n try:\n with ConnectHandler(**device) a... | [
1,
2,
3,
4,
5
] |
import csv
import os
events = {}
eventTypes = set()
eventIndices = {}
i = 0
with open('Civ VI Modding Companion - Events.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
if i < 4:
i += 1
continue
eventName = row[3]
eventType = "GameEvents" if... | normal | {
"blob_id": "5ce98ae241c0982eeb1027ffcff5b770f94ff1a3",
"index": 77,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('Civ VI Modding Companion - Events.csv', newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in reader:\n if i < 4:\n ... | [
0,
1,
2,
3,
4
] |
from openerp import models, fields, api, _
class priority_customer(models.Model):
_inherit = 'res.partner'
is_priority = fields.Boolean("Is Priority Partner:?")
registration_date = fields.Date("Registration Date:")
liability_card_number = fields.Char("Liability Card Number:")
| normal | {
"blob_id": "f2bb00d06023ef7b3ea3dc33f7ec00d1f48d46ae",
"index": 8477,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass priority_customer(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass priority_customer(models.Model)... | [
0,
1,
2,
3,
4
] |
"""
Copyright (c) 2017 Cyberhaven
Copyright (c) 2017 Dependable Systems Laboratory, EPFL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the right... | normal | {
"blob_id": "e5921edef3d3c56a73f2674f483ea4d1f3577629",
"index": 5186,
"step-1": "<mask token>\n\n\ndef _get_user_name():\n \"\"\"\n Get the current user.\n \"\"\"\n return pwd.getpwuid(os.getuid())[0]\n\n\ndef _user_belongs_to(group_name):\n \"\"\"\n Check that the current user belongs to the ... | [
17,
21,
24,
30,
34
] |
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Jack
@datetime: 2018/8/31 13:32
@E-mail: zhangxianlei117@gmail.com
"""
def isValid(s):
stack = []
for ss in s:
if ss in '([{':
stack.append(ss)
if ss in ')]}':
if len(stack) <= 0:
return Fal... | normal | {
"blob_id": "607f0aac0d6d2c05737f59803befcff37d559398",
"index": 5117,
"step-1": "#!usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n@author: Jack\n@datetime: 2018/8/31 13:32\n@E-mail: zhangxianlei117@gmail.com\n\"\"\"\n\n\ndef isValid(s):\n stack = []\n for ss in s:\n if ss in '([{':\n ... | [
0
] |
import json
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dangjianyun.settings")# project_name 项目名称
django.setup()
from dangjiansite.djfuncs import *
import os
import datetime
import requests
import time
import urllib3
import base64
import csv
import random
from bs4 import Beautifu... | normal | {
"blob_id": "55a26eb2625acb201677f5ff50fde809402c9b93",
"index": 2630,
"step-1": "<mask token>\n\n\nclass Runner:\n\n def __init__(self, appid='TJZHDJ01', username='', password=''):\n urllib3.disable_warnings()\n self.currentTime = datetime.datetime.now().strftime('%H:%M:%S')\n self.usern... | [
17,
19,
20,
21,
24
] |
import urlparse
def parse_url(url):
"""
Parse a url into a ParseResult() object then evolve that ParseResult()
instance into an EasyUrl() object, finally return the EasyUrl() instance.
"""
url = urlparse.urlparse(url)
#print url.__class__
return EasyUrl.EvolveParseResult(url)
class ... | normal | {
"blob_id": "0d322bdaf1bfed2b76172cc4dfb1b9af52bdc641",
"index": 8264,
"step-1": "import urlparse\n\n\n\n\ndef parse_url(url):\n \"\"\" \n Parse a url into a ParseResult() object then evolve that ParseResult()\n instance into an EasyUrl() object, finally return the EasyUrl() instance.\n \"\"\"\n u... | [
0
] |
"""
Copyright (C) 2019-2020 Zilliz. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | normal | {
"blob_id": "65a9f732fc8c7b9c63f6ef0d7b2172bb4138a895",
"index": 2761,
"step-1": "<mask token>\n\n\nclass TestScope:\n\n @pytest.mark.run(order=1)\n def test_create_scope(self, host, port):\n url = 'http://' + host + ':' + port + '/scope'\n r = requests.post(url=url)\n print(r.text)\n ... | [
10,
14,
17,
18,
20
] |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
from flask_ckeditor import CKEditorField
class BoldifyEncryptForm(FlaskForm):
boldMessage = StringField('Bolded Message: ', validators=[DataRequired()])
submit = SubmitField('Submit... | normal | {
"blob_id": "77b43d7d9cd6b912bcee471c564b47d7a7cdd552",
"index": 6227,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass BoldifyEncryptForm(FlaskForm):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass BoldifyEncryptForm(FlaskForm):\n boldMessage = StringField('Bolded... | [
0,
1,
2,
3
] |
__author__ = 'susperius'
"""
Abstract class used to implement own fuzzers
"""
class Fuzzer:
NAME = []
CONFIG_PARAMS = []
@classmethod
def from_list(cls, params):
raise NotImplementedError("ABSTRACT METHOD")
@property
def prng_state(self):
raise NotImplementedError("ABSTRACT M... | normal | {
"blob_id": "aa2a268143856d8f33b1aaf24f4e28ffd95cab01",
"index": 4658,
"step-1": "<mask token>\n\n\nclass Fuzzer:\n <mask token>\n <mask token>\n\n @classmethod\n def from_list(cls, params):\n raise NotImplementedError('ABSTRACT METHOD')\n\n @property\n def prng_state(self):\n rai... | [
7,
8,
9,
10,
11
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
class ZoomPanHandler:
"""
Matplotlib callback class to handle pan and zoom events.
"""
def __init__(self, axes, scale_factor=2, mouse_button=2):
"""
Default constructor for the ZoomPanHandler class.
Parameters... | normal | {
"blob_id": "6afcb8f17f7436f0ae9fa3a8c2a195245a9801f1",
"index": 6533,
"step-1": "<mask token>\n\n\nclass ZoomPanHandler:\n <mask token>\n\n def __init__(self, axes, scale_factor=2, mouse_button=2):\n \"\"\"\n Default constructor for the ZoomPanHandler class.\n\n Parameters\n ax... | [
13,
14,
15,
16,
19
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
con = lite.connect('./logs.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS log")
cur.execute('''CREATE TABLE log (msg_id text, u_id text, username text, first_name text, last_name text, msg text, ch_id text, d... | normal | {
"blob_id": "1c31649ac75214a6d26bcb6d6822579be91e5074",
"index": 2748,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith con:\n cur = con.cursor()\n cur.execute('DROP TABLE IF EXISTS log')\n cur.execute(\n 'CREATE TABLE log (msg_id text, u_id text, username text, first_name text, last_n... | [
0,
1,
2,
3,
4
] |
import re
s=input('enter the string:')
def end_num(s):
text = re.compile(r".*[0-9]$")
if text.match(s):
return 'Yes!Number is present at the end of string'
else:
return 'No!Number is not present at the end of string'
print(end_num(s))
| normal | {
"blob_id": "94334f91b1556c05dce0ed6f23c074bb8875f185",
"index": 2505,
"step-1": "<mask token>\n\n\ndef end_num(s):\n text = re.compile('.*[0-9]$')\n if text.match(s):\n return 'Yes!Number is present at the end of string'\n else:\n return 'No!Number is not present at the end of string'\n\n... | [
1,
2,
3,
4,
5
] |
from django.urls import path
from . import views as user_views
from produtos import views as prod_views
from django.contrib.auth import views as auth_views
app_name = 'user'
urlpatterns = [
path('detalhes/', user_views.painel, name="painel"),
path('produto/ajax/delete_prod/', prod_views.deleteProd, name="dele... | normal | {
"blob_id": "a7f2791e359b848a217beadc77fc983d971ef8b0",
"index": 8436,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'user'\nurlpatterns = [path('detalhes/', user_views.painel, name='painel'), path(\n 'produto/ajax/delete_prod/', prod_views.deleteProd, name='deleteProd'),\n path('produt... | [
0,
1,
2,
3
] |
from pulp import *
from collections import namedtuple
import networkx as nx
import itertools
from mcfpox.controller.lib import Flow, Hop
def get_host_from_ip(G, ip):
return next((i for i in G.nodes() if G.node[i].get('ip') == str(ip)), None)
# https://docs.python.org/2/library/itertools.html#recipes
def pairwis... | normal | {
"blob_id": "65bcb4a2fbc05ee19c8a94811d369562ec5e72ff",
"index": 9261,
"step-1": "from pulp import *\nfrom collections import namedtuple\nimport networkx as nx\nimport itertools\nfrom mcfpox.controller.lib import Flow, Hop\n\n\ndef get_host_from_ip(G, ip):\n return next((i for i in G.nodes() if G.node[i].get(... | [
0
] |
from django.db import models
class Article(models.Model):
created = models.DateTimeField(auto_now_add=True)
published = models.DateTimeField(null=True, blank=True)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
content = models.TextField()
| normal | {
"blob_id": "28233cb4a56ee805e66f34e6abd49137503d5f7b",
"index": 1405,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Article(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Article(models.Model):\... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
import rospy
import numpy as np
import time
import RPi.GPIO as GPIO
from ccn_raspicar_ros.msg import RaspiCarWheel
from ccn_raspicar_ros.msg import RaspiCarWheelControl
from ccn_raspicar_ros.srv import RaspiCarMotorControl
class MotorControl(object):
def __init__(self, control_pin=[16, 18,... | normal | {
"blob_id": "2985360c1e2d03c619ea2994c609fdf8c033bebd",
"index": 9177,
"step-1": "<mask token>\n\n\nclass MotorControl(object):\n <mask token>\n <mask token>\n\n def forward(self, speed=1.0, t=None):\n self.pwm_r1.ChangeDutyCycle(self.r_level * speed)\n self.pwm_r2.ChangeDutyCycle(0)\n ... | [
5,
11,
13,
15,
18
] |
import torch
import numpy as np
from torch.autograd import Variable
from util import helpers
from util.metrics import ECELoss, ece_score
import sklearn.metrics as skm
import os
import pandas as pd
import pickle
def eval(path_in, path_out, net, testloader, oodloader, use_cuda=True, save_dir=None):
f1 = open(path_... | normal | {
"blob_id": "edd2b7b453d7fa33e6cca3b5dbc895f034a9e22a",
"index": 2746,
"step-1": "<mask token>\n\n\ndef eval_cifar10(path_in, path_out, net, testloader, oodloader, use_cuda=\n True, save_dir=None):\n f1 = open(path_in, 'w')\n f2 = open(path_out, 'w')\n ece_criterion = ECELoss().cuda()\n net.eval()... | [
1,
2,
3,
4,
5
] |
from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
"""
With selenium we need web driver for our browser.
If you use google chrome, you can download chrome driver from here:
http://chromedriver.chromium.org/downloads
In linux (my OS) I extracted downloaded zip file and pla... | normal | {
"blob_id": "03b2b722832eb46f3f81618f70fd0475f1f08c94",
"index": 2997,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndriver.get('https://www.facebook.com')\n<mask token>\nprint(soup.prettify())\ndriver.close()\n",
"step-3": "<mask token>\ndriver = webdriver.Chrome('/Users/UserName/Downloads/chromedriv... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
serviceType = "server"
serviceDesc = _({"en": "Icecream Daemon",
"tr": "Icecream Servisi"})
from comar.service import *
@synchronized
def start():
startService(command="/opt/icecream/sbin/iceccd",
args="-d -m 5 > /dev/null",
pidfile="/var/... | normal | {
"blob_id": "e3603d90bd5aa5de40baa27b62acf6f71eff9f6c",
"index": 6827,
"step-1": "<mask token>\n\n\n@synchronized\ndef start():\n startService(command='/opt/icecream/sbin/iceccd', args=\n '-d -m 5 > /dev/null', pidfile='/var/run/iceccd.pid', donotify=True)\n\n\n<mask token>\n\n\ndef status():\n retu... | [
2,
3,
4,
5,
6
] |
from django.db import models
from helpers.models import BaseAbstractModel
from Auth.models import Profile
# from Jobs.models import UserJob
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Notification(BaseAbstractModel):
title = models.CharField(m... | normal | {
"blob_id": "1066f86d3a35e892ca2a7054dfc89fe79f1d32c8",
"index": 7496,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Notification(BaseAbstractModel):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Notification(... | [
0,
1,
2,
3,
4
] |
def ispalindrome(s):
if len(s) <= 1:
return True
elif s[0] != s[-1]:
return False
else:
return ispalindrome(s[1:-1])
| normal | {
"blob_id": "c20a414f7f96a96f6e458fc27e5d2c7ac7ab05cf",
"index": 8574,
"step-1": "<mask token>\n",
"step-2": "def ispalindrome(s):\n if len(s) <= 1:\n return True\n elif s[0] != s[-1]:\n return False\n else:\n return ispalindrome(s[1:-1])\n",
"step-3": null,
"step-4": null,
... | [
0,
1
] |
# Generated by Django 2.2.6 on 2019-11-13 13:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('interface', '0010_auto_20191104_2107'),
]
operations = [
migrations.AlterField(
model_name='submission',
name='revie... | normal | {
"blob_id": "3b42e218acf1c93fab3a0893efa8bf32a274eb23",
"index": 448,
"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 = [('interface', ... | [
0,
1,
2,
3,
4
] |
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from .models import Attendance, Holidays
#I think the update forms are not required here. They might be required in the profiles app. For this app, update attendance option can be available to the staff and faculty... | normal | {
"blob_id": "d48f02d8d5469b966f109e8652f25352bc9b3b80",
"index": 7252,
"step-1": "<mask token>\n\n\nclass AttendanceUpdateForm(ModelForm):\n\n\n class Meta:\n model = Attendance\n fields = 'enrollment_id', 'date', 'present', 'absent', 'outpass'\n",
"step-2": "<mask token>\n\n\nclass HolidaysUp... | [
1,
2,
3,
4,
5
] |
import unittest
import BasicVmLifecycleTestBase
class testVmIsAccessibleViaSsh(BasicVmLifecycleTestBase.
VmIsAccessibleViaSshTestBase):
vmName = 'cernvm'
timeout = 20 * 60
sshTimeout = 5 * 60
def suite():
return unittest.TestLoader().loadTestsFromTestCase(testVmIsAccessibleViaSsh
)
| normal | {
"blob_id": "79e4e37fc17462508abf259e3a7861bd76797280",
"index": 9182,
"step-1": "<mask token>\n\n\nclass testVmIsAccessibleViaSsh(BasicVmLifecycleTestBase.\n VmIsAccessibleViaSshTestBase):\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass testVmI... | [
1,
2,
3,
4
] |
#!/usr/bin/python3
"""
request api and write in JSON file
all tasks todo for every users
"""
import json
import requests
import sys
if __name__ == "__main__":
req = "https://jsonplaceholder.typicode.com/todos"
response = requests.get(req).json()
d = {}
req_user = "https://jsonplaceholder.typic... | normal | {
"blob_id": "53de53614b3c503a4232c00e8f2fd5a0f4cb6615",
"index": 1624,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n req = 'https://jsonplaceholder.typicode.com/todos'\n response = requests.get(req).json()\n d = {}\n req_user = 'https://jsonplaceholder.typicode.c... | [
0,
1,
2,
3
] |
"""
Create a list of words and with it, create a new dictionary
in which the key is the word and the value is the same word
reversed.
"""
word_list = ['Tree','Apple','Snake','flowers']
word_dict = {word:word[::-1] for word in word_list}
print(word_dict)
#Output: {'Tree': 'eerT', 'Apple': 'elppA', 'Snake': 'ekanS', 'fl... | normal | {
"blob_id": "5ac489a2d30155bb92767184ad546247817e28ea",
"index": 1478,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(word_dict)\n<mask token>\nprint(multiple_list)\n<mask token>\nprint(final_list)\n",
"step-3": "<mask token>\nword_list = ['Tree', 'Apple', 'Snake', 'flowers']\nword_dict = {word: ... | [
0,
1,
2,
3
] |
from point import Point
from velocity import Velocity
import arcade
import config
PADDLE_WIDTH = 15
PADDLE_HEIGHT = 30
class Paddle:
def __init__(self):
self.center = Point(390, 50)
self.velocity = Velocity(0, 5)
def draw(self):
self.drawing = arcade.draw_rectangle_filled(self.center... | normal | {
"blob_id": "cb3c1adb9d91aecee5b21774d61dfe9400a330fa",
"index": 619,
"step-1": "<mask token>\n\n\nclass Paddle:\n\n def __init__(self):\n self.center = Point(390, 50)\n self.velocity = Velocity(0, 5)\n <mask token>\n\n def move_up(self):\n if self.center.y < config.SCREEN_HEIGHT - ... | [
4,
5,
6,
7,
8
] |
from django.conf.urls import url
from price_App import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^api/price/(?P<pk>[0-9]+)$', views.product_price),
url(r'^api/price_history/(?P<pk>[0-9]+)$', views.product_history),]
urlpatterns = format_suffix... | normal | {
"blob_id": "9816a8265bcdb8c099f599efbe1cfe1a554e71f5",
"index": 8396,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('^api/price/(?P<pk>[0-9]+)$', views.product_price), url(\n '^api/price_history/(?P<pk>[0-9]+)$', views.product_history)]\nurlpatterns = format_suffix_patterns(urlpat... | [
0,
1,
2,
3
] |
import os
import math
import shutil
from evoplotter import utils
from evoplotter.dims import *
from evoplotter import printer
import numpy as np
CHECK_CORRECTNESS_OF_FILES = 1
STATUS_FILE_NAME = "results/status.txt"
OPT_SOLUTIONS_FILE_NAME = "opt_solutions.txt"
class TableGenerator:
"""Generates table from dat... | normal | {
"blob_id": "b3cb94a44f64091714650efb81c4cad27b211cef",
"index": 8804,
"step-1": "<mask token>\n\n\nclass TableGenerator:\n \"\"\"Generates table from data.\"\"\"\n\n def __init__(self, f_cell, dim_rows, dim_cols, headerRowNames, title='',\n color_scheme=None, table_postprocessor=None, vertical_bord... | [
22,
30,
37,
44,
48
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 17:08:06 2023
@author: Alice Wells
Plotting script for Figure 10 in Wells et al., 2023
Aerosol extinction coefficient vertical profile averaged longitudinally.
Averaged monthly CALIOP (centre) aerosol extinction coefficient vertical
profiles ... | normal | {
"blob_id": "e77c855ba87bc36ab09b0a3eca5c1b7123535794",
"index": 2802,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(85):\n so2_ash_masked[:, i, :] = so2_ash[:, i, :] * mask\n so2_only_masked[:, i, :] = so2_only[:, i, :] * mask\n<mask token>\nplt.rcParams.update(params)\n<mask token... | [
0,
1,
2,
3,
4
] |
#
# abc088 c
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.r... | normal | {
"blob_id": "8b97c1e14adfcb09806e2d37e2f5c4f0b356c009",
"index": 2742,
"step-1": "<mask token>\n\n\nclass TestClass(unittest.TestCase):\n <mask token>\n\n def test_入力例_1(self):\n input = '1 0 1\\n2 1 2\\n1 0 1'\n output = 'Yes'\n self.assertIO(input, output)\n <mask token>\n <mas... | [
2,
6,
8,
9,
10
] |
from flask_restful import Resource, reqparse
import sqlite3
from flask_jwt import jwt_required
from models.item_model import ItemModel
from flask_sqlalchemy import SQLAlchemy
from d import db
from models.store_model import StoreModel
class Modell(Resource):
def get(self, name):
item = Store... | normal | {
"blob_id": "5616ec135a2233e742ff3b2b1f378ec12298b935",
"index": 9578,
"step-1": "<mask token>\n\n\nclass Modell(Resource):\n <mask token>\n <mask token>\n\n def put(self, name):\n item = StoreModel.find_by_name(name)\n item.save_to_db()\n return item.json()\n <mask token>\n\n\nc... | [
4,
5,
6,
8,
9
] |
'''
Aaditya Upadhyay
oooo$$$$$$$$$$$
oo$$$$$$$$$$$$$$$$$$$$$$$o
oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o o$ $$ o$
o $ oo o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o $$ $$ $o$
oo $ $ "$ o$$$$$$$$$ $$$$$$$$$... | normal | {
"blob_id": "9cd1cb84c457db64019fa542efcf6500aa8d6d42",
"index": 9275,
"step-1": "<mask token>\n\n\ndef li():\n return list(map(int, stdin.readline().split()))\n\n\ndef mp():\n return map(int, stdin.readline().split())\n\n\n<mask token>\n\n\ndef pr(n):\n return stdout.write(str(n) + '\\n')\n\n\n<mask to... | [
4,
7,
8,
9,
10
] |
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import tensorflow as tf
import numpy as np
import argparse
import imutils
import pickle
import cv2
# USAGE
# python classify.py --model output/fashion.model --categorybin output/category_lb.pickle
# --colorbin output/color_lb.pickle... | normal | {
"blob_id": "8ff9961c1415c04899bbc15ba64811a1b3ade262",
"index": 3082,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nap.add_argument('-m', '--model', required=True, help=\n 'path to trained model model')\nap.add_argument('-l', '--categorybin', required=True, help=\n 'path to output category label ... | [
0,
1,
2,
3,
4
] |
def pantip(k, n, arr, path,len):
if len == 0:
if sum(path)==k:
path.reverse()
print(path)
return
path.append(arr[len-1])
pantip(k,n,arr,path,len-1)
path.pop()
#backtrack
pantip(k,n,arr,path,len-1)
inp = input('Enter Input (Money, Product) : ').... | normal | {
"blob_id": "6cdaf89d97be8f5ef37ab35f2916a36b4c75ddbe",
"index": 7513,
"step-1": "<mask token>\n",
"step-2": "def pantip(k, n, arr, path, len):\n if len == 0:\n if sum(path) == k:\n path.reverse()\n print(path)\n return\n path.append(arr[len - 1])\n pantip(k, n, arr... | [
0,
1,
2,
3,
4
] |
# NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,
# 支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。 | normal | {
"blob_id": "94348aed0585024c70062e9201fb41aae2122625",
"index": 9331,
"step-1": "# NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,\r\n# 支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
1
]
} | [
1
] |
'''
MDSANIMA Setup
'''
import sys
import pathlib
from setuptools import setup, find_packages
HERE = pathlib.Path(__file__).parent
CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 6)
# This check and everything above must remain compatible with Python 2.7.
if CURRENT_PYTHON < REQUIRED_PYTHON:
sys.stde... | normal | {
"blob_id": "2827a56c12c1e15a6fe26ce182aa07d76735d77f",
"index": 407,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif CURRENT_PYTHON < REQUIRED_PYTHON:\n sys.stderr.write(\n \"\"\"==========================\nUnsupported Python Version\n==========================\nThis version of MDSANIMA requ... | [
0,
1,
2,
3,
4
] |
from __future__ import print_function
from __future__ import division
import os
import sys
import time
import datetime
import os.path as osp
from collections import defaultdict
import numpy as np
import math
from functools import partial
from tqdm import tqdm
import glog as log
import torch
import torch.nn as nn
impo... | normal | {
"blob_id": "0ad529298f321d2f3a63cde8179a50cf2881ee00",
"index": 2162,
"step-1": "<mask token>\n\n\ndef main():\n global args\n torch.manual_seed(args.seed)\n if not args.use_avai_gpus:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices\n use_gpu = torch.cuda.is_available()\n if args.u... | [
1,
2,
3,
4,
5
] |
import tensorflow as tf
optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
_, l = sess.run([optimizer, loss], feed_dict={X:x, Y:y})
Session looks at all trainable variables that loss depends on and update them
tf.Variable(initializer=None, trainable=True, collections=None, validate_shape=True, caching... | normal | {
"blob_id": "edb206a8cd5bc48e831142d5632fd7eb90abd209",
"index": 72,
"step-1": "import tensorflow as tf\noptimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\n_, l = sess.run([optimizer, loss], feed_dict={X:x, Y:y})\n\nSession looks at all trainable variables that loss depends on and update them\n... | [
0
] |
from collections import deque
def solution(play_time, adv_time, logs):
'''
Strategy :
adv_start_time을 log start time 부터 < 995959 - adv time
sliding window
Step 1.
String time -> integer time
Step 2. pseudo code : Two pointer algorithm
max time = 0
return max time
'''
... | normal | {
"blob_id": "cb50a5352b0ad7b04dee9393c50da54fdf507376",
"index": 2018,
"step-1": "<mask token>\n\n\ndef str2int(strtime: str):\n hh, mm, ss = strtime.split(':')\n return 3600 * int(hh) + 60 * int(mm) + int(ss)\n\n\ndef int2str(inttime: int):\n hh = inttime // 3600\n mm = inttime % 3600 // 60\n ss ... | [
2,
3,
4,
5,
6
] |
import times_series_learning as tsl
import numpy as np
import time
import datetime as dt
import sortedcontainers
import pandas as pd
from collections import defaultdict
class ServerProfileLearning(object):
def __init__(self, data, parameters, distribution, distribution_period, level_threshold,
p... | normal | {
"blob_id": "53dd753356d8a8d60975c8f4cdaf20de66c2db46",
"index": 3486,
"step-1": "<mask token>\n\n\nclass ServerProfileLearning(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def process_distance(self, streaming_data):\n t0 = time.time()\n cluster_name = sel... | [
2,
3,
4,
5,
8
] |
from compas.geometry import Line
# This import is use to test __repr__.
from compas.geometry import Point # noqa: F401
def test_line():
p1 = [0, 0, 0]
p2 = [1, 0, 0]
line = Line(p1, p2)
assert line.start == p1
assert line.end == p2
def test_equality():
p1 = [0, 0, 0]
p2 = [1, 0, 0]
... | normal | {
"blob_id": "03629e62b11e66eeb0e111fee551c75c8463cbb8",
"index": 1059,
"step-1": "<mask token>\n\n\ndef test_line():\n p1 = [0, 0, 0]\n p2 = [1, 0, 0]\n line = Line(p1, p2)\n assert line.start == p1\n assert line.end == p2\n\n\n<mask token>\n\n\ndef test___getitem__():\n p1 = [0, 0, 0]\n p2 ... | [
2,
3,
4,
5,
6
] |
class Region:
"""
A region (represented by a list of long/lat coordinates).
"""
def __init__(self, coords, r_votes, d_votes, o_votes):
self.coords = coords
def lats(self):
"Return a list of the latitudes of all the coordinates in the region"
return [y for x,y in self.coords... | normal | {
"blob_id": "517436d61ac9993bee5ecfd932f272dbb8bec60b",
"index": 7608,
"step-1": "class Region:\n <mask token>\n\n def __init__(self, coords, r_votes, d_votes, o_votes):\n self.coords = coords\n\n def lats(self):\n \"\"\"Return a list of the latitudes of all the coordinates in the region\"... | [
6,
7,
8,
9,
10
] |
#!/bin/python3
def word_ladder(start_word, end_word, dictionary_file='words5.dict'):
'''
Returns a list satisfying the following properties:
1. the first element is `start_word`
2. the last element is `end_word`
3. elements at index i and i+1 are `_adjacent`
4. all elements are entries in the... | normal | {
"blob_id": "631323e79f4fb32611d7094af92cff8f923fa996",
"index": 303,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef _adjacent(word1, word2):\n \"\"\"\n Returns True if the input words differ by only a single character;\n returns False otherwise.\n\n >>> _adjacent('phone','phony')\n ... | [
0,
1,
2,
3,
4
] |
#### As an example below shell script can be used to execute this every 300s.
####!/bin/bash
####while true
####do
#### /usr/bin/sudo python3 /path/of/the/python/script.sh
####done
#!/usr/bin/python
import sys
import time
import paho.mqtt.client as mqtt
broker_url = "<IP_Address_of_MQTT_broker>"
b... | normal | {
"blob_id": "f311b803d8c0ee68bc43526f56e6b14f3a2836b8",
"index": 7309,
"step-1": "#### As an example below shell script can be used to execute this every 300s.\r\n####!/bin/bash\r\n####while true\r\n####do\r\n#### /usr/bin/sudo python3 /path/of/the/python/script.sh\r\n####done\r\n\r\n#!/usr/bin/python\r\n... | [
0
] |
#!/usr/bin/env python
from time import sleep
from org.mustadroid.python.interleech import processPage
import MySQLdb
from org.mustadroid.python.interleech.item import Item
import re
import time
if __name__ == "__main__":
db = MySQLdb.connect(host = "localhost",
user = "interleech",
pa... | normal | {
"blob_id": "598c634aac1df951f544127e102a1e2d61cac0b0",
"index": 4323,
"step-1": "#!/usr/bin/env python\nfrom time import sleep\nfrom org.mustadroid.python.interleech import processPage\nimport MySQLdb\nfrom org.mustadroid.python.interleech.item import Item\nimport re\nimport time\n\nif __name__ == \"__main__\":... | [
0
] |
#1.25.2019 - shashi
#Program that accepts an array of different elements
#And moves all the integer 0s to the end of it. String 0s like "0" or "0.0" remain untouched.
def shiftZeroesToEnd(myArray): #function starts here
zeroCounter = 0 #counter to keep track of how many 0s exist.
shiftedArray = [] #array to h... | normal | {
"blob_id": "4a9c42727a28e19cf1eebcf72784b85bbae695bf",
"index": 3429,
"step-1": "<mask token>\n",
"step-2": "def shiftZeroesToEnd(myArray):\n zeroCounter = 0\n shiftedArray = []\n for item in myArray:\n if (str(item) == '0' or str(item) == '0.0') and type(item) is not str:\n zeroCou... | [
0,
1,
2,
3
] |
# Generated by Django 3.1.1 on 2020-10-10 07:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('socialapp', '0004_mesage... | normal | {
"blob_id": "38751da57ad7c786e9fc0722faf065380e5f7e60",
"index": 4994,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.sw... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
import json, sys, getopt, re
# Usage: ./get_code.py -i <inputfile>
def main(argv):
inputfile = argv[0]
with open(inputfile) as json_data:
d=json.load(json_data)
json_data.close()
code_array = d["hits"]["hits"]
output_json = []
for element in code_array:
gistid = ele... | normal | {
"blob_id": "9594cda360847d2878aa2bd9c9c85fe50562b6ab",
"index": 5685,
"step-1": "#!/usr/bin/python\n\nimport json, sys, getopt, re\n\n# Usage: ./get_code.py -i <inputfile>\n\ndef main(argv): \n inputfile = argv[0]\n \n with open(inputfile) as json_data: \n d=json.load(json_data)\n json_data.close()\n ... | [
0
] |
"""Sophie Tan's special AI."""
from typing import Sequence, Tuple
from battleships import Player, ShotResult
from random import randint
class SophiesAI(Player):
"""Sophie Tan's Random Shot Magic."""
def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def d... | normal | {
"blob_id": "127bf47de554dd397d18c6a70616a2a4d93cae80",
"index": 3659,
"step-1": "<mask token>\n\n\nclass SophiesAI(Player):\n <mask token>\n\n def ship_locations(self) ->Sequence[Tuple[int, int, int, bool]]:\n return [(2, 0, 0, True)]\n <mask token>\n\n def bomb_feedback(self, x: int, y: int,... | [
4,
5,
6,
7,
8
] |
import sys
filepath = 'input.txt'
def intersection(list1, list2):
return set(list1).intersection(list2)
def computeSteps(x, y, step, steps):
# build dictionary with steps for each point
curr = 0
if (x,y) in steps:
curr = steps.get((x,y))
steps[(x,y)] = step + curr
... | normal | {
"blob_id": "e9e119dd69f9416e007e748d7f494741140efc8e",
"index": 8182,
"step-1": "<mask token>\n\n\ndef intersection(list1, list2):\n return set(list1).intersection(list2)\n\n\ndef computeSteps(x, y, step, steps):\n curr = 0\n if (x, y) in steps:\n curr = steps.get((x, y))\n steps[x, y] = step... | [
2,
4,
5,
6,
7
] |
#Takes - Contact Name(Must be saved in phone's contact list), Message, Time as input
# and sends message to the given contact at given time
# Accuracy Level ~ Seconds. (Also depends on your network speed)
from selenium import webdriver
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
f... | normal | {
"blob_id": "1811c0c5aca9d209638e2221cad2c30e80ee5199",
"index": 3116,
"step-1": "<mask token>\n\n\ndef send_msg():\n global nameofcontact, msg\n css_path = 'span[title=\"' + nameofcontact + '\"]'\n nameofcontact = driver.find_element_by_css_selector(css_path)\n nameofcontact.click()\n chatbox = d... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/env python
###############################################################################
#
#
# Project:
# Purpose:
#
#
# Author: Massimo Di Stefano , epiesasha@me.com
#
###############################################################################
# Copyright (c) 2009, Massimo Di Stefano <epiesasha@me.c... | normal | {
"blob_id": "59338170b44be037f749790a7942c2bcca1fc078",
"index": 2434,
"step-1": "#!/usr/bin/env python\n###############################################################################\n#\n#\n# Project:\n# Purpose:\n#\n#\n# Author: Massimo Di Stefano , epiesasha@me.com\n#\n#####################################... | [
0
] |
class State(object):
def __init__(self, stateName, stateLevel):
self.stateName = stateName;
self.stateLevel = stateLevel;
| normal | {
"blob_id": "73082ed2824ee65f7f4cbac47b9ebad19cec4196",
"index": 7226,
"step-1": "class State(object):\ndef __init__(self, stateName, stateLevel):\n self.stateName = stateName;\n self.stateLevel = stateLevel;\t\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
... | [
0
] |
"""
Creates a ResNeXt Model as defined in:
Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016).
Aggregated residual transformations for deep neural networks.
arXiv preprint arXiv:1611.05431.
import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py
"""
import torch
import torch.nn as nn
... | normal | {
"blob_id": "50ed1512b0e6ff8e01f5d4aa034406fa78850176",
"index": 2293,
"step-1": "<mask token>\n\n\nclass CifarResNeXt(nn.Module):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass ResNeXtBottleneck(nn.Module):\n <mask token>\n\n... | [
1,
8,
10,
11,
13
] |
# import tensorflow as tf
# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets('/tmp/data/',one_hot=True)
# def build_CNN_clasifier(x):
# x_image = tf.reshape (x, [-1,28,28,1])
#
# #layer1
# w_conv1 = tf.Variable(tf.truncated_normal(shape = [5,5,1,32],stddev= ... | normal | {
"blob_id": "a336434abc526357db0536955885cf076ee60f59",
"index": 7220,
"step-1": "<mask token>\n\n\ndef conv1d(x, w, p=0, s=1):\n w_rot = np.array(w[::-1])\n x_padded = np.array(x)\n if p > 0:\n zero_pad = np.zeros(shape=p)\n x_padded = np.concatenate([zero_pad, x_padded, zero_pad])\n r... | [
1,
2,
3,
4,
5
] |
vocales = "aeiou"
resultado = []
frase = input("Por favor ingrese la frase que desea verificar").lower()
print(frase)
for vocal in vocales:
conteo_vocales = frase.count(vocal)
mensaje = (f"En la frase hay {conteo_vocales} veces, la vocal{vocal}")
resultado.append(mensaje)
for elemento in resultado:
p... | normal | {
"blob_id": "f0a03f9a6dc78d01455913f7db3ab1948b19ea63",
"index": 6250,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(frase)\nfor vocal in vocales:\n conteo_vocales = frase.count(vocal)\n mensaje = f'En la frase hay {conteo_vocales} veces, la vocal{vocal}'\n resultado.append(mensaje)\nfor ... | [
0,
1,
2,
3
] |
import xarray as xr
def precip_stats_to_climatology(fili, start_year=1981, end_year=2015):
"""
Calculates average climatology for annual data - either Jan to Dec or accummulation period
"""
nyear = end_year - start_year + 1
ds = xr.open_dataset(fili)
year = ds['time'].dt.year
#dsMsk ... | normal | {
"blob_id": "eb403fbb307332c18ffdcdf52589c714f0719960",
"index": 3052,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef precip_stats_to_climatology(fili, start_year=1981, end_year=2015):\n \"\"\"\n Calculates average climatology for annual data - either Jan to Dec or accummulation period\n ... | [
0,
1,
2,
3,
4
] |
# 12.02.17
"""
nomencalura
a__b__c
a: parametro
t-temperatura
tm-temperatura minima
tM-teperatura massima
b: intervallo di tempo
a-anno
c: tabella fonte dati
g-giornaliero
"""
import db_02 as DB
def t_tm_tM__a__g(db, anno):
cmd = """
SELECT data, t, tmin, tmax
FROM Giornaliero
WHERE strft... | normal | {
"blob_id": "26b0a762b8eb30f0ef3c5a914f032c2a7d24f750",
"index": 5606,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef t_tm_tM__a__g(db, anno):\n cmd = (\n \"\\nSELECT data, t, tmin, tmax\\nFROM Giornaliero\\nWHERE strftime('%Y') = '{}'\\n \"\n .format(anno))\n dati = db.cur... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8-*-
import random
import re
from datetime import datetime, time
from phue import Bridge
import os
import glob
WORDS = []
def handle(text, mic, profile):
messages1 = ["Naturally Sir ","Of course Sir ","I'll get right at it"]
final = random.choice(messages1)
mic.say(final)
command = "ssh pi@... | normal | {
"blob_id": "668a8005f2f66190d588fb9289293d73a608f767",
"index": 926,
"step-1": "<mask token>\n\n\ndef handle(text, mic, profile):\n messages1 = ['Naturally Sir ', 'Of course Sir ', \"I'll get right at it\"]\n final = random.choice(messages1)\n mic.say(final)\n command = 'ssh pi@'\n ip = profile['... | [
1,
2,
3,
4,
5
] |
from functools import update_wrapper
from django.db import models
# Create your models here.
class Product(models.Model):
product_id=models.AutoField
product_name=models.CharField(max_length=50)
category=models.CharField(max_length=50,default="")
subcategory=models.CharField(max_length=50,default="")... | normal | {
"blob_id": "d123083358a4fd69f6f8de27fa177afac3bf80ce",
"index": 5680,
"step-1": "<mask token>\n\n\nclass Contact(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name\n\n\nclass Order(models.Model):\n order... | [
7,
9,
11,
12,
13
] |
from django.shortcuts import render,redirect
from . import download_function
from django.http import HttpResponse
# Create your views here.
def download(request):
if request.method == "GET":
session = request.GET['session']
title = request.GET['download_title']
download_quality = request.GET... | normal | {
"blob_id": "339506777f5471ec99b39c67c28df8ec3d06ce19",
"index": 3084,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef download(request):\n if request.method == 'GET':\n session = request.GET['session']\n title = request.GET['download_title']\n download_quality = request.GE... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 18:53:02 2020
@author: vinhe
I followed below tutorial to push newly created csv to google sheets:
https://medium.com/craftsmenltd/from-csv-to-google-sheet-using-python-ef097cb014f9
"""
import gspread
from oauth2client.service_account import ServiceAcc... | normal | {
"blob_id": "ac2edcd6ea71ebdc5b1df5fd4211632b5d8e2704",
"index": 3019,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('C:/users/vinhe/code/projects/golf/golf_stats.csv', 'r') as file_obj:\n content = file_obj.read()\n client.import_csv(spreadsheet.id, data=content)\n",
"step-3": "<mask ... | [
0,
1,
2,
3,
4
] |
import asyncio
import logging
import os.path
from serial_asyncio import open_serial_connection
from typing import NewType, cast
# Type annotations and converters
AsciiBytes = NewType('AsciiBytes', bytes)
def to_ascii(s: str) -> AsciiBytes:
if s[-1] != '\n':
s += '\n'
return cast(AsciiBytes, s.encode(... | normal | {
"blob_id": "50b630b762251f8646044b234ac4b82b8e4b645b",
"index": 8460,
"step-1": "<mask token>\n\n\nclass USBHandler:\n <mask token>\n\n def __init__(self):\n self.initialized = False\n self.run_task = None\n self.waiters = {}\n self.queues = {}\n self.logger = logging.ge... | [
3,
7,
8,
9,
10
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# sphinx_gallery_thumbnail_number = 3
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import NullFormatter # useful for `logit` scale
import matplotlib.ticker as ticker
import matplotlib as mpl
mpl.style.use('classic')
# Data for plotting
ch... | normal | {
"blob_id": "66904cbe3e57d9cc1ee385cd8a4c1ba3767626bd",
"index": 923,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmpl.style.use('classic')\n<mask token>\nax1.plot(chi2, color='r', linestyle='--', linewidth=2, markersize=5, label=\n '$\\\\chi^B_2$')\nax1.axis([0, 300, -0.05, 0.2])\nax1.set_xlabel('$... | [
0,
1,
2,
3,
4
] |
from base.SpellingDictionary import SpellingDictionary
from datastructure.trie import NeedMore
class WordFinder:
def __init__(self):
self.spellingDictionary = SpellingDictionary()
#self.dictionary.add(["toad", "to", "do", "dot"])
self.spellingDictionary.populateDictionary()
pr... | normal | {
"blob_id": "3be3edbecfbb602d4c4a853f006a3a6f4b992fd3",
"index": 1728,
"step-1": "from base.SpellingDictionary import SpellingDictionary\r\nfrom datastructure.trie import NeedMore\r\nclass WordFinder:\r\n def __init__(self):\r\n self.spellingDictionary = SpellingDictionary()\r\n #self.dictionary... | [
0
] |
from enum import Enum
# Genie
from genie.decorator import managedattribute
from genie.conf.base import Base, \
DeviceFeature, \
LinkFeature, \
Interface
import genie.conf.base.attributes
from genie.libs.conf.base.feature import consoli... | normal | {
"blob_id": "6d2581b83a2839dcbc644ca572b05b158d80b58d",
"index": 2479,
"step-1": "<mask token>\n\n\nclass Keychains(DeviceFeature):\n <mask token>\n\n\n class DeviceAttributes(genie.conf.base.attributes.DeviceSubAttributes):\n\n\n class KeyChainAttributes(KeyedSubAttributes):\n\n def __in... | [
4,
6,
7,
8,
9
] |
#!/usr/bin/env python3
"""Shows how to call C code from python"""
__appname__ = "myccalc.py"
__author__ = "Joseph Palmer <joseph.palmer18@imperial.ac.uk>"
__version__ = "0.0.1"
__license__ = "License for this code/"
__date__ = "Dec-2018"
## imports ##
import os
import ctypes
# Load the C library into python - needs t... | normal | {
"blob_id": "12ecfd2750f79fd19355665b6e57c2103a3cac3e",
"index": 4257,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nctypes.cdll.LoadLibrary(so_filepath)\n<mask token>\nprint('The sum of %.1f and %.1f is %.1f' % (x, y, a))\n<mask token>\nprint('Subtracting %.1f from %.1f is %.1f' % (x, y, b))\n",
"ste... | [
0,
1,
2,
3,
4
] |
import datetime
import logging
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional
from dagster import check
from dagster.core.utils import coerce_valid_log_level, make_new_run_id
if TYPE_CHECKING:
from dagster.core.events import DagsterEvent
DAGSTER_META_KEY = "dagster_meta"
class DagsterM... | normal | {
"blob_id": "f900e08c06ae736f5e32ac748e282700f9d0a969",
"index": 7922,
"step-1": "<mask token>\n\n\nclass DagsterMessageProps(NamedTuple('_DagsterMessageProps', [(\n 'orig_message', Optional[str]), ('log_message_id', Optional[str]), (\n 'log_timestamp', Optional[str]), ('dagster_event', Optional[Any])])):\... | [
16,
18,
21,
22,
25
] |
n, k = raw_input().split()
n = int(n)
k = int(k)
div = 0
for i in range(n):
new = int(raw_input())
if (new % k) == 0:
div += 1
print div | normal | {
"blob_id": "68e1e39f193537367d899c5fd01c1361ed93ef29",
"index": 7668,
"step-1": "n, k = raw_input().split()\nn = int(n)\nk = int(k)\n\ndiv = 0\n\nfor i in range(n):\n new = int(raw_input())\n if (new % k) == 0:\n div += 1\n\nprint div",
"step-2": null,
"step-3": null,
"step-4": null,
"step-... | [
0
] |
r"""
Definition
----------
Calculates the scattering from a **body-centered cubic lattice** with
paracrystalline distortion. Thermal vibrations are considered to be negligible,
and the size of the paracrystal is infinitely large. Paracrystalline distortion
is assumed to be isotropic and characterized by a Gaussian dis... | normal | {
"blob_id": "7ccaa15f025b2c1ba560d07c1a30b06c9ebf9ad1",
"index": 1927,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef random():\n \"\"\"Return a random parameter set for the model.\"\"\"\n radius = 10 ** np.random.uniform(1.3, 4)\n d_factor = 10 ** np.random.uniform(-2, -0.7)\n dnn_fr... | [
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.