code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
# Copyright 2021-2022 Huawei Technologies Co., Ltd
#
# 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 agre... | normal | {
"blob_id": "8ae10aada79b0a687732e341d275eb3823ec0e4a",
"index": 9475,
"step-1": "<mask token>\n\n\nclass BucketDatasetGenerator:\n \"\"\"\n Provide data distribution of different gears for the bert network.\n\n Args:\n data_set (Dataset): The training dataset.\n batch_size (Int): The trai... | [
8,
11,
12,
13,
14
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('guac_auth', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='guacamoleconnectiongroup',
... | normal | {
"blob_id": "7f63097265b1058785e90441f85b7f0088946717",
"index": 7785,
"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 = [('guac_auth',... | [
0,
1,
2,
3,
4
] |
"""Exercise 9c"""
import time
import numpy as np
import matplotlib.pyplot as plt
from plot_results import plot_2d
from run_simulation import run_simulation
from simulation_parameters import SimulationParameters
def exercise_9c(world, timestep, reset):
"""Exercise 9c"""
n_joints = 10
Rhead = 0.44
... | normal | {
"blob_id": "a0284eba1a0e6c498f240068c586e7f8b79cd86c",
"index": 5782,
"step-1": "<mask token>\n\n\ndef main():\n n_joints = 10\n parameter_set = [SimulationParameters(simulation_duration=15, drive=4.0,\n amplitudes=None, phase_lag=None, turn=None, amplitude_gradient=[\n Rhead, Rtail], backwa... | [
2,
3,
4,
5,
6
] |
from amqpstorm import management
if __name__ == '__main__':
# If using a self-signed certificate, change verify=True to point at your CA bundle.
# You can disable certificate verification for testing by passing in verify=False.
API = management.ManagementApi('https://rmq.amqpstorm.io:15671', 'guest',
... | normal | {
"blob_id": "0279057b3962e4b9839a86fc2e2683ac1da11b1a",
"index": 8665,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n API = management.ManagementApi('https://rmq.amqpstorm.io:15671',\n 'guest', 'guest', verify=True)\n try:\n result = API.aliveness_test('/'... | [
0,
1,
2,
3
] |
# encoding:UTF-8
# 题目:斐波那契数列。
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print (fib(10))
| normal | {
"blob_id": "59376f6565cd72e20087609253a41c04c6327a27",
"index": 6324,
"step-1": "<mask token>\n",
"step-2": "def fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n - 1) + fib(n - 2)\n\n\n<mask token>\n",
"step-3": "def fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n ... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
# python >= 3.7
# supported xmanager version <5.1, 5.1, 5.2, 6
import os
import argparse
import configparser
import unicodedata
from win32api import GetComputerName, GetUserName
from win32security import LookupAccountName, ConvertSidToStringSid
from base64 import b64encode, b64decode
from Cryp... | normal | {
"blob_id": "5f2427c077d460d109f5a3e94b93f72c090f036d",
"index": 7181,
"step-1": "<mask token>\n\n\ndef decrypt_string(password_string, need_return=False):\n if not is_number(VERSION):\n raise ValueError('Invalid argument: --Version')\n ver = float(VERSION)\n Cipher = ARC4.new(getCipherKey())\n ... | [
5,
8,
9,
10,
11
] |
# coding: utf8
from __future__ import unicode_literals
from nltk.tag import stanford
from .SequenceTagger import SequenceTagger
class POSTagger(SequenceTagger):
"""
>>> tagger = POSTagger(model='resources/postagger.model')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدر... | normal | {
"blob_id": "1ac3630e6433a2d11c716b558640cab7c559f6ba",
"index": 4483,
"step-1": "<mask token>\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n <mask token>\n\n def __init__(self, model_filename, path_to_jar, *args, **kwargs):\n self._SEPARATOR = '/'\n super(stanford.StanfordPOSTag... | [
3,
5,
7,
8,
9
] |
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
import xmind
from xmind.core.markerref import MarkerId
xmind_name="数据结构"
w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")
s2=w.createSheet()
s2.setTitle("二叉树——递归套路")... | normal | {
"blob_id": "b713e38824db13f919484b071fb35afb29e26baa",
"index": 3803,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.insert(0, parentdir)\n<mask token>\ns2.setTitle('二叉树——递归套路')\n<mask token>\nr2.setTitle('二叉树——递归套路')\n<mask token>\nxmind.build(content, r2)\nxmind.save(w, os.path.dirname(os.pat... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-10-28 17:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('KYusers', '0017_caprofile_regs'),
]
operations = [
migrations.AddField(
... | normal | {
"blob_id": "12c3fe8a3ca1e660eeb90b16eca17eddd47e5de7",
"index": 7124,
"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 = [('KYusers', '... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
plugins_list = []
class PluginType(type):
def __init__(cls, name, bases, attrs):
super(PluginType, cls).__init__(name, bases, attrs)
# registrar el plugin en la lista
if not cls in plugins_list:
plugins_list.append(cls)
class PluginB... | normal | {
"blob_id": "b670655e3a8e88b97eed35e187b01d6524a16af3",
"index": 7709,
"step-1": "<mask token>\n\n\nclass PluginBase(object):\n \"\"\"\n Clase base para todos los plugins\n \"\"\"\n __metaclass__ = PluginType\n pass\n",
"step-2": "<mask token>\n\n\nclass PluginType(type):\n <mask token>\n\n\n... | [
3,
4,
5,
6,
7
] |
import config
import math
import pygame
import utils
class Rocket:
def __init__(self):
self.x = config.initialPosition['x']*config.game['scale'] + config.game['width']/2;
self.y = config.game['height'] - config.game['floorHeight'] - config.initialPosition['y']*config.game['scale'];
self.angle = config.initial... | normal | {
"blob_id": "7a1a9d2e773fb783d8522f1ea51e753d5d3782e9",
"index": 7517,
"step-1": "<mask token>\n\n\nclass Rocket:\n <mask token>\n <mask token>\n\n def update(self, x, y, angle, leftPower, rightPower):\n self.x = x * config.game['scale'] + config.game['width'] / 2\n self.y = config.game['h... | [
2,
3,
4,
5,
6
] |
class Node(object):
def __init__(self, d, n=None):
self.data = d
self.next_node = n
def get_data(self):
return self.data
def set_data(self, d):
self.data = d
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node=n
class... | normal | {
"blob_id": "de3e952ad43fe7e323e8f975a45bbd4eec7192db",
"index": 3481,
"step-1": "class Node(object):\n\n def __init__(self, d, n=None):\n self.data = d\n self.next_node = n\n\n def get_data(self):\n return self.data\n\n def set_data(self, d):\n self.data = d\n\n def get_n... | [
0
] |
# -*- coding: utf-8 -*-
"""
Description: This modules is used for testing. Testing is performed based on the list of commands given to perform in a website
Version : v1.5
History :
v1.0 - 08/01/2016 - Initial version
v1.1 - 08/05/2016 - Modified to accept List input.
... | normal | {
"blob_id": "9e77385933cf6e381f25bea9020f909d5dc6817d",
"index": 4744,
"step-1": "# -*- coding: utf-8 -*-\n\"\"\"\n Description: This modules is used for testing. Testing is performed based on the list of commands given to perform in a website\n Version : v1.5\n History :\n v1.0 - 0... | [
0
] |
import pytest
import mock
from awx.main.models import (
UnifiedJob,
WorkflowJob,
WorkflowJobNode,
Job
)
def test_unified_job_workflow_attributes():
with mock.patch('django.db.ConnectionRouter.db_for_write'):
job = UnifiedJob(id=1, name="job-1", launch_type="workflow")
job.unified_... | normal | {
"blob_id": "80a397b0974e41c4669f07638b5b38830b58cb37",
"index": 9051,
"step-1": "<mask token>\n\n\n@pytest.fixture\ndef unified_job(mocker):\n mocker.patch.object(UnifiedJob, 'can_cancel', return_value=True)\n j = UnifiedJob()\n j.status = 'pending'\n j.cancel_flag = None\n j.save = mocker.MagicM... | [
2,
4,
5,
6,
7
] |
import tensorflow as tf
from util.helper import focal_loss
from util.helper import conv_elu_bn
from util.helper import deconv_elu_bn
from util.helper import residual_block_elu
from util.helper import conv_elu
from util.helper import conv
from util.helper import reg_l1_loss
from util.helper import conv_bn
from util.hel... | normal | {
"blob_id": "e24a62f2a3ff0122922f472a7b37f1773dfe9c11",
"index": 7605,
"step-1": "<mask token>\n\n\nclass model_objectdetection_ppm_centernet_v1:\n <mask token>\n\n def _build_net(self):\n self.learning_rate_tensor = tf.compat.v1.placeholder(tf.float32,\n shape=[], name='learning_rate')\n... | [
4,
5,
6,
7,
8
] |
n = int(input())
m = int(input())
x = int(input())
y = int(input())
if m < n:
if m - x < x:
x = m - x
if n - y < y:
y = n - y
else:
if n - x < x:
x = n - x
if m - y < y:
y = m - y
if x < y:
print(x)
else:
print(y)
| normal | {
"blob_id": "002cced6d24a4790d29f195355c795d609f744a7",
"index": 9134,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif m < n:\n if m - x < x:\n x = m - x\n if n - y < y:\n y = n - y\nelse:\n if n - x < x:\n x = n - x\n if m - y < y:\n y = m - y\nif x < y:\n pr... | [
0,
1,
2
] |
# funkcja usuwająca zera z listy
def remove_zeros(given_list):
list_without_zero = []
for element in given_list:
if element != 0:
list_without_zero.append(element)
return list_without_zero
# funkcja sortująca listę
def sort_desc(given_list):
# sorted_list = []
# for ... | normal | {
"blob_id": "0779e516e35c41acf0529961e11541dfd1320749",
"index": 6501,
"step-1": "def remove_zeros(given_list):\n list_without_zero = []\n for element in given_list:\n if element != 0:\n list_without_zero.append(element)\n return list_without_zero\n\n\ndef sort_desc(given_list):\n r... | [
5,
7,
8,
10,
11
] |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import random
from utils.misc import *
from utils.adapt_helpers import *
from utils.rotation import rotate_batch, rotate_single_with_label
from utils.model import resnet18
from utils.train_helpers impor... | normal | {
"blob_id": "1f345a20343eb859cb37bf406623c0fc10722357",
"index": 4826,
"step-1": "<mask token>\n\n\ndef gn_helper(planes):\n return nn.GroupNorm(args.group_norm, planes)\n\n\n<mask token>\n",
"step-2": "<mask token>\nparser.add_argument('--dataroot', default='data/CIFAR-10-C/')\nparser.add_argument('--share... | [
1,
2,
3,
4,
5
] |
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
h = len(matrix)
w = len(matrix[0])
for curRow in range(h) :
val = matrix[curRow][0]
i = 0
while i < h-curRow and i < w :
# print(curRow+i,i)
if mat... | normal | {
"blob_id": "774f5d01cd274755626989c2b58bde68df349d8e",
"index": 5845,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def isToeplitzMatrix(self, matrix: List[List[int]]) ->bool:\n h = len(matrix)\n w = len(matrix[0])\n for c... | [
0,
1,
2,
3
] |
import matplotlib.pyplot as plt
import numpy as np
# 描画用サンプルデータ
#x= np.array([0,1,2,3,4])
y = np.array([2, 2, 3, 4, 5])
print(y)
#print(range(y))
plt.figure(figsize=(10,1))
plt.bar(range(len(y)), y)
plt.savefig('test.png')
plt.clf() | normal | {
"blob_id": "2f714ed54a19ec26d7ecb1979e79366721b3d0fe",
"index": 6682,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(y)\nplt.figure(figsize=(10, 1))\nplt.bar(range(len(y)), y)\nplt.savefig('test.png')\nplt.clf()\n",
"step-3": "<mask token>\ny = np.array([2, 2, 3, 4, 5])\nprint(y)\nplt.figure(fig... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
"""
Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian
Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent
for use on A3 of Reinforcement learning course University of Alberta Fall 2017
"""
"""
/*
* Copyright (c) HAOTIAN ZHU ,COMPUT301,... | normal | {
"blob_id": "4e02edcf8a512060fa92ede11f33993978584147",
"index": 1997,
"step-1": "\n\n\n\n#!/usr/bin/env python\n\n\"\"\"\n Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian\n Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent\n\t\t for use on A3 of Reinforcemen... | [
0
] |
# Generated by Django 2.0.3 on 2018-07-05 04:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('application_manager', '0015_auto_20180705_0415'),
]
operations = [
migrations.RemoveField(
model_name='application',
name='u... | normal | {
"blob_id": "7bf81954bef81004b6c9838ed00c624d24fcf0c6",
"index": 3839,
"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 = [('application... | [
0,
1,
2,
3,
4
] |
from django.contrib import admin
# from .models import Usuario
# from .models import Lote
# from .models import Fornecedor
# from .models import Cliente
# from .models import Medicamento
# from .models import Medicamento_Entrada
# from .models import Medicamento_Saida
# Register your models here.
#
# class UsuarioAdmin... | normal | {
"blob_id": "63a2258bf0ed779254b68a683e3d30e9fb356b1f",
"index": 139,
"step-1": "<mask token>\n",
"step-2": "from django.contrib import admin\n",
"step-3": "from django.contrib import admin\n# from .models import Usuario\n# from .models import Lote\n# from .models import Fornecedor\n# from .models import Cli... | [
0,
1,
2
] |
import numpy as np
from .metrics import r2_score
class LinearRegression:
def __init__(self):
self.coef_ = None # 系数
self.interception_ = None # 截距
self._theta = None
def fit_normal(self, X_train, y_train):
assert X_train.shape[0] == y_train.shape[0], ""
#!!!impor... | normal | {
"blob_id": "e47e614c88c78fb6e8ff4098ea2b89d21bfa9684",
"index": 6935,
"step-1": "<mask token>\n\n\nclass LinearRegression:\n\n def __init__(self):\n self.coef_ = None\n self.interception_ = None\n self._theta = None\n <mask token>\n\n def fit_gd(self, X_train, y_train, eta=0.01, n_... | [
5,
7,
8,
9,
10
] |
#!/usr/bin/env python
import re
class Solution:
def __new__(self, p):
nr_counts, nr_consonants, replaced = self.count_vowels_consonants(self, p)
inversed = ''.join(c.lower() if c.isupper() else c.upper() for c in p)
replaced_by_ = p.replace(' ' ,'-')
combined_queries = str(nr_counts) + ' ' + str(nr_conso... | normal | {
"blob_id": "ec9de8d54113806ab327f05e077edefa74258adb",
"index": 2662,
"step-1": "<mask token>\n\n\nclass Solution:\n\n def __new__(self, p):\n nr_counts, nr_consonants, replaced = self.count_vowels_consonants(self,\n p)\n inversed = ''.join(c.lower() if c.isupper() else c.upper() for... | [
3,
4,
5,
6,
7
] |
# -*- coding: utf-8 -*-
from odoo import fields, models
class LunchWizard(models.TransientModel):
_name = "lunch.wizard"
_description = "LunchWizard"
lun_type = fields.Char(string="Set New Lunch Type")
lunch_id = fields.Many2one('lunch.lunch', string="Lunch Id")
def action_process_lunch(self):... | normal | {
"blob_id": "85e5bf57f7eba2cbee0fbb8a4d37b5180208f9b7",
"index": 3830,
"step-1": "<mask token>\n\n\nclass LunchWizard(models.TransientModel):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass LunchWizard(models.TransientModel):\n ... | [
1,
2,
3,
4,
5
] |
import cv2
import numpy as np
import show_imgs as si
IMG_PATH = "../sample_imgs"
def blur():
image = cv2.imread(IMG_PATH + "/jjang.jpg")
kernel_sizes = [(1, 1), (3, 3), (5, 5), (7, 7), (7, 1), (1, 7)]
filter_imgs = {}
blur_imgs = {}
for ksize in kernel_sizes:
title = f"ksize: {ksize}"
... | normal | {
"blob_id": "8e5d05d925d47a85ad7c211f26af7951be048d32",
"index": 9351,
"step-1": "<mask token>\n\n\ndef blur():\n image = cv2.imread(IMG_PATH + '/jjang.jpg')\n kernel_sizes = [(1, 1), (3, 3), (5, 5), (7, 7), (7, 1), (1, 7)]\n filter_imgs = {}\n blur_imgs = {}\n for ksize in kernel_sizes:\n ... | [
2,
4,
5,
6,
7
] |
from django.http import HttpResponse
from rest_framework.decorators import api_view
@api_view(['GET'])
def get_status(request):
if request.method == 'GET':
return HttpResponse(content='Service is OK!')
| normal | {
"blob_id": "f021940c16b7ed7fdf1088f2137d3ef724719c80",
"index": 1726,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@api_view(['GET'])\ndef get_status(request):\n if request.method == 'GET':\n return HttpResponse(content='Service is OK!')\n",
"step-3": "from django.http import HttpRespo... | [
0,
1,
2
] |
import math
import numpy as np
# import tkinter
import tensorflow as tf
from matplotlib import axis
import os
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
class MD(BaseEstimator, TransformerMixin):
def __init__(self, data,... | normal | {
"blob_id": "a9947884e805cc8fcb6bff010a5f6e0ff0bb01fe",
"index": 8393,
"step-1": "<mask token>\n\n\nclass MD(BaseEstimator, TransformerMixin):\n <mask token>\n\n def _init_graph(self):\n \"\"\"\n Init a tensorflow Graph containing: input data, variables, model, loss, optimizer\n \"\"\"... | [
4,
8,
9,
11,
13
] |
import openerp
from openerp import pooler
from openerp.report import report_sxw
import xlwt
from openerp.addons.report_xls.report_xls import report_xls
from openerp.tools.translate import _
class openacademy_course_xls_parser(report_sxw.rml_parse):
def __init__(self, cursor, uid, name, context):
super(openacademy_c... | normal | {
"blob_id": "5c415d5bf9d6952863a662d300cb1f706ef02a8f",
"index": 1048,
"step-1": "<mask token>\n\n\nclass openacademy_course_xls_parser(report_sxw.rml_parse):\n\n def __init__(self, cursor, uid, name, context):\n super(openacademy_course_xls_parser, self).__init__(cursor, uid,\n name, contex... | [
5,
6,
7,
8,
9
] |
#!/usr/bin/env python
import numpy as np
import rospy
import tf
from geometry_msgs.msg import PoseStamped, Twist, TwistStamped, Point
from nav_msgs.msg import Odometry
from visualization_msgs.msg import Marker
from bebop_nmpc_solver import BebopNmpcFormulationParam, bebop_nmpc_casadi_solver
# The frame by default is... | normal | {
"blob_id": "76d0dd2d6b2d580900283f2623f05dd02a70fcd8",
"index": 6825,
"step-1": "<mask token>\n\n\nclass BebopNmpcControl:\n <mask token>\n\n def set_bebop_odom(self, odom_msg):\n if self.received_first_odom_ is False:\n self.received_first_odom_ = True\n rospy.loginfo('First ... | [
10,
12,
13,
15,
18
] |
# coding=utf-8
"""SCALE UI: feature tests."""
import pytest
import xpaths
from function import (
wait_on_element,
is_element_present,
wait_on_element_disappear
)
from pytest_bdd import (
given,
scenario,
then,
when,
)
@pytest.mark.dependency(name='Set_Group')
@scenario('features/NAS-T1250... | normal | {
"blob_id": "f4aaf0449bff68814090552ea4f6ccac85dacf1b",
"index": 5617,
"step-1": "<mask token>\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip,\n root_password):\n \"\"\"the browser is open, navigate to the... | [
3,
4,
5,
7,
8
] |
from flask import url_for
from bs4 import BeautifulSoup
from unittest.mock import ANY
import app
from app.notify_client.models import InvitedUser
from tests.conftest import sample_invite as create_sample_invite
from tests.conftest import mock_check_invite_token as mock_check_token_invite
def test_existing_user_acce... | normal | {
"blob_id": "0baa133bd9eb8a162a82b23ba4d26cdd34f701c4",
"index": 1507,
"step-1": "<mask token>\n\n\ndef test_existing_user_accept_invite_calls_api_and_redirects_to_dashboard(\n client, service_one, api_user_active, sample_invite, mock_get_service,\n mock_check_invite_token, mock_get_user_by_email,\n moc... | [
8,
10,
11,
12,
13
] |
def search_way(adjacency_list, points):
use = [False for i in range(points.__len__())]
way = [0 for i in range(points.__len__())]
cost = [100000 for i in range(points.__len__())]
cost[0] = 0
checkVar = 0
test = True
while test:
min = 100000
for i in range(points.__len__()):
... | normal | {
"blob_id": "1e4d21998b9f8915167166e5965b0c8c87fcf61d",
"index": 3060,
"step-1": "<mask token>\n",
"step-2": "def search_way(adjacency_list, points):\n use = [(False) for i in range(points.__len__())]\n way = [(0) for i in range(points.__len__())]\n cost = [(100000) for i in range(points.__len__())]\n... | [
0,
1,
2
] |
__author__ = 'Administrator'
# 抓取IP的主要逻辑
from urllib import request
import urllib.parse
import logging
from multiprocessing import pool
from time import sleep
import random
from lxml import etree
def getRandomUserAgnet():
user_agents=[
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Ge... | normal | {
"blob_id": "911631e96d21bdf22a219007f1bdc04a5e6965dc",
"index": 739,
"step-1": "<mask token>\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.ch... | [
3,
4,
5,
6,
7
] |
# Moving Averages Code
# Load the necessary packages and modules
import pandas as pd
import matplotlib.pyplot as plt
import data.stock as st
# Simple Moving Average
def SMA(data, ndays):
SMA = pd.Series(data['close'].rolling(ndays).mean(), name='SMA')
# SMA = pd.Series(pd.rolling_mean(data['close'], ndays),... | normal | {
"blob_id": "4c9f2b6fd119daa58b7f1dd7153c90df747e62cb",
"index": 1249,
"step-1": "<mask token>\n\n\ndef get_sma(stock_code, ndays):\n stock_data = st.get_csv_data(stock_code, 'price')\n sma_data = SMA(stock_data, ndays)\n sma_data = sma_data.dropna()\n return sma_data['SMA']\n\n\n<mask token>\n",
"... | [
1,
3,
4,
5,
6
] |
import numpy as np
from board_specs import *
from board_components import *
import constants
import board_test
# List of resources available to be distributed on the board
RESOURCE_NAMES = constants.RESOURCE_NAMES
# Create a dictionary of each resource and a corresponding number id
res_dict = dict(zip(RESOURCE_NAMES,... | normal | {
"blob_id": "ee22d6226f734c67be91a3ccf1c8c0024bb7dc08",
"index": 5818,
"step-1": "<mask token>\n\n\nclass Board:\n\n def __init__(self):\n \"\"\"\n Do not forget to ensure 6 and 8 are not next to each other:\n no 6-6 no 6-8 no 8-8\n \"\"\"\n self.board_resources = np.array([... | [
7,
8,
10,
12,
13
] |
# Дано натуральное число. Требуется определить,
# является ли год с данным номером високосным.
# Если год является високосным, то выведите `YES`, иначе выведите `NO`.
# Напомним, что в соответствии с григорианским календарем, год является високосным,
# если его номер кратен 4, но не кратен 100, а также если он кратен 4... | normal | {
"blob_id": "99e6e734c7d638e3cf4d50d9605c99d5e700e82a",
"index": 1699,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif year % 4 == 0 and not year % 100 == 0:\n print('YES')\nelif year % 400 == 0:\n print('yes')\nelse:\n print('NO')\n",
"step-3": "year = int(input('введите год '))\nif year % ... | [
0,
1,
2,
3
] |
# -*- coding:utf-8 -*-
from src.Client.Conf.config import *
class SaveConfigFile():
"""
该类负责保存配置文件,属于实际操作类
"""
def __init__(self, fileName='../conf/main.ini'):
self.config = ConfigParser.ConfigParser()
self.fileName = fileName
def saveConfigFile(self, configMainName, configSubN... | normal | {
"blob_id": "b61bb47f3e059c607447cea92ce1712825735822",
"index": 2373,
"step-1": "<mask token>\n\n\nclass SaveConfigFile:\n <mask token>\n\n def __init__(self, fileName='../conf/main.ini'):\n self.config = ConfigParser.ConfigParser()\n self.fileName = fileName\n\n def saveConfigFile(self, ... | [
3,
4,
5,
6,
7
] |
def emphasize(sentence):
words = sentence.split(" ")
for i, word in enumerate(words):
words[i] = word[0].upper() + word[1:].lower()
return " ".join(words)
exp1 = "Hello World"
ans1 = emphasize("hello world")
assert ans1 == exp1, f"expected {exp1}, got {ans1}"
exp2 = "Good Morning"
ans2 = emphasiz... | normal | {
"blob_id": "518dcdca8f5e6b42624083e4327143dfba59b2ba",
"index": 9785,
"step-1": "<mask token>\n",
"step-2": "def emphasize(sentence):\n words = sentence.split(' ')\n for i, word in enumerate(words):\n words[i] = word[0].upper() + word[1:].lower()\n return ' '.join(words)\n\n\n<mask token>\n",
... | [
0,
1,
2,
3,
4
] |
from __future__ import division, print_function, unicode_literals
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from pyglet.gl import *
from pyglet.window import key
from cocos.actions import *
from cocos.director import director
from cocos.layer import Layer
from cocos.scene... | normal | {
"blob_id": "2678aac08104a580e866984bc4cf4adf8cb8ac5c",
"index": 5930,
"step-1": "<mask token>\n\n\nclass SpriteMoveTo(SpriteLayer):\n <mask token>\n\n\nclass FontLayer(Layer):\n\n def __init__(self, title='Sprite Exmaple #', subtitle='Goto()'):\n super(FontLayer, self).__init__()\n self.titl... | [
4,
9,
10,
11,
13
] |
import xml.parsers.expat
import urllib2
import threading
def check_url(checkurl, checkstring, checkname):
try:
opener = urllib2.urlopen(checkurl, timeout = 5)
if checkstring[0] == "!":
if checkstring.encode('utf-8')[1:] not in opener.read():
print "Open",checkname
else:
#print "... | normal | {
"blob_id": "9d3d7000ed13a2623a53705d55b5dbb42662ce2f",
"index": 4296,
"step-1": "import xml.parsers.expat\nimport urllib2\nimport threading\n\n\n\ndef check_url(checkurl, checkstring, checkname):\n try:\n opener = urllib2.urlopen(checkurl, timeout = 5)\n if checkstring[0] == \"!\":\n if checkstring.... | [
0
] |
from django import forms
from django.core.exceptions import ValidationError
from django.db import connection
from customer.helper_funcs import dictfetchall
class OrderForm(forms.Form):
item_id = forms.IntegerField(required=True)
quantity = forms.IntegerField(required=True)
def clean(self):
cleane... | normal | {
"blob_id": "b32784bf398a58ba4b6e86fedcdc3ac9de0e8d51",
"index": 3137,
"step-1": "<mask token>\n\n\nclass OrderForm(forms.Form):\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass OrderForm(forms.Form):\n <mask token>\n <mask token>\n\n def clean(self):\n ... | [
1,
2,
3,
4,
5
] |
from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... | normal | {
"blob_id": "23f491bbf26ede9052ecdab04b8c00cc78db5a7e",
"index": 8831,
"step-1": "<mask token>\n\n\ndef read_csv_json(file_name) ->pandas.DataFrame:\n if file_name.endswith('json') or file_name.endswith('jsonl'):\n df = pandas.read_json(file_name, lines=True)\n elif file_name.endswith('csv'):\n ... | [
9,
13,
16,
18,
19
] |
"""
r - reading fike
w - writing to file
a - append to file / add to the end of the file - always at the end
r+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over,
will overwrite the contents. -> r+ can only be used with alread... | normal | {
"blob_id": "cde2454c68a0d6a0c86b7d647e41a86d3aa97a0d",
"index": 8267,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('haiku.txt', 'w') as file:\n file.write('This is the line 1 of the haiku\\n')\n file.write('Following the line 2 of the haiku\\n')\n file.write('Finishing off with the ... | [
0,
1,
2
] |
# PDE:
# add_library('hype')
# processing.py:
from hype.core.util import H
from hype.core.interfaces import HCallback
from hype.extended.behavior import HOscillator
from hype.extended.drawable import HCanvas, HRect
from hype.extended.layout import HGridLayout
from hype.extended.util import HDrawablePool
from random im... | normal | {
"blob_id": "b8a41c56a31acab0181ec364f76010ac12119074",
"index": 5489,
"step-1": "<mask token>\n\n\nclass Callback(HCallback):\n\n def __init__(self):\n pass\n\n @staticmethod\n def run(drawable):\n drawable.anchorAt(H.CENTER).fill(choice([color1, color2]))\n HOscillator().target(dr... | [
3,
5,
6,
7,
8
] |
import sys
import HTSeq
import re
import string
import glob
import os
import time
import difflib
import argparse
def parse_input():
parser = argparse.ArgumentParser(description="""
USAGE: python make_figs.py -f data_file
""")
# If the -b option is used, tRNAs with no tails are not counted.
# This... | normal | {
"blob_id": "05f5931a53c9916f151f42910575f9c5533bfceb",
"index": 9921,
"step-1": "import sys\nimport HTSeq\nimport re\nimport string\nimport glob\nimport os\nimport time\nimport difflib\nimport argparse\n\n\ndef parse_input():\n parser = argparse.ArgumentParser(description=\"\"\"\n USAGE: python make_figs.... | [
0
] |
import sys
import sucessor
import expande
from collections import deque
def busca_caminho(nodo_final, nodo_inicial):
pilha_acoes = deque() # iremos empilhar as acoes já que a estaremos com a ordem reversa a priori
v = nodo_final
while v != nodo_inicial:
pilha_acoes.append(v.acao)
v = v.pai
return pilha_acoes
... | normal | {
"blob_id": "a85a7ad6ffb2b9aa5f5326d11c75ddbee680fac4",
"index": 673,
"step-1": "<mask token>\n\n\ndef busca_dfs(nodo_inicial, custo_maximo_atual):\n objetivo = '12345678_'\n custo_maximo_absoluto = 100\n explorados = set()\n fronteira = deque()\n fronteira.append(nodo_inicial)\n if custo_maxim... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 18:39:26 2020
@author: Fanny Fredriksson and Karen Marie Sandø Ambrosen
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm #count ffor loops
import math
from sklearn.model_selection import GridSearch... | normal | {
"blob_id": "69511933697905fb4f365c895264596f19dc1d8d",
"index": 5021,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef leaveKout_CV(X, y, n_scz_te, rep, perms, classifiers, parameters, count,\n freq_bands, x_size, auc, nz_coef_idx, nz_coef_val, n_BAitaSig=None):\n \"\"\"\n Calculates the ... | [
0,
3,
4,
5,
6
] |
## n.b. uses python 3 wordseg virtualenv (wordseg needs Py3)
# e.g. $ source ~/venvs/Py3/wordseg/bin/activate
## wordseg: see https://wordseg.readthedocs.io
from __future__ import division
import io, collections, os, glob, csv, re
from scipy.stats import entropy
from copy import deepcopy
# get username
impo... | normal | {
"blob_id": "4ba0affd3cbdc2652274213a8d410b541fb3edb4",
"index": 4584,
"step-1": "<mask token>\n\n\ndef process_corpus(lcount, text, language, corpus, child, utts, owus, pdict,\n bdict):\n owu = owus / utts\n lineout1 = [language, corpus, child, utts, owu]\n ordered = sorted(pdict.items(), key=lambda... | [
1,
3,
4,
5,
6
] |
from django import http
from django.utils import simplejson as json
import urllib2
import logging
from google.appengine.api import urlfetch
import cmath
import math
from ams.forthsquare import ForthSquare
from ams.twitter import Twitter
OAUTH_TOKEN='3NX4ATMVS35LKIP25ZOKIVBRGAHFREKGNHTAKQ5NPGMCWOE0'
DEFAULT_RADIUS = ... | normal | {
"blob_id": "bd1fbdf70bae7d5853bac8fae83343dfa188ca19",
"index": 5391,
"step-1": "from django import http\nfrom django.utils import simplejson as json\nimport urllib2\nimport logging\nfrom google.appengine.api import urlfetch\nimport cmath\nimport math\nfrom ams.forthsquare import ForthSquare\nfrom ams.twitter i... | [
0
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, masonarmani38@gmail.com and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class LogisticsPlanningTool(Document):
def autoname(self):
if self.cust... | normal | {
"blob_id": "4cbb78234ef6e63b856099060ecaeea1779d6ac5",
"index": 8412,
"step-1": "<mask token>\n\n\nclass LogisticsPlanningTool(Document):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass LogisticsPlanningTool(Document):\n\n def autoname(self):\n if self.customer:\n ... | [
1,
2,
3,
4,
5
] |
from django import template
import random
register = template.Library()
@register.simple_tag
def random_quote():
"""Returns a random quote to be displayed on the community sandwich page"""
quotes = [
"Growth is never by mere chance; it is the result of forces working together.\n-James Cash Penney",
... | normal | {
"blob_id": "6e73625adc10064cdb1b5f0546a4fc7320e9f5dc",
"index": 8366,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@register.simple_tag\ndef random_quote():\n \"\"\"Returns a random quote to be displayed on the community sandwich page\"\"\"\n quotes = [\n \"\"\"Growth is never by mere... | [
0,
1,
2,
3,
4
] |
# from https://web.archive.org/web/20121220025758/http://xkcd.com/actuary.py.txt
# script written by Randall Munroe. Most comments by Emily Cain (although there were a few brief ones explaining how the program worked before I looked at it)
# Summary of program (by Emily):
# this program takes inputs of current ages ... | normal | {
"blob_id": "f0702c8555ef07aac9e667c35b5b5fd85820ec54",
"index": 4355,
"step-1": "# from https://web.archive.org/web/20121220025758/http://xkcd.com/actuary.py.txt\n\n# script written by Randall Munroe. Most comments by Emily Cain (although there were a few brief ones explaining how the program worked before I lo... | [
0
] |
num=int(input())
i=10
while i>=1:
print(i,end=" ")
i-=1
| normal | {
"blob_id": "ec0113dbd79e936e614bb7ee7e48d29aa616d511",
"index": 7389,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile i >= 1:\n print(i, end=' ')\n i -= 1\n",
"step-3": "num = int(input())\ni = 10\nwhile i >= 1:\n print(i, end=' ')\n i -= 1\n",
"step-4": "num=int(input())\r\ni=10\r\... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
import sys
import errno
# read first line from stdin and discard it
first_line = sys.stdin.readline()
# print all other lines
for line in sys.stdin:
try:
print line,
except IOError, e:
if e.errno == errno.EPIPE:
exit(0)
| normal | {
"blob_id": "bd06b04666ade1e7591b02f8211bc9b62fd08936",
"index": 791,
"step-1": "#!/usr/bin/env python\nimport sys\nimport errno\n\n# read first line from stdin and discard it\nfirst_line = sys.stdin.readline()\n\n# print all other lines\nfor line in sys.stdin:\n try:\n print line,\n except IOError,... | [
0
] |
import math
def math_builtins():
assert abs(-123) == 123
assert abs(-123.456) == 123.456
assert abs(2+3j) == math.sqrt(2**2 + 3**2)
assert divmod(5, 2) == (2, 1)
assert max(1, 2, 3, 4) == 4
assert min(1, 2, 3, 4) == 1
a = 2
b = 3
c = 7
assert pow(a, b) == a ** b
assert po... | normal | {
"blob_id": "c77db71844c65eb96946ac0cc384de43ad49ca99",
"index": 6007,
"step-1": "<mask token>\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2)\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n ... | [
2,
3,
4,
5,
6
] |
from django.test import TestCase
from .models import Post, Category, Tag
# Create your tests here.
class TestPost(TestCase):
def test_str(self):
my_title = Post(title='This is a basic title for a basic test case')
self.assertEquals(str(my_title), 'This is a basic title for a basic test case')
c... | normal | {
"blob_id": "825c9510b055c0fa570f577b1c9616e8bde9c98b",
"index": 7653,
"step-1": "<mask token>\n\n\nclass TestCategory(TestCase):\n\n def test_str(self):\n category = Category(name='Test Category')\n self.assertEquals(str(category), 'Test Category')\n\n\nclass TestTag(TestCase):\n\n def test_... | [
4,
5,
6,
7,
8
] |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from sklearn.preprocessing import normalize
def blackbox_function(x, y=None, sim=False):
if sim:
if y is None:
return -x ** 2 + 6
else:
return -(x+y) ** 2 + 6
# Reading the magnitude of t... | normal | {
"blob_id": "6defbe25fc17e53df2fc4d32886bba1cb141bdfd",
"index": 7018,
"step-1": "<mask token>\n\n\ndef obtain_confidence(sim=False):\n if sim:\n noise = np.random.normal(0, 0.6, size=1)[0]\n return noise\n filename = 'Confidence.txt'\n lines = open(filename).read().splitlines()\n try:\... | [
2,
3,
4,
5,
6
] |
from dataclasses import dataclass
from datetime import date
@dataclass
class Book:
id: int
title: str
author: str
genre: str
published: date
status: str = 'Available'
def __str__(self):
return f'{self.id}: {self.title} by {self.author}'
def get_more_information(self):
... | normal | {
"blob_id": "dc13ca17bff8e2a5254c7758bd7274926bafd454",
"index": 5312,
"step-1": "<mask token>\n\n\n@dataclass\nclass Book:\n id: int\n title: str\n author: str\n genre: str\n published: date\n status: str = 'Available'\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\n@dat... | [
1,
2,
3,
4,
5
] |
from mf_app import db
from mf_app.models import User
db.create_all()
#test input data
admin = User('admin', 'admin@admin.com', 'admin')
guest = User('guest', 'guest@guest.com', 'guest')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print(users) | normal | {
"blob_id": "99c2bd56deccc327faf659e91fc1fd0f6ff7a219",
"index": 3932,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndb.create_all()\n<mask token>\ndb.session.add(admin)\ndb.session.add(guest)\ndb.session.commit()\n<mask token>\nprint(users)\n",
"step-3": "<mask token>\ndb.create_all()\nadmin = User('... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
# Creates a new task from a given task definition json and starts on
# all instances in the given cluster name
# USAGE:
# python ecs-tasker.py <task_definition_json_filename> <cluster_name>
# EXAMPLE:
# python ecs-tasker.py ecs-task-stage.json cops-cluster
import boto3
import json
import sys
im... | normal | {
"blob_id": "3b613ec75088d6d9a645443df2bbc2f33b80000b",
"index": 6984,
"step-1": "#!/usr/bin/env python\n# Creates a new task from a given task definition json and starts on\n# all instances in the given cluster name\n# USAGE:\n# python ecs-tasker.py <task_definition_json_filename> <cluster_name>\n# EXAMPLE:\n#... | [
0
] |
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes,
kernel_size=3, stride=stri... | normal | {
"blob_id": "d3f42f329246164cdb6113df3da0eb2d3203b2a9",
"index": 7114,
"step-1": "<mask token>\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1,... | [
13,
15,
18,
22,
25
] |
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# driver = webdriver.Chrome('C:/automation/chromedriver')
# wait = W... | normal | {
"blob_id": "0a23b16329d8b599a4ee533604d316bdfe4b579a",
"index": 4832,
"step-1": "<mask token>\n\n\nclass Methodos(object):\n\n def __init__(self, driver):\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 15)\n <mask token>\n\n def Click(self, id):\n e = self.wait.unt... | [
3,
4,
5,
6,
7
] |
import sqlite3
# cur.execute('CREATE TABLE admin(username TEXT,password TEXT)')
# conn.commit()
# cur.execute("INSERT INTO admin VALUES('nilesh','nilesh')")
# conn.commit()
def verif_admin(username, password):
try:
conn = sqlite3.connect('SuperMarket.db')
cur = conn.cursor()
print(usernam... | normal | {
"blob_id": "88d0ced41a8f176a8a12bba6406b4162ea6dfc52",
"index": 9308,
"step-1": "<mask token>\n\n\ndef update_delete_product(rowid, id_, name, quantity, cost, qry):\n if id_ == '' and name == '' and quantity == '' and cost == '':\n return False, ' You Cannot Leave It Empty '\n try:\n conn =... | [
3,
6,
7,
9,
10
] |
from flask import Blueprint
views = Blueprint('views', __name__)
from . import routes
| normal | {
"blob_id": "139ccdaf7acb2a2d74649f0c32217d1fe71a954a",
"index": 4800,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nviews = Blueprint('views', __name__)\n<mask token>\n",
"step-3": "from flask import Blueprint\nviews = Blueprint('views', __name__)\nfrom . import routes\n",
"step-4": null,
"step-5... | [
0,
1,
2
] |
# coding: utf-8
"""
Knetik Platform API Documentation latest
This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
OpenAPI spec version: latest
Contact: support@knetik.com
Generated by: https://github.com/swagger-api/swagger-codeg... | normal | {
"blob_id": "05aec07b94f3363e07d8740b102262d817e08e71",
"index": 1253,
"step-1": "# coding: utf-8\n\n\"\"\"\n Knetik Platform API Documentation latest \n\n This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.\n\n OpenAPI spec version: lat... | [
0
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `feat` package."""
from feat.detector import Detector
from feat.data import Fex
from feat.utils import get_resource_path
from .utils import get_test_data_path
import pandas as pd
import feat
import os
import wget
# def test_models():
# print("Downloading... | normal | {
"blob_id": "753bdbf080e7a8652c39e40beeae51f74382d606",
"index": 1300,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_detector():\n detector = Detector(n_jobs=1)\n assert detector['n_jobs'] == 1\n assert type(detector) == Detector\n inputFname = os.path.join(get_test_data_path(),... | [
0,
1,
2,
3
] |
import pandas as pd
import numpy as np
import math
from sklearn.datasets import load_digits, load_iris, load_boston, load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import pairwise_distances
class KMeans():
def __init__(self, k = 5, max_iters = 100, random_seed = 42):... | normal | {
"blob_id": "d267c8cbe51fb1bacc9404a1385f1daa4a0db7f2",
"index": 884,
"step-1": "<mask token>\n\n\nclass KMeans:\n\n def __init__(self, k=5, max_iters=100, random_seed=42):\n self.k = k\n self.max_iters = max_iters\n np.random.seed(random_seed)\n\n def _initialise_centroids(self, X):\n... | [
6,
7,
8,
10,
12
] |
from utils import create_data_lists
if __name__ == '__main__':
create_data_lists(ICDAR_path=
'../ICDAR_Dataset/0325updated.task1train(626p)', output_folder=
'../ICDAR_Dataset/0325updated.task1train(626p)')
| normal | {
"blob_id": "6334a8a052d72b0f13395b301bd5a766acf4399b",
"index": 3437,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n create_data_lists(ICDAR_path=\n '../ICDAR_Dataset/0325updated.task1train(626p)', output_folder=\n '../ICDAR_Dataset/0325updated.task1train(62... | [
0,
1,
2
] |
import requests
import os
from jpmesh import parse_mesh_code
from tqdm import tqdm
url_login='https://platform.openquake.org/account/login/'
client = requests.session()
client.get(url_login)
# Identification for openquake platform
login_data = {'username':'###','password':'###'}
r1=client.post(url_login,data=login_dat... | normal | {
"blob_id": "63a40282f16a7f27c118594f1a9468749682594f",
"index": 420,
"step-1": "import requests\nimport os\nfrom jpmesh import parse_mesh_code\nfrom tqdm import tqdm\n\nurl_login='https://platform.openquake.org/account/login/'\nclient = requests.session()\nclient.get(url_login)\n# Identification for openquake p... | [
0
] |
# test CurlypivSetup
"""
Notes about program
"""
# 1.0 import modules
import numpy as np
from skimage import io
import glob
from os.path import join
import matplotlib.pyplot as plt
from curlypiv.utils.calibrateCamera import measureIlluminationDistributionXY, calculate_depth_of_correlation, calculate_darkfield, plot_fi... | normal | {
"blob_id": "6ca7b896cc20220f790c06d4ba08fef7bda8400f",
"index": 3301,
"step-1": "<mask token>\n\n\nclass illumination(object):\n <mask token>\n\n\nclass darkfield(object):\n\n def __init__(self, basePath, darkframePath=None, flip_image_across_axis\n =None, show_image=False, save_image=False, save_i... | [
37,
41,
45,
48,
50
] |
import time
# Decorator
def measure_time_of_func(func):
def wrapper_func(n):
start_time = time.time()
fib_seq = func(n)
end_time = time.time()
return (fib_seq, end_time - start_time)
return wrapper_func
# Returns a list with first n numbers of fibonacci sequence.
@measure_ti... | normal | {
"blob_id": "2c39660da8fe839c4634cd73ce069acc7b1b29b4",
"index": 51,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@measure_time_of_func\ndef fib(n):\n sequence = [1, 1]\n for i in range(2, n, 1):\n sequence.append(sequence[i - 1] + sequence[i - 2])\n return sequence\n",
"step-3": ... | [
0,
1,
2,
3,
4
] |
import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
'/store/mc/Summer12_DR53X... | normal | {
"blob_id": "965bb4c8e7d6650dab7f002645dceacab59a0c5c",
"index": 7298,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nreadFiles.extend([\n '/store/mc/Summer12_DR53X/TTH_Inclusive_M-115_8TeV_pythia6/AODSIM/PU_S10_START53_V7A-v1/00000/FE26AAB2-D90B-E211-AD0F-0025902009B8.root'\n ,\n '/store/mc/Sum... | [
0,
1,
2,
3,
4
] |
from sqlalchemy import create_engine, Column, Integer, Float, \
String, Text, DateTime, Boolean, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from flask_sqlalchemy import SQLAlchemy
engine = create_engine('sqlite:///app/databases/fays-web-... | normal | {
"blob_id": "3d2b8730953e9c2801eebc23b6fb56a1b5a55e3c",
"index": 6156,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nengine = create_engine('sqlite:///app/databases/fays-web-dev.db',\n connect_args={'check_same_thread': False})\nSession = sessionmaker(bind=engine)\nsession = Session()\nBase = declara... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 10:28:04 2020
@author: Maxi
"""
import numpy as np
from ase.io import read
from RDF_3D import pairCorrelationFunction_3D
import matplotlib.pyplot as plt
filename = r"C:\Users\Maxi\Desktop\t\Ag_HfO2_cat_3.125_222_t.cif"
crystal = read(filename)
corrdinates = cryst... | normal | {
"blob_id": "516d9790f40c021d45302948b7fba0cf3e00da0a",
"index": 6322,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.figure()\nplt.plot(r, g_r, color='black')\nplt.xlabel('r')\nplt.ylabel('g(r)')\nplt.xlim((0, rmax))\nplt.ylim((0, 1.05 * g_r.max()))\nplt.show()\n",
"step-3": "<mask token>\nfilenam... | [
0,
1,
2,
3,
4
] |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^stats/$', views.get_stats, name='stats'),
url(r'^follow/me/$', views.follow_me, name='follow_me'),
url(r'^follower/confirm/$', views.confirm_follower, name='follower_confirm'),
url(r'^execute/', views.execute, name='executed')... | normal | {
"blob_id": "33b68246dd3da9561c1d4adb5a3403cba656dcee",
"index": 9175,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('^stats/$', views.get_stats, name='stats'), url(\n '^follow/me/$', views.follow_me, name='follow_me'), url(\n '^follower/confirm/$', views.confirm_follower, name=... | [
0,
1,
2,
3
] |
import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... | normal | {
"blob_id": "4d0f612c74dc175766f489580fc4a492e1bfd085",
"index": 4345,
"step-1": "<mask token>\n\n\n@dataclass\nclass Actions:\n \"\"\" The class for a set of actions.\n\n This class is a collection of actions. It is used to for the four primary\n usecases:\n - to serialize the list of actions in... | [
10,
13,
19,
23,
25
] |
import itertools
n = int(input())
a = [list(map(int, input().split(" "))) for i in range(n)]
ans = 0
for [ix,iy], [jx, jy] in itertools.combinations(a, 2):
ans += ((jx-ix)**2+(jy-iy)**2)**0.5*2
print(ans/n) | normal | {
"blob_id": "a210a015284130f23bfec99898f2f21163a33a67",
"index": 9897,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor [ix, iy], [jx, jy] in itertools.combinations(a, 2):\n ans += ((jx - ix) ** 2 + (jy - iy) ** 2) ** 0.5 * 2\nprint(ans / n)\n",
"step-3": "<mask token>\nn = int(input())\na = [list... | [
0,
1,
2,
3,
4
] |
import unittest
import os
import tempfile
import numpy as np
from keras_piecewise.backend import keras
from keras_piecewise import Piecewise2D
from .util import MaxPool2D
class TestPool2D(unittest.TestCase):
@staticmethod
def _build_model(input_shape, layer, row_num, col_num, pos_type=Piecewise2D.POS_TYPE_SE... | normal | {
"blob_id": "1af9fb91e69ea78709c47fca6b12e4f7a6fd17a8",
"index": 7392,
"step-1": "<mask token>\n\n\nclass TestPool2D(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestPool2D(unittest.TestCase):\n\n @staticmethod\n def _build_model(input_s... | [
1,
3,
4,
5,
6
] |
import os
import sys
from shutil import copyfile
def buildDocumentation():
"""
Build eMonitor Documentation with sphinx
:param sys.argv:
* html: build html documentation in directory */docs/output/html*
* pdf: build pdf documentation in directory */docs/output/pdf*
"""
helptext = 'u... | normal | {
"blob_id": "e60c3a6aececd97ec08ae32b552bcda795375b3b",
"index": 779,
"step-1": "import os\nimport sys\nfrom shutil import copyfile\n\n\ndef buildDocumentation():\n \"\"\"\n Build eMonitor Documentation with sphinx\n\n :param sys.argv:\n\n * html: build html documentation in directory */docs/output... | [
0
] |
"""After seeing how great the lmfit package, I was inspired to create my own
object using it. This acts as a fitting template.
"""
##-------------------------------PREAMBLE-----------------------------------##
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, fit_report
impo... | normal | {
"blob_id": "9e16921d83a5f62aad694b26a92b57b97ccda461",
"index": 1651,
"step-1": "<mask token>\n\n\nclass FitTemplate:\n\n def __init__(self, fit_function, log_dir=None):\n self.fit_function = fit_function\n self.parameters = Parameters()\n self.fit_result = None\n if log_dir is no... | [
6,
7,
8,
9,
10
] |
import numpy as np
from load_data import load_entity, load_candidates2, load_train_data
def predict_batch(test_data, model, batch_size=None):
result = model.predict(test_data, batch_size=batch_size)
return result
def predict_data(test_data, entity_path, model, predict_path, score_path, test_path, dataset):
... | normal | {
"blob_id": "a19616d448da057d5be0af841467a25baaacf5b3",
"index": 9299,
"step-1": "<mask token>\n\n\ndef predict_batch(test_data, model, batch_size=None):\n result = model.predict(test_data, batch_size=batch_size)\n return result\n\n\n<mask token>\n\n\ndef post_predict(test_path, score_path, entity_path, al... | [
2,
3,
4,
5,
6
] |
#! /usr/bin/env python3
#
# This file is part of Toboggan, https://github.com/TheoryInPractice/Toboggan/,
# and is Copyright (C) North Carolina State University, 2017. It is licensed
# under the three-clause BSD license; see LICENSE.
#
# -*- coding: utf-8 -*-
# python libs
import sys
import itertools
# local imports
fr... | normal | {
"blob_id": "1b4c9841fd10d065983974e93fe5dcbe048c1281",
"index": 4180,
"step-1": "<mask token>\n\n\ndef is_feasible(weights, flow, max_weight):\n \"\"\"Test whether set of guessed weights is feasible.\"\"\"\n min_weights = [1] + weights\n max_weights = [max_weight] + list(reversed(weights))\n for i i... | [
1,
2,
3,
4,
5
] |
########################################
__author__ = "Abdelrahman Eldesokey"
__license__ = "GNU GPLv3"
__version__ = "0.1"
__maintainer__ = "Abdelrahman Eldesokey"
__email__ = "abdo.eldesokey@gmail.com"
########################################
import torch
import torch.nn.functional as F
import torch.nn as nn
from to... | normal | {
"blob_id": "64b4deaad548a38ba646423d33fc6a985483a042",
"index": 3592,
"step-1": "<mask token>\n\n\nclass NConv2d(_ConvNd):\n <mask token>\n <mask token>\n\n def init_parameters(self):\n if self.init_method == 'x':\n torch.nn.init.xavier_uniform_(self.weight)\n elif self.init_me... | [
15,
17,
18,
19,
21
] |
#!/usr/bin/env python3
import json
import sqlite3
import sys
from scorelib import *
#from .scorelib import *
from collections import defaultdict
def __map2list(mp):
if len(mp.keys()) == 0:
return []
lst = [None] * max(mp.keys())
for idx in mp.keys():
lst[idx-1] = mp[idx]
return lst
d... | normal | {
"blob_id": "9f6e5c219f7b668720b5379dde912ff22ef434d1",
"index": 9072,
"step-1": "<mask token>\n\n\ndef __map2list(mp):\n if len(mp.keys()) == 0:\n return []\n lst = [None] * max(mp.keys())\n for idx in mp.keys():\n lst[idx - 1] = mp[idx]\n return lst\n\n\ndef __translate_keys(translati... | [
4,
5,
6,
7,
8
] |
from eboss_qso.fits.joint import run_joint_mcmc_fit
from eboss_qso.measurements.utils import make_hash
import os.path as osp
import os
from glob import glob
ARGS = [(False, 1.0),
(False, 1.6),
(True, 1.6),
(True, 1.0)
]
ITERATIONS = 500
WALKERS = 100
def main(argnum, kmin):
z_we... | normal | {
"blob_id": "a40c87fe4b805495e5bd30155faa861cbe16c368",
"index": 6123,
"step-1": "<mask token>\n\n\ndef main(argnum, kmin):\n z_weighted, p = ARGS[argnum]\n kws = {}\n kws['version'] = 'v1.9f'\n kws['krange'] = '%s-0.3' % kmin\n kws['params'] = 'basemodel-N-fnl'\n kws['zrange'] = '0.8-2.2'\n ... | [
1,
2,
3,
4,
5
] |
import base
import telebot
import markups
from starter import start_bot, bot
@bot.message_handler(commands=['start'])
def start(message):
chat = message.chat
# welcome(msg)
msg = bot.send_message(chat.id, "Select a language in the list", reply_markup=markups.language())
bot.register_next_step_handler(... | normal | {
"blob_id": "7cc77de31adff5b4a394f117fc743cd6dd4bc06c",
"index": 6065,
"step-1": "<mask token>\n\n\ndef llanguage(msg):\n chat = msg.chat\n base.create_user(msg.chat.id, msg.text)\n markup = telebot.types.ReplyKeyboardMarkup(True, True)\n markup.row('ok')\n str = bot.send_message(msg.chat.id, base... | [
19,
20,
30,
36,
37
] |
# Generated by Django 2.1.5 on 2019-03-12 18:07
from django.db import migrations
def associate_experiments_to_organisms(apps, schema_editor):
"""Creates missing associations between experiments and organisms.
Based off of:
https://simpleisbetterthancomplex.com/tutorial/2017/09/26/how-to-create-django-da... | normal | {
"blob_id": "b4b2307897f64bb30cad2fbaaa1b320ae2aa7456",
"index": 8553,
"step-1": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('data_refinery_common', '0015_dataset_emai... | [
1,
2,
3,
4,
5
] |
from pig_util import outputSchema
@outputSchema('word:chararray')
def reverse(word):
"""
Return the reverse text of the provided word
"""
return word[::-1]
@outputSchema('length:int')
def num_chars(word):
"""
Return the length of the provided word
"""
return len(word)
| normal | {
"blob_id": "94560d8f6528a222e771ca6aa60349d9682e8f4b",
"index": 6558,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@outputSchema('word:chararray')\ndef reverse(word):\n \"\"\"\n Return the reverse text of the provided word\n \"\"\"\n return word[::-1]\n\n\n<mask token>\n",
"step-3": "<... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty, EmptyResponse
import tf
from math import radians, degrees, fabs
class MovementNullifier:
def __init__(self):
rospy.Subscriber("odom", Odometry, self.OdomCallback)
... | normal | {
"blob_id": "c349fa484476e3195e0932e425cbe93d7a7e5394",
"index": 1225,
"step-1": "<mask token>\n\n\nclass MovementNullifier:\n\n def __init__(self):\n rospy.Subscriber('odom', Odometry, self.OdomCallback)\n rospy.Subscriber('cmd_vel', Twist, self.TwistCallback)\n self.cmd_vel_publisher = ... | [
7,
8,
10,
11,
12
] |
import socket
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(20,GPIO.OUT,initial=GPIO.LOW) #green
GPIO.setup(21,GPIO.OUT,initial=GPIO.LOW) #red
GPIO.setwarnings(False)
host = '192.168.87.191'
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Soc... | normal | {
"blob_id": "78efe97d838774cb831ef205186db29f392e1953",
"index": 1584,
"step-1": "<mask token>\n\n\ndef RED(t):\n GPIO.output(21, 1)\n time.sleep(1)\n GPIO.output(21, 0)\n\n\n<mask token>\n\n\ndef dataTransfer(conn):\n while True:\n data = conn.recv(1024)\n data = data.decode('utf-8')\n... | [
2,
4,
7,
9,
10
] |
import math
import numpy as np
class incStat:
def __init__(self, Lambda, isTypeJitter=False): # timestamp is creation time
self.CF1 = 0 # linear sum
self.CF2 = 0 # sum of squares
self.w = 0 # weight
self.isTypeJitter = isTypeJitter
self.Lambda = Lambda # Decay Factor
... | normal | {
"blob_id": "7b2ca3db44c5f71c2975bd8af701dafca3b3d081",
"index": 5492,
"step-1": "<mask token>\n\n\nclass windowed_incStat:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass windowed_incStat_2D:\n\n def __init__(self, L):\n self.incSt... | [
18,
32,
35,
44,
46
] |
import requests
from os.path import join, exists
import os
import fitz
from tqdm import tqdm
from pathlib import Path
import tempfile
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + ".pdf")
open(file_path, 'wb').write(r.content)
return f... | normal | {
"blob_id": "c6113088f45951bc4c787760b6ca0138265fb83f",
"index": 9966,
"step-1": "<mask token>\n\n\ndef download_pdf(url, folder, name):\n r = requests.get(url, allow_redirects=True)\n file_path = join(folder, name + '.pdf')\n open(file_path, 'wb').write(r.content)\n return file_path\n\n\n<mask token... | [
2,
3,
4,
5,
6
] |
import pytz
import datetime
def apply_timezone_datetime(_local_tz: str, _time: datetime.time):
"""
set time zone + merge now().date() with time()
:param _local_tz:
:param _time:
:return:
"""
return pytz.timezone(_local_tz).localize(datetime.datetime.combine(
datetime.datetime.now()... | normal | {
"blob_id": "347627df4b08eca6e2137161472b4d31534cf81b",
"index": 1238,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef apply_timezone_datetime(_local_tz: str, _time: datetime.time):\n \"\"\"\n set time zone + merge now().date() with time()\n :param _local_tz:\n :param _time:\n :retu... | [
0,
1,
2
] |
#!/usr/bin/env python3
from collections import OrderedDict
import torch.nn as nn
from fairseq.models import FairseqMultiModel, register_model
from pytorch_translate import common_layers, utils
@register_model("multilingual")
class MultilingualModel(FairseqMultiModel):
"""
To use, you must extend this class ... | normal | {
"blob_id": "0ac471d2cb30a21c1246106ded14cdc4c06d2d40",
"index": 8329,
"step-1": "<mask token>\n\n\n@register_model('multilingual')\nclass MultilingualModel(FairseqMultiModel):\n <mask token>\n\n def __init__(self, task, encoders, decoders):\n super().__init__(encoders, decoders)\n self.task ... | [
4,
5,
6,
7,
8
] |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 19:16:16 2019
@author: pc
"""
from socket import *
import threading
import time
import cv2
import struct
import pickle
import zlib
import cartoon_edit
import face_capture_edit
import pencil_edit
class Video_Server(threading.Thread):
def __init__ (self, port, vers... | normal | {
"blob_id": "6b138dabf57166ec971052fff7df89ae0346e083",
"index": 1582,
"step-1": "<mask token>\n\n\nclass Video_Server(threading.Thread):\n <mask token>\n <mask token>\n\n def run(self):\n detector, predictor = face_capture_edit.face_init(self.\n face_shape_predictor)\n print('f... | [
2,
3,
4,
5,
6
] |
from sqlalchemy.orm import sessionmaker
from IMDB.spiders.models import IMDB_DATABASE, db_connect, create_table
class ScrapySpiderPipeline(object):
# Bu Fonksiyon Veritabanı bağlantısını ve oturum oluşturucuyu başlatır ve bir İlişkisel Veritabanı tablosu oluşturur.
def __init__(self):
en... | normal | {
"blob_id": "16074fc1824a99b6fd1c4bf113d5b752308e8803",
"index": 5198,
"step-1": "<mask token>\n\n\nclass ScrapySpiderPipeline(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ScrapySpiderPipeline(object):\n\n def __init__(self):\n engine = db_connect()\n cre... | [
1,
2,
3,
4,
5
] |
# PROBLEM: Code organized in package and want to import a submodule from one o the other pkg
# submodules without hardcoding the package name into the import statement
# SOLUTION: Use pkg-relative import
# Absolete path
from mypackage.A import grok
print(dir(grok))
grok.testA() | normal | {
"blob_id": "ad9facb9c8e552845df9171549f886f3e9cba193",
"index": 7544,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(dir(grok))\ngrok.testA()\n",
"step-3": "from mypackage.A import grok\nprint(dir(grok))\ngrok.testA()\n",
"step-4": "# PROBLEM: Code organized in package and want to import a su... | [
0,
1,
2,
3
] |
# Runtime: 44 ms, faster than 62.95% of Python3 online submissions for Rotate List.
# Memory Usage: 13.9 MB, less than 6.05% of Python3 online submissions for Rotate List.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class... | normal | {
"blob_id": "a79c9799ed237a943ae3d249a4d66eb2f8693e83",
"index": 1896,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def rotateRight(self, head: ListNode, k: int) ->ListNode:\n if head is None or head.next is None or k == 0:\n ... | [
0,
1,
2,
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.