code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
import cx_Oracle
import datetime
SDATE = '01.01.2014'
FDATE = '01.01.2020'
#p.PRESZAB,
#GDR_RATE.RFLUID,
#p.NRES
#join GDR_RATE on GDR_RATE.IDWELL = p.IDWELL and GDR_RATE.DTBGN = p.DTBGN and GDR_RATE.NRES = p.NRES)
pbu_query_raw = f"""
select
WELLNAME,
DTBGN,
DPDEVICE,
(TVDSS-(MD - DPDEVICE)*... | normal | {
"blob_id": "39f1595374147c71bc2d4c945a0f1149891f1883",
"index": 5300,
"step-1": "<mask token>\n\n\ndef get_data_from_database_cns(connection, query_string, delimiter=';'):\n with connection.cursor() as cur:\n cur.execute(query_string)\n [print(x[0], end=delimiter) for x in cur.description]\n ... | [
3,
4,
5,
6,
7
] |
"""
"""
#####################################################################
#This software was developed by the University of Tennessee as part of the
#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
#project funded by the US National Science Foundation.
#See the license text in license.txt
#copyr... | normal | {
"blob_id": "3cdb39e201983e672f6c22c25492a120be3d0d48",
"index": 9937,
"step-1": "\"\"\"\n\"\"\"\n#####################################################################\n#This software was developed by the University of Tennessee as part of the\n#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)... | [
0
] |
from os import listdir
import re
import numpy as np
from sklearn.metrics import f1_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import LeaveOneOut
import matplotlib.pyplot as plt
n_gram_range = (1, 1)
alpha_smoothing = 1e-1... | normal | {
"blob_id": "8bb67317ede277e03e8cbdefefeffa3d206ece65",
"index": 9434,
"step-1": "<mask token>\n\n\ndef parse_doc_line(line):\n parsed = re.search('\\\\d[\\\\d\\\\s]+\\\\d', line)\n return 'empty' if parsed is None else parsed[0]\n\n\ndef get_roc_point(clf, x_set, y_set, threshold):\n loo = LeaveOneOut(... | [
3,
4,
5,
6,
7
] |
import datetime
import json
import logging
import requests
from lib.crits.exceptions import CRITsOperationalError
from lib.crits.vocabulary.indicators import IndicatorThreatTypes as itt
from lib.crits.vocabulary.indicators import IndicatorAttackTypes as iat
log = logging.getLogger()
class CRITsAPI():
def __init... | normal | {
"blob_id": "a505cc0e382554d65447a3fe3a56fac43c1964f2",
"index": 8133,
"step-1": "<mask token>\n\n\nclass CRITsAPI:\n <mask token>\n\n def get_object(self, obj_id, obj_type):\n type_trans = self._type_translation(obj_type)\n get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)\n ... | [
6,
7,
8,
9,
11
] |
from django.shortcuts import render
from django.http import Http404
from thermometer.models import Therm
def index(request):
therms = Therm.objects.all()
return render(request, 'thermometer/index.html', {
'therms': therms,
})
def fetchsquare(request, id):
try:
therm = Therm.objects.get(id=id)
except Therm.D... | normal | {
"blob_id": "504d4afc4b3e708d43110a2d85676fb745f1aba8",
"index": 9874,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef fetchsquare(request, id):\n try:\n therm = Therm.objects.get(id=id)\n except Therm.DoesNotExist:\n raise Http404('This item does not exist')\n return render... | [
0,
1,
2,
3,
4
] |
from ..core import promise, rule
_context = {
'@vocab': 'https://schema.org/',
'fairsharing': 'https://fairsharing.org/',
'html': 'fairsharing:bsg-s001284',
}
@promise
def resolve_html(url):
from urllib.request import urlopen
return urlopen(url).read().decode()
@rule({
'@context': _context,
'@type': 'W... | normal | {
"blob_id": "3272296bca0d6343540597baebef8d882a1267c0",
"index": 3111,
"step-1": "<mask token>\n\n\n@rule({'@context': _context, '@type': 'WebSite', '@id': {}, 'url': {}})\ndef html_resolver(ld):\n return dict(ld, **{'html': str(resolve_html(ld['url']))})\n",
"step-2": "<mask token>\n\n\n@promise\ndef resol... | [
1,
2,
3,
4,
5
] |
def h1_wrap(func):
def func_wrapper(param):
return "<h1>"+func(param) + "</h1>"
return func_wrapper
@h1_wrap
def say_hi(name):
return "Hello, " + name.capitalize()
print(say_hi("Stephan"))
| normal | {
"blob_id": "9c9005acb40e4b89ca215345361e21f08f984847",
"index": 5735,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@h1_wrap\ndef say_hi(name):\n return 'Hello, ' + name.capitalize()\n\n\n<mask token>\n",
"step-3": "def h1_wrap(func):\n\n def func_wrapper(param):\n return '<h1>' + fu... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2017, 2018 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration for REANA-Workflow-Controller."""
from __future__ import absolu... | normal | {
"blob_id": "502e92d3e5d059d73016702ce0b2591a123810d3",
"index": 6892,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@pytest.fixture(scope='module')\ndef base_app(tmp_shared_volume_path):\n \"\"\"Flask application fixture.\"\"\"\n config_mapping = {'SERVER_NAME': 'localhost:5000', 'SECRET_KEY'... | [
0,
1,
2,
3
] |
import time
from wxpy import *
bot = Bot(cache_path='wxpy.pkl')
def get(i):
with open('晚安.txt', 'r', encoding='utf-8') as f:
line = f.readlines()[i]
return line
def send(i):
myfriend = bot.friends().search('微信好友昵称')[0]
myfriend.send(get(i))
i += 1
def main():
for i in range(3650):
... | normal | {
"blob_id": "a7d11f130e0d5d6c9b4ac7c5d3a804fb9f79b943",
"index": 2284,
"step-1": "<mask token>\n\n\ndef get(i):\n with open('晚安.txt', 'r', encoding='utf-8') as f:\n line = f.readlines()[i]\n return line\n\n\n<mask token>\n\n\ndef main():\n for i in range(3650):\n send(i)\n time.slee... | [
2,
4,
5,
6
] |
import torch
import numpy as np
# source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb
def kernel(X1, X2, l=1.0, sigma_f=1.0):
''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x d). X2: Arr... | normal | {
"blob_id": "82c3bde5746d04c126a93851844f775e7ce65f4b",
"index": 9442,
"step-1": "<mask token>\n\n\nclass CNP(torch.nn.Module):\n <mask token>\n <mask token>\n\n\nclass ANP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n sup... | [
7,
8,
9,
10,
13
] |
print(" whats your name boi ?")
name = input();
if name == "arrya":
print("u are a boi");
elif name == "jon":
print("basterd")
elif name == "ned":
print("you are dead man")
elif name == "rob":
print("the king in the north")
else:
print("carry on")
| normal | {
"blob_id": "483a5e95a7bfca2cc6b1e7e81740620468fb5623",
"index": 9646,
"step-1": "<mask token>\n",
"step-2": "print(' whats your name boi ?')\n<mask token>\nif name == 'arrya':\n print('u are a boi')\nelif name == 'jon':\n print('basterd')\nelif name == 'ned':\n print('you are dead man')\nelif name ==... | [
0,
1,
2,
3
] |
'''
Created on 17.05.2018
@author: markus
'''
import Ship
import Player
import Planet
import random
from FighterShip import FighterShip
turnCounter = 0
def cleanScreen():
for i in range(0,50):
print("")
def spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower
... | normal | {
"blob_id": "97611fef5faafe660c7640e4a5aec8456e52135c",
"index": 9960,
"step-1": "<mask token>\n\n\ndef spacePortMenu(player, planet):\n global turnCounter\n while True:\n cleanScreen()\n print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****')\n print('Enter 1 to jump to a ... | [
2,
5,
8,
9,
10
] |
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import precision_score, recall_score, f1_score
from scipy.optimize import fsolve
import numba
from numba import njit,jit
#
@jit(parallel = True)
def conventional_tes... | normal | {
"blob_id": "e564e0d05c3c0e60f356422722803df510d9dd0b",
"index": 281,
"step-1": "<mask token>\n\n\n@njit(parallel=True)\ndef parallel_test(subject_array, typeII_error, typeI_error, num):\n test_result = np.zeros(subject_array.shape, dtype=int)\n random_table = np.random.uniform(0, 1, (subject_array.shape[0... | [
10,
14,
15,
17,
20
] |
#Max Low
#9-25-17
#quiz2.py -- numbers , bigger smaller same, divisible by 3, product and correct person
numone = int(input('Enter a number: '))
numtwo = int(input('Enter a 2nd number: '))
if numone > numtwo:
print('The first number is bigger')
elif numtwo > numone:
print('The second number is bigger')
else:
... | normal | {
"blob_id": "a67612e8301728d1fb366d7c8909fa830f04bf45",
"index": 9739,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif numone > numtwo:\n print('The first number is bigger')\nelif numtwo > numone:\n print('The second number is bigger')\nelse:\n print('The numbers are the same')\nif numone % 3 ... | [
0,
1,
2,
3
] |
from botocore_eb.model import ServiceModel
from botocore_eb.exceptions import ParamValidationError
from botocore_eb.exceptions import DataNotFoundError
from botocore_eb.exceptions import OperationNotPageableError
from botocore_eb import xform_name
from botocore_eb.paginate import Paginator
import botocore_eb.validate
i... | normal | {
"blob_id": "829c833866198307d7d19c4a0cbe40299ee14eb9",
"index": 5288,
"step-1": "<mask token>\n\n\nclass ClientCreator(object):\n <mask token>\n\n def __init__(self, loader, endpoint_creator):\n self._loader = loader\n self._endpoint_creator = endpoint_creator\n\n def create_client(self, ... | [
6,
8,
15,
16,
18
] |
from django.contrib import admin
from .models import Wbs, Equipment_Type
class WbsAdmin(admin.ModelAdmin):
list_display = ('code','description','equipment_type')
list_filter = ('code','description','equipment_type')
readonly_fields = ('code','description')
class Equipment_TypeAdmin(admin.ModelAdmi... | normal | {
"blob_id": "292c66bd5b7f56ee8c27cabff01cd97ff36a79dc",
"index": 8885,
"step-1": "<mask token>\n\n\nclass WbsAdmin(admin.ModelAdmin):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Equipment_TypeAdmin(admin.ModelAdmin):\n list_display = 'type',\n list_filter = 'type',\n\n\n<mask token>\n"... | [
3,
4,
5,
6,
7
] |
# !/usr/bin/python
# sudo mn --custom _mininet_topo.py --topo mytopo,5
# sudo mn --custom _mininet_topo.py --topo mytopo,3 --test simpletest
# or just run this python file
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
fro... | normal | {
"blob_id": "8fd74287fbc653ea3ed4aa76a272486aa29185cf",
"index": 1032,
"step-1": "# !/usr/bin/python\n\n# sudo mn --custom _mininet_topo.py --topo mytopo,5\n# sudo mn --custom _mininet_topo.py --topo mytopo,3 --test simpletest\n# or just run this python file\n\nfrom mininet.topo import Topo\nfrom mininet.net imp... | [
0
] |
class BucketSort:
def __init__(self, a):
self.a = a
def result(self, bucketCount=10):
buckets = [[] for i in range(bucketCount + 1)]
maxElement = max(self.a)
minElement = min(self.a)
bucketRange = (maxElement - minElement + 1) / bucketCount
for i in range(len(se... | normal | {
"blob_id": "3b803850418638bf65528088044918e93ecabff6",
"index": 3085,
"step-1": "<mask token>\n",
"step-2": "class BucketSort:\n <mask token>\n <mask token>\n",
"step-3": "class BucketSort:\n <mask token>\n\n def result(self, bucketCount=10):\n buckets = [[] for i in range(bucketCount + 1... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
from pathlib import Path
from ruamel.yaml import YAML
from .screen import color2sgr
def _get(d, *paths):
""" Query into configuration dictionary, return None on any error
usag:
_get(d, 'k1.2.k3.k4', 2, 'name')
"""
if d is None:
return None
if paths is None:
return Non... | normal | {
"blob_id": "784159dfb2e85ca4634adf790e68129834155e4d",
"index": 2702,
"step-1": "<mask token>\n\n\nclass _Settings:\n <mask token>\n\n def _valueAt(self, *paths):\n u = _get(self.userConfig, *paths)\n d = _get(self.defaultConfig, *paths)\n return u, d\n\n def _loadConfigs(self):\n ... | [
5,
6,
8,
9,
10
] |
from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
app_name = "rooms"
router = DefaultRouter()
router.register("", views.RoomViewSet)
urlpatterns = router.urls
#
# urlpatterns = [
# # path("list/", views.ListRoomsView.as_view()),
# # path("list/", views.rooms_vie... | normal | {
"blob_id": "96708216c5ffa56a60475b295c21b18225e6eed9",
"index": 6056,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nrouter.register('', views.RoomViewSet)\n<mask token>\n",
"step-3": "<mask token>\napp_name = 'rooms'\nrouter = DefaultRouter()\nrouter.register('', views.RoomViewSet)\nurlpatterns = rou... | [
0,
1,
2,
3,
4
] |
import sklearn
import pandas as pd
import numpy as np
from sklearn import datasets, ensemble
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import statistics as st
import itertools
from sklearn.model_selection import cross_val_score
from sklearn.experimen... | normal | {
"blob_id": "0d862715524bd35347626e7708c7c8f8b370bb3a",
"index": 7769,
"step-1": "<mask token>\n\n\ndef expandgrid(*itrs):\n product = list(itertools.product(*itrs))\n return {'Var{}'.format(i + 1): [x[i] for x in product] for i in range(\n len(itrs))}\n\n\n<mask token>\n",
"step-2": "<mask token>... | [
1,
2,
3,
4,
5
] |
#Uses python3
import sys
def lcs2(a, b):
dp_result = [[0 for j in range(b+1)] for i in range(a+1)]
for x in range(1, a+1):
for y in range(1, b+1):
if a[x-1] == b[y-1] and b[y-1] == c[z-1]:
dp_result[x][y] = dp_result[x-1][y-1] + 1
else:
dp_re... | normal | {
"blob_id": "d20b336c6588c3cfc4393256b660d6e4ff56b84e",
"index": 1543,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef lcs2(a, b):\n dp_result = [[(0) for j in range(b + 1)] for i in range(a + 1)]\n for x in range(1, a + 1):\n for y in range(1, b + 1):\n if a[x - 1] == b[y ... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
#
# Dividend!
#
import os
import sys
import urllib2
import math
import numpy
from pylab import *
#
# Dividend adjusted! ... | normal | {
"blob_id": "6454790c98b254edeead4e68ef7f5760c9105a57",
"index": 433,
"step-1": "#!/usr/bin/python\n#\n# Dividend!\n#\n\nimport os\nimport sys\nimport urllib2\nimport math\nimport numpy\nfrom pylab import *\n\n# ... | [
0
] |
#예외처리 문법을 활용하여 정수가 아닌 숫자를 입력했을때 에러문구가나오도록 작성.(에러문구:정수가아닙니다)
try:
x = int(input('정수를 입력하세요: '))
print(x)
except:
print('정수가 아닙니다.')
| normal | {
"blob_id": "906265182a9776fec5bad41bfc9ee68b36873d1e",
"index": 573,
"step-1": "<mask token>\n",
"step-2": "try:\n x = int(input('정수를 입력하세요: '))\n print(x)\nexcept:\n print('정수가 아닙니다.')\n",
"step-3": "#예외처리 문법을 활용하여 정수가 아닌 숫자를 입력했을때 에러문구가나오도록 작성.(에러문구:정수가아닙니다)\n\ntry:\n x = int(input('정수를 입력하세요:... | [
0,
1,
2
] |
""" Utility functions and classes for SRP
Context : SRP
Module : Statsistics
Version : 1.0.0
Author : Stefano Covino
Date : 04/04/2013
E-mail : stefano.covino@brera.inaf.it
URL: : http://www.merate.mi.astro.it/utenti/covino
Usage : to be imported
Remarks : inputs are a 1D vectors to be cross-correlated. O... | normal | {
"blob_id": "c62ffcaa9095d772e51be086be349d200346bc22",
"index": 9662,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef XCorr_1D(data, refdata, xdata=None):\n if data.ndim == 1 and refdata.ndim == 1:\n ycorr = numpy.correlate(data, refdata, mode='full')\n xcorr = numpy.arange(ycorr... | [
0,
1,
2,
3
] |
import tkinter as tk
import Widgets as wg
import Logic as lgc
from tkinter.ttk import Separator
from tkinter.messagebox import showerror, showinfo
# Fonts that we can utilise
FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)}
class Handler: # Handles the window and... | normal | {
"blob_id": "9b8f3962172d4a867a3a070b6139bb302fd7e2f5",
"index": 9934,
"step-1": "<mask token>\n\n\nclass Window(tk.Tk):\n <mask token>\n <mask token>\n <mask token>\n\n def Get_Current_Player(self) ->str:\n return self.Handler.Get_Current_Player()\n <mask token>\n\n\nclass Pregame(tk.Frame... | [
39,
40,
41,
52,
59
] |
# %%
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA, TruncatedSVD
import matplotlib.patches as mpatches
import time
from sklearn.linear_model import LogisticRegression
from skle... | normal | {
"blob_id": "3923aed29006b4290437f2b0e11667c702da3241",
"index": 4605,
"step-1": "<mask token>\n\n\ndef plotTensorflowConfmat(confmat, classes):\n plt.imshow(confmat, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title('Confusion Matrix')\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n ... | [
1,
2,
3,
4,
5
] |
###
### Copyright 2009 The Chicago Independent Radio Project
### 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/LICENS... | normal | {
"blob_id": "d077f32061b87a4bfd6a0ac226730957a4000804",
"index": 5859,
"step-1": "<mask token>\n\n\nclass UserNotAllowedError(Exception):\n \"\"\"Raised when the user is recognized but forbidden from entering.\"\"\"\n\n\nclass _Credentials(object):\n email = None\n security_token_is_stale = False\n\n\n<... | [
10,
11,
12,
13,
16
] |
#!/usr/bin/env python
#_*_coding:utf-8_*_
#作者:Paul哥
from fabric.api import settings,run,cd,env,hosts
from fabric.colors import *
env.hosts=['192.168.75.130:22']
env.password='hello123'
env.user='root'
def test():
with cd('/home'):
print yellow(run('ls -l'))
test()
| normal | {
"blob_id": "6b45541c54f1a4ce94d6bd457701ecd1b90a4c4c",
"index": 1129,
"step-1": "#!/usr/bin/env python\n#_*_coding:utf-8_*_\n#作者:Paul哥\n\n\n\nfrom fabric.api import settings,run,cd,env,hosts\nfrom fabric.colors import *\n\nenv.hosts=['192.168.75.130:22']\nenv.password='hello123'\nenv.user='root'\ndef test():\n\... | [
0
] |
/home/khang/anaconda3/lib/python3.6/tempfile.py | normal | {
"blob_id": "399a22450d215638051a7d643fb6d391156779c5",
"index": 5855,
"step-1": "/home/khang/anaconda3/lib/python3.6/tempfile.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
# 玩家(攻击力)攻击敌人(血量)敌人受伤(减血)可能死亡(播放动画)
# 敌人攻击玩家 玩家受伤(减血 碎屏) 可能死亡(游戏结束)
# class Player:
# def __init__(self,name,hp,atk):
# self.name = name
# self.hp = hp
# self.atk = atk
#
# @property
# def hp(self):
# return self.__hp
# @hp.setter
# def hp(self,value):
# if 0... | normal | {
"blob_id": "3065c87f79433e9fbbd2ff45c2915dfd5b1fa7cc",
"index": 8427,
"step-1": "class Player:\n\n def __init__(self, hp=100, atk=100):\n self.hp = hp\n self.atk = atk\n <mask token>\n <mask token>\n\n\nclass Enemy:\n\n def __init__(self, hp=100, atk=99):\n self.hp = hp\n ... | [
6,
7,
8,
9,
11
] |
#------------------------------------------------------------------------
#
# @Author : EV2 CHEVALLIER
#
# @Date : 16.09.20
# @Location : École Navale / Chaire de Cyberdéfense des systèmes navals
# @Project : Projet de Fin d'Études
# @Subject : # Real time detection of cyber anomalies upon a NMEA network by using mach... | normal | {
"blob_id": "6726c8f1b3ef9a0df74c25c1921203af3aaacb12",
"index": 8758,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef training(dict):\n model = {}\n model['µ'] = {}\n model['sigma'] = {}\n for x in dict:\n model['µ'][x] = {}\n model['sigma'][x] = {}\n for y in dic... | [
0,
1,
2,
3,
4
] |
import webbrowser as wb
points = 0
import time as t
import pyautogui as pg
name = pg.prompt("What is your name? ").title()
pg.alert(name)
if name == "Caroline":
pg.alert ("Hi " + name)
points += 5
t.sleep(1)
wb.open ("https://www.textgiraffe.com/Caroline/Page2/")
elif name == "Bob":
... | normal | {
"blob_id": "16e10db90a0a0d8ee7ca5b0c7f86cc81432d87d1",
"index": 4391,
"step-1": "<mask token>\n",
"step-2": "<mask token>\npg.alert(name)\nif name == 'Caroline':\n pg.alert('Hi ' + name)\n points += 5\n t.sleep(1)\n wb.open('https://www.textgiraffe.com/Caroline/Page2/')\nelif name == 'Bob':\n p... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from flask import jsonify
from flask.views import MethodView
class Users(MethodView):
def get(self):
return jsonify(
{
'status': 'OK',
'users': [
{'name': 'Pepe', 'age': 35, 'ocupation': "Engineer"},
... | normal | {
"blob_id": "781ce153d5053078ee11cecc13d055a67999a651",
"index": 3800,
"step-1": "<mask token>\n\n\nclass Users(MethodView):\n <mask token>\n <mask token>\n\n def put(self):\n pass\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Users(MethodView):\n\n def get(self):\n return ... | [
2,
4,
5,
6,
7
] |
# I Have Created this file -Nabeel
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def aboutme(request):
return HttpResponse (" <a href='https://nb786.github.io/Ncoder/about.html' > Aboutme</a>")
def contact(request):
retur... | normal | {
"blob_id": "512d0a293b0cc3e6f7d84bb6958dc6693acde680",
"index": 1612,
"step-1": "<mask token>\n\n\ndef aboutme(request):\n return HttpResponse(\n \" <a href='https://nb786.github.io/Ncoder/about.html' > Aboutme</a>\")\n\n\n<mask token>\n\n\ndef analyze(request):\n djtext = request.POST.get('text', ... | [
2,
3,
4,
5,
6
] |
"""Usage:
sharedprint.py INPUT [--output=out.mrc]
sharedprint.py INPUT [--csv=greenglass.csv]
Process Koha MARC export for SCELC Shared Print.
The two uses above either 1) create a subset of the MARC input that's limited to
circulating items only or 2) performs a comparison between what's in the catalog
and w... | normal | {
"blob_id": "c6cce2edafd7683af766b932d90ca170359e648a",
"index": 679,
"step-1": "<mask token>\n\n\ndef main():\n total_count = 0\n valid_count = 0\n with open(options['INPUT'], 'rb') as fh:\n reader = MARCReader(fh, to_unicode=True, force_utf8=True)\n if not options['--csv']:\n ... | [
1,
2,
3,
5,
6
] |
import numpy as np
import cv2
import glob
from scipy.spatial.transform import Rotation
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Rectangle
import celluloid
from celluloid import Camera # couldn't save animation ... | normal | {
"blob_id": "50ae47c88bbc0f281ef75784377fb65192e257b0",
"index": 1206,
"step-1": "<mask token>\n\n\nclass DLT(object):\n <mask token>\n\n def getimg(self, idx):\n images = sorted(glob.glob(datadir + 'images_undistorted/*.jpg'))\n return cv2.imread(images[idx])\n <mask token>\n\n def est... | [
4,
6,
7,
8,
10
] |
"""autogenerated by genpy from arm_navigation_msgs/GetPlanningSceneRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import arm_navigation_msgs.msg
import geometry_msgs.msg
import std_msgs.msg
import genpy
import sensor_msgs.msg
class GetPlanni... | normal | {
"blob_id": "b8e18877af990c533c642d4937354198a4676419",
"index": 5194,
"step-1": "<mask token>\n\n\nclass GetPlanningSceneResponse(genpy.Message):\n _md5sum = '285525c9abe002fbafa99af84a14b4cb'\n _type = 'arm_navigation_msgs/GetPlanningSceneResponse'\n _has_header = False\n _full_text = \"\"\"\n\nPla... | [
10,
14,
18,
20,
21
] |
from typing import List
class NURBS:
def __init__(self, degree: int) -> None:
self._degree = degree
self._points = [] # type: List[complex]
self._weights = [] # type: List[float]
self._knots = [] # type: List[float]
def addPoint(self, p: complex) -> None:
self._poin... | normal | {
"blob_id": "40b3cacf55f6c5056c3541d70d8b2c0e2cc7d01b",
"index": 2564,
"step-1": "<mask token>\n\n\nclass NURBS:\n <mask token>\n <mask token>\n\n def addKnot(self, knot: float) ->None:\n self._knots.append(knot)\n\n def pointCount(self) ->int:\n return len(self._points)\n <mask toke... | [
6,
7,
8,
9,
11
] |
# -*- coding=utf-8 -*-
from mako.template import Template
from xblock.fragment import Fragment
from .lookup import TemplateLookup # xblock_ifmo.lookup
from .utils import deep_update
class FragmentMakoChain(Fragment):
"""
Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в
друга.
... | normal | {
"blob_id": "9d904225afd4f4d0cf338ae16f031f8ab41639ad",
"index": 234,
"step-1": "<mask token>\n\n\nclass FragmentMakoChain(Fragment):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, content=None, base=None, lookup_dirs=None):\n \"\"\"\n ... | [
7,
8,
9,
11,
12
] |
from typing import List
class Solution:
def grayCode(self, n: int) ->List[int]:
res = [0] * 2 ** n
exp = 0
l = r = 1
for i in range(1, 2 ** n):
res[i] += res[r - i] + 2 ** exp
if i == r:
exp += 1
l = r + 1
r =... | normal | {
"blob_id": "dc600763b12edda05820721098e7e5bc80f74c89",
"index": 4798,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution:\n\n def grayCode(self, n: int) ->List[int]:\n res = [0] * 2 ** n\n exp = 0\n ... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
class Problem1(object):
def sum_below(self, threshold):
current_number = 1
total = 0
while current_number < threshold:
if (current_number % 3 == 0) or (current_number % 5 == 0):
total += current_number
current_number += 1
... | normal | {
"blob_id": "918653cdeea8d91921f8b96779fcd3ebce491948",
"index": 1217,
"step-1": "#!/usr/bin/env python\nclass Problem1(object):\n def sum_below(self, threshold):\n current_number = 1\n total = 0\n while current_number < threshold:\n if (current_number % 3 == 0) or (current_num... | [
0
] |
from nose.tools import assert_equal
def rec_coin(target, coins):
'''
INPUT: Target change amount and list of coin values
OUTPUT: Minimum coins needed to make change
Note, this solution is not optimized.
'''
# Default to target value
min_coins = target
# Check to see if we have a sin... | normal | {
"blob_id": "f8c30f8ccd1b901fd750a2c9e14cab78e1d12a14",
"index": 4039,
"step-1": "<mask token>\n\n\ndef rec_coin(target, coins):\n \"\"\"\n INPUT: Target change amount and list of coin values\n OUTPUT: Minimum coins needed to make change\n\n Note, this solution is not optimized.\n \"\"\"\n min_... | [
4,
6,
7,
8,
9
] |
# -*- coding: utf-8 -*-
import numpy as np
def gauss_seidel(relax, est, stop):
"""
Método iterativo de Gauss-Seidel para o sistema linear do trabalho.
Onde relax é o fator de relaxação, est é o valor inicial, stop é o
critério de parada, n é a quantidade de linhas do sistema e k é o
nú... | normal | {
"blob_id": "51540a80c7b29dc0bbb6342ee45008108d54b6f2",
"index": 714,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor ini... | [
0,
1,
2,
3
] |
"""
You have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs.
Other areas are safe to sail in. There are other explorers trying to find the treasure.
So you must figure out a shortest route to one of the treasure islands.
Assume the map area is a two dimens... | normal | {
"blob_id": "e6851e86fa86ab2096f059218b2b8a2994642807",
"index": 3717,
"step-1": "<mask token>\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/env python3
import io
import json
import fire
from collections import OrderedDict
def main(input, output):
vocab = OrderedDict({'</s>': 0, '<unk>': 1})
for line in io.open(input, 'r', encoding='utf-8'):
word, count = line.strip().split()
vocab[word] = len(vocab)
with io.open(ou... | normal | {
"blob_id": "e3665141397d52877242463d548c059272d13536",
"index": 863,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main(input, output):\n vocab = OrderedDict({'</s>': 0, '<unk>': 1})\n for line in io.open(input, 'r', encoding='utf-8'):\n word, count = line.strip().split()\n ... | [
0,
1,
2,
3,
4
] |
from app_auth.recaptcha.services.recaptcha_service import validate_recaptcha
from django.shortcuts import render, redirect
from django.contrib import auth
from django.views import View
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Res... | normal | {
"blob_id": "b2eb2d006d6285947cc5392e290af50f25a9f566",
"index": 4724,
"step-1": "<mask token>\n\n\nclass Signup(Auth):\n <mask token>\n <mask token>\n\n\nclass UserViewSet(APIView):\n authentication_classes = [CustomBearerAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, ... | [
12,
14,
16,
18,
22
] |
import argparse, os, joblib, json, torch
import pandas as pd
from utils import regression, dataset, lstm
PREDICT_X_SKIP_COLS = ["date", "weight", "ts_id", "resp", "resp_1", "resp_2", "resp_3", "resp_4"]
X_COLS = ["resp_1", "resp_2", "resp_3", "resp_4"]
Y_OUTPUT_COLS = ["date", "ts_id"]
Y_COL = ["resp"]
METRICS_INFO = ... | normal | {
"blob_id": "4bdff51a4e277889f4d54d4ace7a0f5384e74f1e",
"index": 9017,
"step-1": "<mask token>\n\n\ndef get_prediction_data(data, model_path):\n x = data.drop(PREDICT_X_SKIP_COLS, axis=1)\n y = data[X_COLS]\n model = joblib.load(model_path)\n y_pred, metrics = regression.evaluate(model, x, y, METRICS... | [
6,
7,
8,
9,
10
] |
import datetime
import os
import uuid
from abc import ABC, abstractmethod
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.contenttypes.fields import (GenericForeignKey,
GenericRelation)
from django.contrib.conten... | normal | {
"blob_id": "9da995184641525cd763ecdb0bca4f28159ae740",
"index": 7617,
"step-1": "<mask token>\n\n\nclass ActExam(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def get_files_path(cls, package: 'DocumentsPackage'):\n tmp_path = package.get_s... | [
76,
93,
95,
98,
116
] |
#!/usr/bin/env python
"""
haxor
Unofficial Python wrapper for official Hacker News API
@author avinash sajjanshetty
@email hi@avi.im
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
import json
import sys
import requests
from .settings import supported_api_versions... | normal | {
"blob_id": "e14c7eb11c06d6de5c2f9f8adfb8b742fcb432e1",
"index": 8073,
"step-1": "<mask token>\n\n\nclass HackerNews(object):\n <mask token>\n\n def _get(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (string): URL to send GET.\n\n Returns:\n ... | [
11,
16,
17,
20,
29
] |
from __future__ import annotations
import asyncio
import signal
from functools import wraps
from typing import TYPE_CHECKING, Awaitable, Callable
import click
from .utils import import_obj
if TYPE_CHECKING:
from donald.manager import Donald
from .types import TV
def import_manager(path: str) -> Donald:
... | normal | {
"blob_id": "3da4896f368f067a339db5cc89201c93ba8166ce",
"index": 6220,
"step-1": "<mask token>\n\n\ndef process_await(fn: Callable[..., Awaitable[TV]]) ->Callable[..., TV]:\n\n @wraps(fn)\n @click.pass_context\n def wrapper(ctx, *args, **kwargs):\n loop = ctx.obj['loop']\n return loop.run_... | [
3,
4,
5,
6,
7
] |
#!/usr/bin/env python
'''
fix a time and then draw the instant geopotential (contour) from
/gws/nopw/j04/ncas_generic/users/renql/ERA5_subdaily/ERA5_NH_z_1989.nc,
spatial filtered relative vorticity (shaded) from
~/ERA5-1HR-lev/ERA5_VOR850_1hr_1995_DET/ERA5_VOR850_1hr_1995_DET_T63filt.nc
and identified feature poin... | normal | {
"blob_id": "09a468e11651eb60e0805c151bda270e0ebecca9",
"index": 4853,
"step-1": "<mask token>\n\n\ndef calc_frames(new_time):\n old_time = datetime(new_time.year - 1, 11, 30, 23)\n days = (new_time - old_time).days\n sec = (new_time - old_time).seconds\n hours = days * 24 + sec / 3600\n return in... | [
2,
3,
4,
5,
6
] |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | normal | {
"blob_id": "aa4226c377368d1ece4e556db9b7fdd0134472c9",
"index": 5450,
"step-1": "<mask token>\n\n\nclass _RestrictData:\n __slots__ = ()\n\n\n<mask token>\n\n\nclass RestrictBlend:\n __slots__ = 'context', 'data'\n\n def __enter__(self):\n self.data = _bpy.data\n self.context = _bpy.conte... | [
6,
9,
10,
11,
13
] |
N, M, T = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(M)]
now_time = 0
battery = N
ans = 'Yes'
for a, b in AB:
# カフェに付くまでにの消費
battery -= a-now_time
if battery <= 0:
ans = 'No'
break
# カフェでの充電
battery += b-a
battery = min(battery, N)
# 現... | normal | {
"blob_id": "15a7f6a63536ed24b6cf17395643476c689ec99b",
"index": 8499,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor a, b in AB:\n battery -= a - now_time\n if battery <= 0:\n ans = 'No'\n break\n battery += b - a\n battery = min(battery, N)\n now_time = b\nbattery -= T ... | [
0,
1,
2,
3
] |
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_rnn import TextRNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params
flags = tf.app.flags
FLAGS = flags.FLA... | normal | {
"blob_id": "aa1a7de92b971b6d10d09b2f8ca2c55516e538e4",
"index": 9904,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntf.flags.DEFINE_integer('embedding_dim', 100,\n 'Dimensionality of character embedding (default: 100)')\ntf.flags.DEFINE_float('dropout_keep_prob', 0.5,\n 'Dropout keep probability ... | [
0,
1,
2,
3,
4
] |
n=int(input("enter the number\n"))
sum=0
for i in range(1,n-1):
rem=n%i
if(rem==0):
sum=sum+i
if(sum==n):
print("the number is perfect")
else:
print("not prime")
| normal | {
"blob_id": "5721786b61cf8706b1d401a46d06f2d32153df8b",
"index": 765,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(1, n - 1):\n rem = n % i\n if rem == 0:\n sum = sum + i\nif sum == n:\n print('the number is perfect')\nelse:\n print('not prime')\n",
"step-3": "n = in... | [
0,
1,
2,
3
] |
##Problem 10 «The number of even elements of the sequence» (Medium)
##Statement
##Determine the number of even elements in the sequence ending with the number 0.
a = True
i = 0
while a is True:
x = int(input())
if x != 0:
if x%2 == 0:
i = i+1
else:
a =False
print(i)
| normal | {
"blob_id": "2eddd446dc59695b185be368b359bae78a868b90",
"index": 9918,
"step-1": "\n##Problem 10 «The number of even elements of the sequence» (Medium)\n##Statement\n##Determine the number of even elements in the sequence ending with the number 0. \n\n\na = True\ni = 0\nwhile a is True:\n x = int(input())\n ... | [
0
] |
import subprocess
import re
class Command:
InputSize = 1
OutputSize = 2
MultiThreadable = True
ShareResources = False
def __init__(self, bin, config, showerr=False):
self.travatar = subprocess.Popen([bin, "-config_file", config, "-trace_out", "STDOUT", "-in_format", "egret", "-buffer", "... | normal | {
"blob_id": "91cef72962332e7efcc86f1b19da4382bd72a466",
"index": 9278,
"step-1": "<mask token>\n\n\nclass Command:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Command:\n <mask token>\n <mask token>\n ... | [
1,
3,
4,
5,
6
] |
# uploadops.py
# CS304-Final Project
# Created by: Megan Shum, Maxine Hood, Mina Hattori
#!/usr/local/bin/python2.7
# This file handles all the SQL calls for the upload page.
import sys
import MySQLdb
import dbconn2
def uploadPost(conn, username, description, location, time_stamp, pathname):
'''Inserts post in Po... | normal | {
"blob_id": "f0deb8ccaf50ea0abb9e1632eaa4354a4f21dece",
"index": 5794,
"step-1": "# uploadops.py\n# CS304-Final Project\n# Created by: Megan Shum, Maxine Hood, Mina Hattori\n#!/usr/local/bin/python2.7\n# This file handles all the SQL calls for the upload page.\n\nimport sys\nimport MySQLdb\nimport dbconn2\n\ndef... | [
0
] |
from .entity import EventBase, event_class
from .. import LOG as _LOG
LOG = _LOG.getChild('entity.event')
@event_class()
class FunctionCallEvent(EventBase):
"""
function call
"""
deferred = True
def parse_jsondict(self, jsdict):
assert 'func_name' in jsdict['option'], 'func_name required'
... | normal | {
"blob_id": "9a665d126d7b48adbd876b48c3d8806eabea1108",
"index": 3716,
"step-1": "<mask token>\n\n\n@event_class()\nclass FunctionCallEvent(EventBase):\n <mask token>\n <mask token>\n <mask token>\n\n\n@event_class()\nclass PacketEvent(EventBase):\n \"\"\"\n L7 packet message\n \"\"\"\n defe... | [
11,
12,
13,
15,
17
] |
from quantopian.algorithm import order_optimal_portfolio
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage
from quantopian.pipeline.filters im... | normal | {
"blob_id": "c447d1fe38a4af43de39e05d46dacbe88249d427",
"index": 3654,
"step-1": "<mask token>\n\n\ndef compute_target_weights(context, data):\n \"\"\"\n Compute ordering weights.\n \"\"\"\n weights = {}\n if context.longs:\n long_weight = 0.5 / len(context.longs)\n if context.shorts:\n ... | [
1,
2,
4,
6,
7
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 12:16:15 2020
@author: zhangjuefei
"""
import sys
sys.path.append('../..')
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import OneHotEncoder
import matrixslow as ms
# 加载MNIST数据集,取一部分样本并归一化
X, y = fetch_openml('mnist_784', v... | normal | {
"blob_id": "63f155f7da958e9b6865007c701f7cf986b0cbac",
"index": 7800,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append('../..')\n<mask token>\nfor epoch in range(60):\n batch_count = 0\n for i in range(len(X)):\n feature = np.mat(X.values[i]).reshape(img_shape)\n label ... | [
0,
1,
2,
3,
4
] |
"""
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
查找J中的每个字符在 S 出现的次数的总和。
改进:
J有可能有重复的数。
测试数据:
https://leetcode.com/problems/jewels-and-stones/description/
"""
c... | normal | {
"blob_id": "8a04447f12a9cb6ba31a21d43629d887a0d1f411",
"index": 3097,
"step-1": "\"\"\"\nExample 1:\n\nInput: J = \"aA\", S = \"aAAbbbb\"\nOutput: 3\nExample 2:\n\nInput: J = \"z\", S = \"ZZ\"\nOutput: 0\nNote:\n\nS and J will consist of letters and have length at most 50.\nThe characters in J are distinct.\n\n... | [
0
] |
from lmfit import Parameters
import numpy as np
from cls.cls import *
from reading.ellipseOutput import readEllipseOutput
def readInputModel(txt, equivalentAxisFit, Settings):
psfwing_02pxscale_datatab = None
psfwing_logscale_datatab = None
componentslist = []
params = Parameters()
data = open(txt)
for lin... | normal | {
"blob_id": "219b22b6ad685fc316b1df02cc924a1cfec89f5b",
"index": 650,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef readInputModel(txt, equivalentAxisFit, Settings):\n psfwing_02pxscale_datatab = None\n psfwing_logscale_datatab = None\n componentslist = []\n params = Parameters()\n ... | [
0,
1,
2,
3
] |
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from mp_data_scrapper.items import MpDataScrapperItem
class MininovaSpider(CrawlSpider):
name = 'mp'
allowed_domains = ['india.gov.in']
... | normal | {
"blob_id": "94e9d67095dde4d3bf7ddb207ac17a4c250a2bfc",
"index": 1986,
"step-1": "from scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors import LinkExtractor\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom mp_data_scrapper.items import MpDataScrapperItem\... | [
0
] |
from Global import *
import ShuntingYard
from Thompson import *
def check_string(automaton, word):
inicial = automata['s'].closure
for i in word:
inicial = state_list_delta(inicial, i)
return automaton['f'] in inicial
def create_AFND(re):
deltas = []
initial_node = ShuntingYard.create_tree(ShuntingYard.to_rpn... | normal | {
"blob_id": "9cf0174a8bd2bccbd8e5d0be1f0b031a1a23c9df",
"index": 4691,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef check_string(automaton, word):\n inicial = automata['s'].closure\n for i in word:\n inicial = state_list_delta(inicial, i)\n return automaton['f'] in inicial\n\n\n... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
#Your code here
def loadData(fileDj):
data = []
fid = open(fileDj)
for line in fid:
line = line.strip()
m = [float(x) for x in line.split(' ')]
data.append(m)
return data
## K-means... | normal | {
"blob_id": "000dd63089fd0c6184fd032fe75ccc920beee7a8",
"index": 127,
"step-1": "<mask token>\n\n\ndef loadData(fileDj):\n data = []\n fid = open(fileDj)\n for line in fid:\n line = line.strip()\n m = [float(x) for x in line.split(' ')]\n data.append(m)\n return data\n\n\ndef get... | [
9,
10,
12,
13,
14
] |
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.dispatch import Signal
from djangochannelsrestframework.observer.base_observer import BaseObserver
class Observer(BaseObserver):
def __init__(self, func, signal: Signal = None, kwargs=None):
super().__init__(... | normal | {
"blob_id": "66e93295d2797ca9e08100a0a1f28619acb72aa4",
"index": 3397,
"step-1": "<mask token>\n\n\nclass Observer(BaseObserver):\n <mask token>\n\n def handle(self, signal, *args, **kwargs):\n message = self.serialize(signal, *args, **kwargs)\n channel_layer = get_channel_layer()\n fo... | [
2,
3,
4,
5,
6
] |
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseNotAllowed
from booli import booliwood
from models import add_bosta, get_all_bostas, Bosta
from django import forms
import time
class BostaForm(forms.Form):
maxPrice = forms.IntegerField()
livin... | normal | {
"blob_id": "53573a21364e9dfef9ed1164185ab441dbc29601",
"index": 123,
"step-1": "<mask token>\n\n\nclass BostaForm(forms.Form):\n maxPrice = forms.IntegerField()\n livingArea = forms.IntegerField()\n room = forms.IntegerField()\n\n\nclass BostaIdForm(forms.Form):\n bostaId = forms.IntegerField()\n\n\... | [
6,
8,
9,
10,
11
] |
from lredit import *
# customization of MainWindow
def configure(window):
#----------------------------------------------
# Generic edit config
# tab width and indent width
Mode.tab_width = 4
# make TAB character visible
Mode.show_tab = True
# make space character visible
Mode.sh... | normal | {
"blob_id": "d8e2613b45b3f4a24db0b07a01061c6057c9feed",
"index": 4973,
"step-1": "from lredit import *\n\n\n# customization of MainWindow\ndef configure(window):\n\n\n #----------------------------------------------\n # Generic edit config\n\n # tab width and indent width\n Mode.tab_width = 4\n\n ... | [
0
] |
def climb_ways(n, k): | normal | {
"blob_id": "05144338cc9c0c65010e0b8a3dd6fb50f6343214",
"index": 6641,
"step-1": "def climb_ways(n, k):",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
from collections import namedtuple
import argparse
import pdb
import traceback
import sys
import os
from qca_hex_analyzer import WmiCtrlAnalyzer, HtcCtrlAnalyzer, HttAnalyzer, AllAnalyzer
import hexfilter
description = \
"Tool used to analyze hexdumps produced by a qca wireless kernel " \
"driver (such as ath... | normal | {
"blob_id": "3b381668dbb9b4e5a2e323dc4d6b5e3951736882",
"index": 1804,
"step-1": "<mask token>\n\n\ndef auto_int(x):\n return int(x, 0)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef auto_int(x):\n return int(x, 0)\n\n\ndef load_options():\n global parsed_args\n base_parser = argparse.Argum... | [
1,
4,
5,
6,
7
] |
# Python 2.7 Doritobot Vision System
# EECS 498 Purple Team, 2014
# Written by Cody Hyman (hymanc@umich.edu)
# Written against OpenCV 3.0.0-alpha
import sys
import os
import cv2
import numpy as np
from uvcinterface import UVCInterface as uvc
from visionUtil import VisionUtil as vu
from collections import deque
from ... | normal | {
"blob_id": "324030a976af29dc93fdb637583bfaab93671cc2",
"index": 8515,
"step-1": "# Python 2.7 Doritobot Vision System\n# EECS 498 Purple Team, 2014\n# Written by Cody Hyman (hymanc@umich.edu)\n# Written against OpenCV 3.0.0-alpha\n\nimport sys\nimport os\n\nimport cv2\nimport numpy as np\n\nfrom uvcinterface im... | [
0
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import arabic_reshaper
from scrapy import Spider, Request
from bidi.algorithm import get_display
from websites.items import ArticleItem
from operator import add
from scrapy_splash import SplashRequest
class Blogsaljazeera2Spider(Spider):
na... | normal | {
"blob_id": "17058b323c0a0974dfa8f124ccd6cb5bf29dd849",
"index": 2065,
"step-1": "<mask token>\n\n\nclass Blogsaljazeera2Spider(Spider):\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(clean... | [
6,
7,
8,
9,
10
] |
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from .models import Flight, Passenger, Reservation
from .serializers import FlightSerializer, Passenger... | normal | {
"blob_id": "d437d77d5a57a6f2f4a2d530be05c3845dce93bc",
"index": 1459,
"step-1": "<mask token>\n\n\nclass Detailedreservation(RetrieveUpdateDestroyAPIView):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ListReservation(ListCreateAPIView):\n <mask token>\n <mask token>\n\n\ncl... | [
1,
7,
13,
14,
16
] |
from typing import List, Any, Callable, Iterable, TypeVar, Tuple
T = TypeVar('T')
def partition(pred: Callable[[T], bool], it: Iterable[T]) \
-> Tuple[List[T], List[T]]: ...
| normal | {
"blob_id": "8e443d136a4e9fcdd18a106192f9c097928b8c99",
"index": 7340,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef partition(pred: Callable[[T], bool], it: Iterable[T]) ->Tuple[List[T],\n List[T]]:\n ...\n",
"step-3": "<mask token>\nT = TypeVar('T')\n\n\ndef partition(pred: Callable[[T... | [
0,
1,
2,
3,
4
] |
# coding:utf-8
__author__ = 'yinzishao'
# dic ={}
class operation():
def GetResult(self):
pass
class operationAdd(operation):
def GetResult(self):
return self.numberA + self.numberB
class operationDev(operation):
def GetResult(self):
# if(self.numberB!=0):
# return sel... | normal | {
"blob_id": "7e33c6ada3d141ba8067dbf88c2e85a91802a067",
"index": 8446,
"step-1": "# coding:utf-8\n__author__ = 'yinzishao'\n# dic ={}\n\nclass operation():\n def GetResult(self):\n pass\n\nclass operationAdd(operation):\n def GetResult(self):\n return self.numberA + self.numberB\n\nclass oper... | [
0
] |
import sys
import utils
#import random
def findNearestPoint(points,no_used , src):
# If no nearest point found, return max.
dest = src
minDist = sys.float_info.max
for i in range(len(points)):
if no_used[i] and i!=src:
dist = utils.length(points[src], poi... | normal | {
"blob_id": "943db90aa7721ddad3d7f5103c4d398fbf4e143b",
"index": 2768,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef findNearestPoint(points, no_used, src):\n dest = src\n minDist = sys.float_info.max\n for i in range(len(points)):\n if no_used[i] and i != src:\n dist ... | [
0,
1,
2,
3,
4
] |
from django.urls import path
from .views import job_upload_view, job_view, job_applicants_view, posted_job_view, bussiness_list_view
app_name = 'jobs'
urlpatterns = [
path('', job_view, name='job-index'),
path('applicants/', job_applicants_view, name='job-applicants'),
path('posted/', posted_job_view, name='job-... | normal | {
"blob_id": "b88af16693eca10d0bd78fd706389f5468c9b99b",
"index": 144,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'jobs'\nurlpatterns = [path('', job_view, name='job-index'), path('applicants/',\n job_applicants_view, name='job-applicants'), path('posted/',\n posted_job_view, name='jo... | [
0,
1,
2,
3
] |
from .most_serializers import *
| normal | {
"blob_id": "a718949ed95b7d78f091b1e0f237eed151b102ae",
"index": 2160,
"step-1": "<mask token>\n",
"step-2": "from .most_serializers import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
import argparse
import tensorboardX as tb
import torch as th
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as D
import data
import mlp
import resnet
import utils
parser = argparse.ArgumentParser()
parser.add_argument('--bst', nargs='+', type=int, help='Batch Size for Training')
pa... | normal | {
"blob_id": "92bcfff733e5f305ad1276ceb39a72a8f0fcb214",
"index": 8038,
"step-1": "<mask token>\n\n\ndef log(model, i):\n mmm = []\n for loader in (train_loader, val_loader, test_loader):\n y, y_bar = infer(loader, model)\n a = th.sum(y == y_bar).item() / len(y)\n fnfn = utils.fn_mc(y, ... | [
1,
3,
4,
5,
6
] |
# Databricks notebook source
#import and create sparksession object
from pyspark.sql import SparkSession
spark=SparkSession.builder.appName('rc').getOrCreate()
# COMMAND ----------
#import the required functions and libraries
from pyspark.sql.functions import *
# COMMAND ----------
# Convert csv file to Spark Data... | normal | {
"blob_id": "d22ebe24605065452ae35c44367ee21a726ae7a1",
"index": 1892,
"step-1": "<mask token>\n\n\ndef loadDataFrame(fileName, fileSchema):\n return spark.read.format('csv').schema(fileSchema).option('header', 'true'\n ).option('mode', 'DROPMALFORMED').csv('/FileStore/tables/%s' % fileName\n )\... | [
2,
3,
4,
5,
6
] |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Define a function to compute color histogram features
# Pass the color_space flag as 3-letter all caps string
# like 'HSV' or 'LUV' etc.
# KEEP IN MIND IF YOU DECIDE TO USE THIS FUNCTION LATER
# IN YOUR PROJECT THAT IF ... | normal | {
"blob_id": "f178ae70ce54244624c2254d0d6256b83144db33",
"index": 5085,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef bin_spatial(img, color_space='RGB', size=(32, 32)):\n colour_dict = {'RGB': 'RGB', 'BGR': cv2.COLOR_BGR2RGB, 'HLS': cv2.\n COLOR_BGR2HLS, 'HSV': cv2.COLOR_BGR2HSV, 'LUV'... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
# encoding=utf-8
"""
@Author : Don
@Date : 9/16/2020 1:40 PM
@Desc :
"""
import os
import yaml
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yaml")
with open(config_path, "r", encoding="utf-8") as f:
conf = yaml.load(f.read(), Loader=yaml.FullLoader)... | normal | {
"blob_id": "8834548f6180fc864d73a71194125b22d230a393",
"index": 6882,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(config_path, 'r', encoding='utf-8') as f:\n conf = yaml.load(f.read(), Loader=yaml.FullLoader)\n",
"step-3": "<mask token>\nconfig_path = os.path.join(os.path.dirname(os.pa... | [
0,
1,
2,
3,
4
] |
from nose.tools import *
from packt_offer import *
from bs4 import BeautifulSoup
class TestPacktOffer:
def setUp(self):
self.proper_soup = BeautifulSoup(
""""
<div id="deal-of-the-day" class="cf">
<div class="dotd-main-book cf">
<div class="section-inner">
... | normal | {
"blob_id": "a29f89750ef3a55116959b217b8c9100b294c66c",
"index": 3766,
"step-1": "<mask token>\n\n\nclass TestPacktOffer:\n <mask token>\n <mask token>\n <mask token>\n\n def test_offer_title_extracter_proper(self):\n result = offer_title_extracter(self.proper_soup)\n assert_equals(resu... | [
3,
7,
8,
11,
12
] |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
import numpy as np
from datetime import datetime as dat
from sklearn.model_selection import train_test_split
from sklearn... | normal | {
"blob_id": "9b581df505765e895047584c5bb586faef95295f",
"index": 453,
"step-1": "<mask token>\n\n\ndef getStatsByYear(teamID, year, data):\n \"\"\" Returns the stats for a chosen team for a specific year. Choices are 2016 - 2019 \"\"\"\n teamStats = data[data['team_id'] == teamID]\n for index, row in te... | [
8,
9,
11,
12,
13
] |
from flask import Flask
from flask import request
from flask import session
from flask import jsonify
from flask import make_response
import mariadb
import datetime
import json
import scad_utils
testing: bool = True
if testing:
fake_datetime = datetime.datetime(2020, 8, 7, 15, 10)
app = Flask(__name__)
app.confi... | normal | {
"blob_id": "ff6b7e2097d78b013f8f5989adee47156579cb9e",
"index": 6226,
"step-1": "<mask token>\n\n\n@app.route('/login', methods=['POST'])\ndef login() ->dict:\n db_connection = db.get_connection()\n db_cursor = db_connection.cursor(named_tuple=True)\n data: dict = request.get_json()\n query: str = (... | [
10,
11,
12,
14,
16
] |
import xml.etree.ElementTree as ET
class Stage:
def __init__(self, costumes, sounds, variables, blocks, scripts, sprites):
self.costumes = costumes
self.sounds = sounds
self.variables = variables
self.blocks = blocks
self.scripts = scripts
self.sprites = sprites
... | normal | {
"blob_id": "575768c200ad81f878c132d68569c84f497091f2",
"index": 8137,
"step-1": "<mask token>\n\n\nclass Sprite:\n\n def __init__(self, name: str, index: str, xCoord: int, yCoord: int,\n heading: int, scale: float, volume: int, pan: int, rotation: int,\n draggable: bool, hidden: bool, costumes:... | [
2,
3,
4,
5
] |
import socket
comms_socket1 = socket.socket()
comms_socket2 = socket.socket()
comms_socket1.bind(("120.79.26.97",55000))
comms_socket2.bind(("120.79.26.97",55001))
comms_socket1.listen()
user1,address1 = comms_socket1.accept()
comms_socket2.listen()
user2,address2 = comms_socket2.accept()
while True:
send_date = ... | normal | {
"blob_id": "8981d53641d22430efb2dd43401fab562b8a95ed",
"index": 3262,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncomms_socket1.bind(('120.79.26.97', 55000))\ncomms_socket2.bind(('120.79.26.97', 55001))\ncomms_socket1.listen()\n<mask token>\ncomms_socket2.listen()\n<mask token>\nwhile True:\n send... | [
0,
1,
2,
3,
4
] |
import tensorflow as tf
import random
from tqdm import tqdm
import spacy
import ujson as json
from collections import Counter
import numpy as np
import os.path
nlp = spacy.blank("en")
def word_tokenize(sent):
doc = nlp(sent)
return [token.text for token in doc]
def convert_idx(text, tokens):
current = ... | normal | {
"blob_id": "5cd9d4fe9889c4d53b50d86fa78ae84d0c242536",
"index": 3693,
"step-1": "<mask token>\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print('Token {} cannot be found'.format(... | [
5,
6,
7,
8,
10
] |
import boring.dialog
import boring.form
FORMSTRING = '''
Project name@string
Width@int|Height@int
Background color@color
Fullscreen@check
'''
class NewProjectWindow(boring.dialog.DefaultDialog):
def __init__(self, master, _dict=None):
self._dict = _dict
self.output = None
boring.dialog.Def... | normal | {
"blob_id": "76420ec1b37d4b9b85f35764a7f8a0e1f19a15dd",
"index": 5745,
"step-1": "<mask token>\n\n\nclass NewProjectWindow(boring.dialog.DefaultDialog):\n\n def __init__(self, master, _dict=None):\n self._dict = _dict\n self.output = None\n boring.dialog.DefaultDialog.__init__(self, maste... | [
4,
5,
6,
7,
8
] |
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import ArticlePost
# Register your models here.
class SomeModelAdmin(SummernoteModelAdmin): # instead of ModelAdmin
summernote_fields = '__all__'
admin.site.register(ArticlePost, SummernoteModelAdmin) | normal | {
"blob_id": "a86b64ccd0dab4ab70ca9c2b7625fb34afec3794",
"index": 63,
"step-1": "<mask token>\n\n\nclass SomeModelAdmin(SummernoteModelAdmin):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass SomeModelAdmin(SummernoteModelAdmin):\n summernote_fields = '__all__'\n\n\n<mask token>\n",... | [
1,
2,
3,
4,
5
] |
from __future__ import with_statement # this is to work with python2.5
from pyps import workspace, module
def invoke_function(fu, ws):
return fu._get_code(activate = module.print_code_out_regions)
if __name__=="__main__":
workspace.delete('paws_out_regions')
with workspace('paws_out_regions.c',name='paws_ou... | normal | {
"blob_id": "299432b095f16c3cb4949319705800d06f534cf9",
"index": 1017,
"step-1": "from __future__ import with_statement # this is to work with python2.5\nfrom pyps import workspace, module\n\ndef invoke_function(fu, ws):\n return fu._get_code(activate = module.print_code_out_regions)\n\nif __name__==\"__m... | [
0
] |
"""Generic utilities module"""
from . import average
from . import extract_ocean_scalar
from . import git
from . import gmeantools
from . import merge
from . import netcdf
from . import xrtools
__all__ = [
"average",
"extract_ocean_scalar",
"git",
"gmeantools",
"merge",
"netcdf",
"xrtools"... | normal | {
"blob_id": "ab6450ee9038e0c58ca8becf6d2518d5e00b9c90",
"index": 9393,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n__all__ = ['average', 'extract_ocean_scalar', 'git', 'gmeantools', 'merge',\n 'netcdf', 'xrtools']\n",
"step-3": "<mask token>\nfrom . import average\nfrom . import extract_ocean_sca... | [
0,
1,
2,
3
] |
import logging
import search_yelp
import uuid
from apiclient import errors
from google.appengine.api import taskqueue
def insert_worker(mirror_service, food_type=None):
logging.info('zip1 food_type %s' % food_type)
try:
location = mirror_service.locations().get(id='latest').execute()
latlong... | normal | {
"blob_id": "22c0b8c8d598bb91bb2333343aad285bbcb4ee5b",
"index": 2669,
"step-1": "import logging\nimport search_yelp\nimport uuid\nfrom apiclient import errors\nfrom google.appengine.api import taskqueue\n\n\n\ndef insert_worker(mirror_service, food_type=None):\n\n logging.info('zip1 food_type %s' % food_type... | [
0
] |
import numpy as np
import numdifftools as nd
from scipy import stats
from scipy import optimize
from functools import partial
class TCRPowerCalculator:
def __init__(self, pcmodel):
self.pcmodel = pcmodel
self.predict_variance = self.pcmodel.predict_variance
self.predict_mean = self.pcmodel.predict_mean
self.... | normal | {
"blob_id": "d327151c9659078e12e4aca46631de33e7ca4dcf",
"index": 167,
"step-1": "<mask token>\n\n\nclass TCRPowerCalculator:\n <mask token>\n\n def predict_detection_probability_2step(self, tcr_frequency, num_reads,\n num_cells, detect_thresh=1):\n \"\"\"\n\t\t2-step detection probability mod... | [
3,
4,
5,
6,
7
] |
import csv
import json
from urllib import request
from urllib.error import HTTPError
from urllib.parse import urljoin, urlparse, quote_plus
from optparse import OptionParser
HEADER = ["id", "module", "channel", "type", "value", "datetime"]
def parse_options():
parser = OptionParser()
parser.add_option("-H", "... | normal | {
"blob_id": "b47f15a79f7a82304c2be6af00a5854ff0f6ad3e",
"index": 6987,
"step-1": "<mask token>\n\n\ndef write_csv(url, recursive=False, writer=None, token=''):\n response = fetch(url)\n if recursive:\n write_rows(writer, response)\n cursor = next_cursor(response)\n if cursor is not Non... | [
3,
6,
7,
8,
9
] |
#!ipython3
pi_f = 0.1415926
pi = []
for i in range(10):
pi.append(str(pi_f * i*16)[0])
print(pi)
def convertBase(digits, baseA, baseB, precisionB):
return output
#0.56 b8 to b10
#(1/base) ^ (i+1) *x
to10('56')
test = list(str(56))
test
27 9 3
33
0.3212 * 3
4*1.5
0.3212* 4/6
3*3**-1
2*3**-2
1*3**... | normal | {
"blob_id": "cffc64970cb82072e5fb949f62e9778942b2be96",
"index": 8269,
"step-1": "#!ipython3\n\npi_f = 0.1415926\npi = []\nfor i in range(10):\n pi.append(str(pi_f * i*16)[0])\n\nprint(pi)\n\n\ndef convertBase(digits, baseA, baseB, precisionB):\n return output\n\n#0.56 b8 to b10\n#(1/base) ^ (i+1) *x\n\n\n... | [
0
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# auther : xiaojinsong(61627515@qq.com)
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
data = ['ACME', 50, 91.1]
print(' '.join(parts))
def generate_str():
print(','.join(str(d) for d in data))
def sample():
yield 'Is'
yield 'Chicago'
yield 'Not'
yi... | normal | {
"blob_id": "4ce1e802831f09e503d18fd287cb35400986e3c8",
"index": 8095,
"step-1": "<mask token>\n\n\ndef generate_str():\n print(','.join(str(d) for d in data))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef generate_str():\n print(','.join(str(d) for d in data))\n\n\ndef sample():\n yield 'Is'... | [
1,
2,
4,
5,
6
] |
from functiona import *
total = totalMarks(85, 67, 56, 45, 78)
avg = average(total)
grade = findGrade(avg)
print(grade)
print(total)
print(avg)
| normal | {
"blob_id": "05f77472625e902b66c4a97a4c640835826bd494",
"index": 3635,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(grade)\nprint(total)\nprint(avg)\n",
"step-3": "<mask token>\ntotal = totalMarks(85, 67, 56, 45, 78)\navg = average(total)\ngrade = findGrade(avg)\nprint(grade)\nprint(total)\npri... | [
0,
1,
2,
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.