code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .models import Post
from django.shortcuts import redirect
from django.core.exceptions import ObjectDoesNotExist
def index(request):
blogs = Post.objects.filter(status=... | normal | {
"blob_id": "aec374ffa368755350d0d75c96860f760e8524e1",
"index": 7301,
"step-1": "<mask token>\n\n\ndef index(request):\n blogs = Post.objects.filter(status=1).order_by('-created_on')[:10]\n context = {'Post': blogs}\n return render(request, 'blogapp/index.html', context)\n\n\ndef blogs(request):\n r... | [
6,
7,
8,
9,
10
] |
from rest_framework import serializers
from django.contrib import auth
from rest_framework.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from django.utils.translation import gettext as _
from rest_users.utils.api import _build_initial_user
User = auth.get_user_... | normal | {
"blob_id": "88e34878cdad908ed4ac30da82355aaa46ed719b",
"index": 5429,
"step-1": "<mask token>\n\n\nclass RegisterUserSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = User\n fields = '__all__'\n\n def validate_password(self, password):\n user = _build_initial_user(s... | [
10,
13,
14,
15,
21
] |
#给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。你可以返回满足此条件的任何数组作为答案
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
l=[]
r=[]
for x in A:
if(x%2==0):
l.append(x)
else:
r.append(x)
ans=l+r
return a... | normal | {
"blob_id": "ae4d12ff88cf08b2e19b212c80549adc0a0d47dc",
"index": 2030,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def sortArrayByParity(self, A: List[int]) ->List[int]:\n l = []\n r = []\n for x in A:\n if x %... | [
0,
1,
2,
3
] |
class ModelInfo:
def __init__(self, name: str, path: str, filter: str):
self.name: str = name
self.path: str = path
self.filter: str = filter
| normal | {
"blob_id": "def089c2749444797ac3079809c082dacab08554",
"index": 1167,
"step-1": "<mask token>\n",
"step-2": "class ModelInfo:\n <mask token>\n",
"step-3": "class ModelInfo:\n\n def __init__(self, name: str, path: str, filter: str):\n self.name: str = name\n self.path: str = path\n ... | [
0,
1,
2
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | normal | {
"blob_id": "5c8628e41c0dd544ade330fdd37841beca6c0c91",
"index": 3986,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass TriangleError(Exception):\n pass\n",
"step-3": "def triangle(a, b, c):\n \"\"\"\n Determines the number of non-matching sides using len(set()). Then uses dictiona... | [
0,
1,
2,
3
] |
from .parapred import main
main()
| normal | {
"blob_id": "96cb2754db2740767dfb145078ed17969e85123d",
"index": 843,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmain()\n",
"step-3": "from .parapred import main\nmain()\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
#### про enumerate
##s = input()
##for index, letter in enumerate(s):
## print(index,':',letter)
#### то же что и
##for i in range(len(s)):
## print (i,':', s[i])
#### номер начала каждого слова
##st = input()
##for index, symbol in enumerate(st):
## if symbol == ' ' and index != len(st)-1 or index == 0 or in... | normal | {
"blob_id": "f4bfef2ee78b87184cc72666fade949f8f931fc3",
"index": 826,
"step-1": "#### про enumerate\n##s = input()\n##for index, letter in enumerate(s):\n## print(index,':',letter)\n#### то же что и\n##for i in range(len(s)):\n## print (i,':', s[i])\n\n#### номер начала каждого слова\n##st = input()\n##for... | [
1
] |
import pygame
import os
from network import Network
from card import Card
from game import Game, Player
pygame.font.init()
# Initializing window
WIDTH, HEIGHT = 700, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Zole")
CARD_WIDTH = 60
############################## Uploading cards
de... | normal | {
"blob_id": "9c478c59398618d0e447276f9ff6c1c143702f12",
"index": 2360,
"step-1": "<mask token>\n\n\ndef get_card_size(card_width, image):\n card_height = image.get_height() / (image.get_width() / card_width)\n return round(card_height)\n\n\n<mask token>\n\n\ndef upload_card_images(card_name):\n card_n =... | [
6,
7,
8,
9,
10
] |
import os
os.environ['CITY_CONF'] = '/opt/ris-web/city/duisburg.py'
from webapp import app
app.run(debug=True, host='0.0.0.0')
| normal | {
"blob_id": "4276fd61ad48b325961cd45be68eea6eab51f916",
"index": 6085,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp.run(debug=True, host='0.0.0.0')\n",
"step-3": "<mask token>\nos.environ['CITY_CONF'] = '/opt/ris-web/city/duisburg.py'\n<mask token>\napp.run(debug=True, host='0.0.0.0')\n",
"step... | [
0,
1,
2,
3
] |
import django
from rest_framework import serializers
from django.shortcuts import render
from .models import Student
from .serializiers import StudentSerializer
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse,JsonResponse
import io
from rest_framework.parsers import JSONParser
f... | normal | {
"blob_id": "99785ffb4b594db1fac05ca3d3f5764151b2b7b6",
"index": 103,
"step-1": "<mask token>\n\n\n@csrf_exempt\ndef create(request):\n if request.method == 'POST':\n json_data = request.body\n stream = io.BytesIO(json_data)\n pythondata = JSONParser().parse(stream)\n serializer = ... | [
1,
2,
3,
4,
5
] |
from django.contrib import admin
# Register your models here.
from .models import Participant
class ParticipantAdmin(admin.ModelAdmin):
fieldsets = [
("Personal information", {'fields': ['email', 'name', 'institution', 'assistant']}),
("Asistance", {'fields': ['assistant', 'participant_hash']}),
... | normal | {
"blob_id": "c43b899234ffff09225153dcaf097591c7176430",
"index": 841,
"step-1": "<mask token>\n\n\nclass ParticipantAdmin(admin.ModelAdmin):\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass ParticipantAdmin(admin.ModelAdmin):\n fieldsets = [('Per... | [
1,
2,
3,
4,
5
] |
from backend.personal.models import User, UserState
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from backend.personal.views import produceRetCode, authenticated
from backend.utils.fetch.fetch import fetch_curriculum
from backend.univinfo.... | normal | {
"blob_id": "a33ddb999f7bb50688b33946046ba460cbbbd172",
"index": 9181,
"step-1": "<mask token>\n\n\n@api_view(['POST'])\n@authenticated\ndef fetchCurriculum(request):\n university = request.DATA['user'].university.shortname\n if university == 'Unknown':\n ret = produceRetCode('fail', 'university not... | [
4,
6,
7,
8,
10
] |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | normal | {
"blob_id": "0719448e7eb8d48e636be1332c904beebf27e02d",
"index": 4163,
"step-1": "<mask token>\n\n\nclass PredictionQueryToken(Model):\n <mask token>\n <mask token>\n\n def __init__(self, session=None, continuation=None, max_count=None,\n order_by=None, tags=None, iteration_id=None, start_time=No... | [
2,
3,
4,
5,
6
] |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
sum = 0
def sumNumbers(self, root):
def dfs(root,sofar):
... | normal | {
"blob_id": "e6ac742eb74d5d18e4c304a8ea1331e7e16e403d",
"index": 2317,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n",
"step-3": "class Solution:\n <mask token>\n\n def sumNumbers(self, root):\n\n def dfs(root, sofar):\n if root.left is N... | [
0,
1,
2,
3,
4
] |
'''
Created on 17 june, 2018
@author: sp977u@att.com (Satish Palnati)
This class is for
'''
import sys
from PySide.QtGui import *
from PySide.QtCore import *
from PySide import QtGui
from PySide import QtCore
class PingWindow:
wind_close_flg = False
def __init__(self,last_parent):
... | normal | {
"blob_id": "75b1d2fb927063669a962f72deb57323001c0b7a",
"index": 5657,
"step-1": "<mask token>\n\n\nclass PingWindow:\n <mask token>\n\n def __init__(self, last_parent):\n self.last_parent = last_parent\n self.main_widget = QWidget()\n self.main_widget.setMaximumHeight(400)\n se... | [
3,
4,
5,
6,
7
] |
#usage: exploit.py
print "-----------------------------------------------------------------------"
print ' [PoC 2] MS Visual Basic Enterprise Ed. 6 SP6 ".dsr" File Handling BoF\n'
print " author: shinnai"
print " mail: shinnai[at]autistici[dot]org"
print " site: http://shinnai.altervista.org\n"
print " Once you create... | normal | {
"blob_id": "40a73ceeeb310c490fe2467511966679a1afa92b",
"index": 9585,
"step-1": "#usage: exploit.py\n\nprint \"-----------------------------------------------------------------------\"\nprint ' [PoC 2] MS Visual Basic Enterprise Ed. 6 SP6 \".dsr\" File Handling BoF\\n'\nprint \" author: shinnai\"\nprint \" mail... | [
0
] |
#!/usr/bin/python
# This script deletes and recreates the NIC BoD intents.
# Use nic-bod-setup.py to set up the physical network and NEMO nodes first
import requests,json
import argparse, sys
from requests.auth import HTTPBasicAuth
USERNAME='admin'
PASSWORD='admin'
NIC_INTENTS="http://%s:8181/restconf/config/intent... | normal | {
"blob_id": "955017ad7cc9dde744b8d8a9439f63f4725d50bc",
"index": 1673,
"step-1": "#!/usr/bin/python\n\n# This script deletes and recreates the NIC BoD intents.\n# Use nic-bod-setup.py to set up the physical network and NEMO nodes first\n\nimport requests,json\nimport argparse, sys\nfrom requests.auth import HTTP... | [
0
] |
class Solution:
def longestConsecutive(self, nums) -> int:
s = set(nums)
answer = 0
# n = len(s)
for value in s:
if value - 1 not in s:
j = value
while (j in s):
j = j + 1
answer = max(answer, j - val... | normal | {
"blob_id": "9cb5573fada7a1529507da1d031f836044c10066",
"index": 2474,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def longestConsecutive(self, nums) ->int:\n s = set(nums)\n answer = 0\n for value in s:\n if v... | [
0,
1,
2,
3
] |
import torch, torchvision
import torch.nn.functional as F
import transformers
from transformers import BertTokenizer, BertModel
from transformers.models.bert.modeling_bert import BertPreTrainingHeads
from utils import construct_bert_input, EvaluationDataset, save_json
from fashionbert_evaluator_parser import Evaluation... | normal | {
"blob_id": "7a01bffa5d7f0d5ecff57c97478f2cf5e9a27538",
"index": 1210,
"step-1": "<mask token>\n\n\nclass FashionbertEvaluator(transformers.BertPreTrainedModel):\n\n def __init__(self, config):\n super().__init__(config)\n self.bert = BertModel(config)\n self.im_to_embedding = torch.nn.Li... | [
8,
10,
12,
13,
14
] |
from rest_framework import serializers
from .models import Twit, Comment, Message
from django.contrib.auth.models import User
class TwitSerializer(serializers.ModelSerializer):
class Meta:
model = Twit
fields = '__all__'
class CommentSerializer(serializers.ModelSerializer):
class Meta:
... | normal | {
"blob_id": "536a67935527eb99bc0424613c9b931401db0b06",
"index": 6461,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = Comment\n fields = '__all__'\n\n\nclass MessageSerializer(serializers.ModelSerialize... | [
0,
2,
3,
4,
5
] |
test_case = int(input())
while test_case != 0:
test_case -= 1
(n, m) = map(int, input().split())
ans = n * m
A = []
for i in range(n):
t = list(map(int, input().split()))
A.append(t)
for i in range(1, n - 1):
for j in range(1, m - 1):
k = 1
while ... | normal | {
"blob_id": "dbc3e51fed63fe0fadea67d05c4b4efc693938a3",
"index": 1487,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile test_case != 0:\n test_case -= 1\n n, m = map(int, input().split())\n ans = n * m\n A = []\n for i in range(n):\n t = list(map(int, input().split()))\n ... | [
0,
1,
2,
3
] |
#!/usr/bin/python
import sys
OPEN_BRACES = ['{', '(', '[']
CLOSE_BRACES = ['}', ')', ']']
def match_paranthesis (s, pos):
stack = []
for i,c in enumerate(s):
if not c in OPEN_BRACES and not c in CLOSE_BRACES:
continue
if c in OPEN_BRACES:
stack.append((i, c))
... | normal | {
"blob_id": "cc6cef70381bb08247720ec32b7e8fe79ed7123d",
"index": 1014,
"step-1": "#!/usr/bin/python\n\nimport sys\n\nOPEN_BRACES = ['{', '(', '[']\nCLOSE_BRACES = ['}', ')', ']']\n\ndef match_paranthesis (s, pos):\n stack = []\n\n for i,c in enumerate(s):\n if not c in OPEN_BRACES and not c in CLOSE... | [
0
] |
from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... | normal | {
"blob_id": "480787d7bc0e87df7c59c4deb402eea76643680c",
"index": 7529,
"step-1": "<mask token>\n\n\ndef createMatchFeed(request, teamwedstrijd=None):\n cal = EventFeed(teamwedstrijd)\n return cal.__call__(request)\n\n\n@login_required\ndef viewMatch(request, match):\n try:\n m = Match.objects.get... | [
6,
8,
9,
11,
13
] |
class WSCommand:
handshake_hi = 'handshake_hi'
ping = 'ping'
pong = 'pong'
http_call = 'http_call'
http_return = 'http_return'
class WSMessage:
def __init__(self, command: str, data: any=None) ->None:
self.command = command
self.data = data
def strData(self) ->str:
... | normal | {
"blob_id": "d4621ef378b89490278c09e569f781aef1fcef3f",
"index": 7013,
"step-1": "<mask token>\n\n\nclass WSMessage:\n\n def __init__(self, command: str, data: any=None) ->None:\n self.command = command\n self.data = data\n <mask token>\n\n def dictData(self) ->dict:\n return self.d... | [
3,
4,
5,
6
] |
"""
Name: Thomas Scola
lab1.py
Problem: This function calculates the area of a rectangle
"""
'''def calc_area():'''
def calc_rec_area():
length = eval(input("Enter the length: "))
width = eval(input("Enter the width: "))
area = length * width
print("Area =", area)
def calc_rec_vol():... | normal | {
"blob_id": "076e10b3741542b7137f6ac517dba482f545b123",
"index": 2154,
"step-1": "<mask token>\n\n\ndef calc_rec_area():\n length = eval(input('Enter the length: '))\n width = eval(input('Enter the width: '))\n area = length * width\n print('Area =', area)\n\n\ndef calc_rec_vol():\n lengthh = eval... | [
2,
3,
4,
5,
6
] |
import xlrd
def get_rosters_from_excel(django_file):
workbook = xlrd.open_workbook(file_contents=django_file.read())
worksheet = workbook.sheet_by_name('Match_Rosters')
num_rows = worksheet.nrows - 1
cur_row = -1
rosters = []
while cur_row < num_rows:
cur_row += 1
if workshe... | normal | {
"blob_id": "a7a219e9ea5cdec004ef936958994ed1f5a96103",
"index": 3244,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_rosters_from_excel(django_file):\n workbook = xlrd.open_workbook(file_contents=django_file.read())\n worksheet = workbook.sheet_by_name('Match_Rosters')\n num_rows = ... | [
0,
1,
2,
3
] |
from colorama import init, Fore, Style
import tempConv
#============================================================================#
# TEMP CONVERSION PROGRAM: #
#============================================================================#
#------------------------... | normal | {
"blob_id": "235bb1b9d4c41c12d7667a6bac48737464c685c7",
"index": 568,
"step-1": "<mask token>\n\n\ndef menu(x):\n \"\"\" Takes a list as argument and displays as a menu \"\"\"\n for i in range(len(x)):\n print('{0:>4s} {1:<3s}{2:^5s}{3:<15}'.format(str(i + 1) + ')', x[i]\n [1], '-->', x[i... | [
3,
5,
7,
10,
11
] |
class Solution(object):
def oddCells(self, m, n, indices):
"""
:type m: int
:type n: int
:type indices: List[List[int]]
:rtype: int
"""
indice_x_dict = {}
indice_y_dict = {}
for x, y in indices:
indice_x_dict[x] = indice_x_dict.get... | normal | {
"blob_id": "148b849ae43617dde8dbb0c949defa2f390ce5cd",
"index": 9902,
"step-1": "<mask token>\n",
"step-2": "class Solution(object):\n <mask token>\n",
"step-3": "class Solution(object):\n\n def oddCells(self, m, n, indices):\n \"\"\"\n :type m: int\n :type n: int\n :type i... | [
0,
1,
2
] |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views.generic import CreateView, UpdateView, ListView, \
DeleteView, TemplateView
from example.forms import EditorTextForm
from example.models import EdidorText
class AjaxableResponseMixin:
"""
Mixi... | normal | {
"blob_id": "87a4fcb26464925952dde57fecf4709f01e9fed7",
"index": 9916,
"step-1": "<mask token>\n\n\nclass AjaxableResponseMixin:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):\n form_class = EditorTextForm\n model = Ed... | [
7,
8,
9,
10,
12
] |
import turtle
import random
shaan = turtle.Turtle()
#shaan.color(50,50,50)
#shaan.begin_fill()
for i in range (2):
shaan.forward(200)
shaan.right(90)
shaan.forward(250)
shaan.right(90)
shaan.left(60)
for i in range(4):
shaan.forward(200)
shaan.right(120)
shaan.forward(100)
shaan.left(150)
shaan.forward(100)... | normal | {
"blob_id": "6f13ebe7355d530ba3403aab54b313ecf35b1261",
"index": 4523,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(2):\n shaan.forward(200)\n shaan.right(90)\n shaan.forward(250)\n shaan.right(90)\nshaan.left(60)\nfor i in range(4):\n shaan.forward(200)\n shaan.right(1... | [
0,
1,
2,
3,
4
] |
from flask import render_template, request, redirect, url_for, send_file
from flask_app import app
import re
import os
from werkzeug.utils import secure_filename
import numpy as np
import cv2 as cv
from flask_mail import Message, Mail
file_path_file = open('flask_app/file_path.txt', 'r')
vars = file_path_file.readline... | normal | {
"blob_id": "e30aaf1616a107662924da3671b179a1887974f7",
"index": 2404,
"step-1": "<mask token>\n\n\ndef get_req_var(var):\n result = 0\n for s in vars:\n s = re.search('((?<=' + var + '>).+)', s)\n if s:\n result = s[0]\n break\n return result\n\n\n<mask token>\n\n\n@... | [
7,
8,
10,
11,
12
] |
#! /home/joreyna/anaconda2/envs/hla/bin/python
import argparse
import os
import sys
import time
import numpy as np
import copy
import subprocess
import math
project_dir = os.path.join(sys.argv[0], '../../')
project_dir = os.path.abspath(project_dir)
output_dir = os.path.join(project_dir, 'output/', 'pipeline/', 'sa... | normal | {
"blob_id": "d3f80deb72ca2bd91fc09b49ad644f54d339f962",
"index": 5819,
"step-1": "<mask token>\n\n\ndef generate_mutation(base):\n \"\"\"\n\tTaking into account the current base, base, return a mutation.\n\t\n\t\"\"\"\n if base in ['A', 'C', 'G', 'T']:\n bases = ['A', 'C', 'G', 'T']\n bases.r... | [
5,
6,
7,
9,
10
] |
import random
def get_ticket():
ticket = ''
s = 'abcdefghijkrmnopqrstuvwxyz1234567890'
for i in range(28):
r_num = random.choice(s)
ticket += r_num
return ticket
| normal | {
"blob_id": "d2a9a2fd3a1118c0855b8f77ce4c25cc6b4e8f87",
"index": 4328,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_ticket():\n ticket = ''\n s = 'abcdefghijkrmnopqrstuvwxyz1234567890'\n for i in range(28):\n r_num = random.choice(s)\n ticket += r_num\n return tick... | [
0,
1,
2
] |
from typing import Tuple, List
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.constraints = []
def __str__(self):
return f"({self.x}, {self.y})"
class Line:
def __init__(self, point1, point2):
if isinstance(point1, Point):
... | normal | {
"blob_id": "e59a51641dc2966b0170678de064e2845e170cf5",
"index": 4943,
"step-1": "<mask token>\n\n\nclass Line:\n\n def __init__(self, point1, point2):\n if isinstance(point1, Point):\n self.p1 = point1\n elif isinstance(point1, (Tuple, List)):\n self.p1 = Point(*point1)\n ... | [
11,
12,
15,
17,
18
] |
import sys
import os
PROJ_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(PROJ_DIR)
| normal | {
"blob_id": "54276074d84e63e6418f8738bb7f910424f1c94d",
"index": 9469,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append(PROJ_DIR)\n",
"step-3": "<mask token>\nPROJ_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(PROJ_DIR)\n",
"step-4": "import sys\nimport os\nPROJ_DIR ... | [
0,
1,
2,
3
] |
# 938. Range Sum of BST
# Share
# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
# The binary search tree is guaranteed to have unique values.
# Example 1:
# Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
# Output: 32
# Example 2:
... | normal | {
"blob_id": "8e1de62f2490d2276a834ae1ab0f1958649fa821",
"index": 5503,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n",
"step-3": "class Solution:\n <mask token>\n\n def cal_sum(self, root, L, R, result):\n if not root:\n return result\n ... | [
0,
1,
2,
3,
4
] |
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
from datetime import datetime, timedelta
class DeadlineMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
re... | normal | {
"blob_id": "0d3e1df1720812e8546b1f3509c83d1e6566e103",
"index": 4639,
"step-1": "<mask token>\n\n\nclass DeadlineMiddleware:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass DeadlineMiddleware:\n\n def __init__(self, get_response):\n self.get_response = ge... | [
1,
3,
4,
5,
6
] |
# Neural network model(s) for the pygym 'CartPoleEnv'
#
# author: John Welsh
import torch.nn as nn
import torch.nn.functional as F
class CartPoleModel(nn.Module):
def __init__(self):
super(CartPoleModel, self).__init__()
self.fc1 = nn.Linear(4, 60)
self.fc2 = nn.Linear(60, 120)
s... | normal | {
"blob_id": "bde3975f5b614a4b00ad392d9f0b4c1bd8c55dc0",
"index": 6855,
"step-1": "<mask token>\n\n\nclass CartPoleModel(nn.Module):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CartPoleModel(nn.Module):\n\n def __init__(self):\n super(CartPoleModel, self).__init__()\n ... | [
1,
2,
3,
4,
5
] |
import collections
import cPickle as pickle
import os
import shutil
import warnings
import numpy as np
import theano
import theano.tensor as T
import tables
#theano.config.compute_test_value = 'warn'
class SGD_Trainer(object):
"""Implementation of a stochastic gradient descent trainer
"""
#{{{ Properties
... | normal | {
"blob_id": "17ac827d181650cd8bd6e75ca7ff363d70d3c4a7",
"index": 2138,
"step-1": "import collections\nimport cPickle as pickle\nimport os\nimport shutil\nimport warnings\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport tables\n#theano.config.compute_test_value = 'warn'\n\n\nclass SGD_Train... | [
0
] |
from nose.tools import with_setup, nottest
from tests.par_test_base import ParTestBase
from ProbPy import RandVar, Factor, ParFactor
class TestFactorMult(ParTestBase):
def __init__(self):
super().__init__()
def par_test_0(self):
"""
f(X), scalar
"""
for i in range(4)... | normal | {
"blob_id": "0aad96de65cc125e5c026dfd72a9cc9f4ebd3dd2",
"index": 6486,
"step-1": "<mask token>\n\n\nclass TestFactorMult(ParTestBase):\n\n def __init__(self):\n super().__init__()\n <mask token>\n\n def par_test_1(self):\n \"\"\"\n f(X, Y), scalar\n \"\"\"\n for i in r... | [
12,
14,
15,
16,
19
] |
import requests as r
from .security import Security, Securities
from .data import Data
url_base = 'https://www.alphavantage.co/query'
def _build_url(**kargs):
query = {
'function': 'TIME_SERIES_DAILY',
'symbol': 'SPY',
'outputsize': 'full',
'datatype': 'json',
'apikey': 'JPIO2GNGBMFRLGMN'
}
query.update(kar... | normal | {
"blob_id": "e99d3ae82d8eea38d29d6c4f09fdb3858e36ca50",
"index": 6518,
"step-1": "<mask token>\n\n\ndef _build_url(**kargs):\n query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize':\n 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'}\n query.update(kargs)\n query_str = '... | [
3,
4,
5,
6,
7
] |
__author__ = 'jacek gruzewski'
#!/user/bin/python3.4
"""
To do: throw exceptions rather than calling sys.exit(1)
"""
############################################################
# IMPORTS
############################################################
# Python's libraries
import time
import sys
import logging
imp... | normal | {
"blob_id": "dc928da92dc7e8a37a7f32dd4a579fd09b89eb01",
"index": 4955,
"step-1": "<mask token>\n\n\ndef swap_dns(live_alias, future_value, alias_dns_name, zone, records):\n \"\"\"\n :description: Changes alias (blue.<domain> or green.<domain>) that is behind live url.\n :param\n live_alias: Your ... | [
1,
10,
14,
15,
23
] |
from recipes.almahelpers import fixsyscaltimes # SACM/JAO - Fixes
__rethrow_casa_exceptions = True
context = h_init()
context.set_state('ProjectSummary', 'proposal_code', '2017.1.01355.L')
context.set_state('ProjectSummary', 'piname', 'unknown')
context.set_state('ProjectSummary', 'proposal_title', 'unknown')
context.s... | normal | {
"blob_id": "290811317ddb49a7d2a9f44ab7e0b6d201db12e1",
"index": 7532,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncontext.set_state('ProjectSummary', 'proposal_code', '2017.1.01355.L')\ncontext.set_state('ProjectSummary', 'piname', 'unknown')\ncontext.set_state('ProjectSummary', 'proposal_title', 'un... | [
0,
1,
2,
3,
4
] |
# Create your views here.
# -*- coding: utf-8 -*-
from json import dumps
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.conf import settings
from utils import Utils, MERCS, ENTITY, PARTS, ARMY, D... | normal | {
"blob_id": "b1c8aceab44574d0f53d30969861be028c920ef2",
"index": 5007,
"step-1": "# Create your views here.\n# -*- coding: utf-8 -*-\n\nfrom json import dumps\nfrom django.shortcuts import render_to_response\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.template import Request... | [
0
] |
filename = 'learning_python.txt'
# with open(filename) as file_object:
# contents = file_object.read()
# print(contents)
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
c_string = ''
for line in lines:
... | normal | {
"blob_id": "2f0dc8697e979f307c86a08832b0eae86357d416",
"index": 2497,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(filename) as file_object:\n lines = file_object.readlines()\n<mask token>\nfor line in lines:\n c_string += line.rstrip()\nprint(f\"{c_string.replace('Python', 'Scala')}\"... | [
0,
1,
2,
3
] |
from os import listdir
from os.path import isfile, join
import sys
cat_list = dict();
def onImport():
mypath = "../../data/roget_processed";
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))];
for f_name in onlyfiles:
f_temp = open(mypath + "/" + f_name);
f_lines = f_temp.readlines();
for l... | normal | {
"blob_id": "b1b9840fabc96c901e5ed45e22ee63af2f3550cb",
"index": 8643,
"step-1": "<mask token>\n\n\ndef onImport():\n mypath = '../../data/roget_processed'\n onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n for f_name in onlyfiles:\n f_temp = open(mypath + '/' + f_name)\n ... | [
2,
3,
4,
5,
6
] |
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
count = 0
inputLength = len(nums)
for i in range (0, inputLength):
for j in range (i, inputLength - 1):
if (nums[i] == nums[j + 1]): count += 1
return count | normal | {
"blob_id": "d7570bbea1e8c7674d507f8e86ce04d22058b21b",
"index": 7595,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def numIdenticalPairs(self, nums: List[int]) ->int:\n count = 0\n inputLength = len(nums)\n for i in range... | [
0,
1,
2,
3
] |
#!/usr/bin/python
# Classification (U)
"""Program: elasticsearchrepo_create_repo.py
Description: Unit testing of create_repo in
elastic_class.ElasticSearchRepo class.
Usage:
test/unit/elastic_class/elasticsearchrepo_create_repo.py
Arguments:
"""
# Libraries and Global Variables
# St... | normal | {
"blob_id": "5c01b83634b7ae9bc691341d7432a4e59617444c",
"index": 5182,
"step-1": "<mask token>\n\n\nclass Elasticsearch(object):\n <mask token>\n <mask token>\n\n\nclass UnitTest(unittest.TestCase):\n \"\"\"Class: UnitTest\n\n Description: Class which is a representation of a unit testing.\n\n M... | [
10,
12,
13,
14,
16
] |
import pygame
from math import sqrt, sin, cos
from numpy import arctan
from os import path
# try these colors or create your own!
# each valid color is 3-tuple with values in range [0, 255]
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
WHITEGRAY = (192, 192, 192)
RED = (255, 0, 0)
MIDRED = (192, 0, 0)
DARKRED = (128, 0, 0... | normal | {
"blob_id": "838279b4f8d9e656c2f90ff06eaff3bd9c12bbef",
"index": 3265,
"step-1": "<mask token>\n\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1]\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * cur... | [
1,
2,
3,
4,
5
] |
from torch import nn
from abc import ABCMeta, abstractmethod
class BaseEncoder(nn.Module):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError(
"Unrecognized options: {}".format(', '.join(kwargs.keys())))
super(BaseEncoder, s... | normal | {
"blob_id": "86ee2300b5270df3dadb22f2cfea626e6556e5db",
"index": 9951,
"step-1": "<mask token>\n\n\nclass BaseEncoder(nn.Module):\n <mask token>\n\n def __init__(self, **kwargs):\n if len(kwargs) > 0:\n raise RuntimeError('Unrecognized options: {}'.format(', '.join(\n kwarg... | [
3,
4,
5,
6,
7
] |
from msl.equipment.connection import Connection
from msl.equipment.connection_demo import ConnectionDemo
from msl.equipment.record_types import EquipmentRecord
from msl.equipment.resources.picotech.picoscope.picoscope import PicoScope
from msl.equipment.resources.picotech.picoscope.channel import PicoScopeChannel
cla... | normal | {
"blob_id": "82c3419679a93c7640eae48b543aca75f5ff086d",
"index": 4880,
"step-1": "<mask token>\n\n\nclass MyConnection(Connection):\n <mask token>\n\n def get_none1(self):\n \"\"\"No return type is specified.\"\"\"\n pass\n <mask token>\n <mask token>\n <mask token>\n <mask token>... | [
19,
20,
21,
37,
39
] |
# Square-Root of Trinomials
import math
print("Έχουμε ένα τριώνυμο ax²+bx+c. Δώστε μία θετική ή αρνητική τιμή σε κάθε σταθερά!")
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
D= b**2-4*a*c
print("Η Διακρίνουσα ειναι: " + str(D))
if D>0:
x1=(-b+math.sqrt(D))/(2*a)
print("Η πρώτη ρίζα ειναι: " + s... | normal | {
"blob_id": "b80deec4d3d3ab4568f37cc59e098f1d4af5504c",
"index": 6503,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\n 'Έχουμε ένα τριώνυμο ax²+bx+c. Δώστε μία θετική ή αρνητική τιμή σε κάθε σταθερά!'\n )\n<mask token>\nprint('Η Διακρίνουσα ειναι: ' + str(D))\nif D > 0:\n x1 = (-b + math... | [
0,
1,
2,
3,
4
] |
import numpy as np
import ipywidgets as widgets
from ipywidgets import interact, interactive, fixed, Layout, VBox, HBox
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.tri as tri
import matplotlib.colors as colors
from matplotlib.colors import LinearSegmentedColormap
import scipy.stats as sps... | normal | {
"blob_id": "e5a4ae2ec0fab1ca8cdce229c69725ece2dcc476",
"index": 8272,
"step-1": "<mask token>\n\n\ndef forc(X):\n Xi = X['Xi']\n Yi = X['Yi']\n Zi = X['Zi']\n SEi = X['SEi']\n Pi = X['Pi']\n Hc1 = X['Hc1']\n Hc2 = X['Hc2']\n Hb1 = X['Hb1']\n Hb2 = X['Hb2']\n style = {'description_w... | [
6,
7,
8,
9,
10
] |
from keras.preprocessing.text import text_to_word_sequence
from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding
from keras.layers.recurrent import LSTM
from keras.optimizers import Adam, RMSprop
#from nltk import FreqDist
import numpy as np
... | normal | {
"blob_id": "2962ef1d7ecd4e8d472b9dc36664e4e8745391fd",
"index": 3616,
"step-1": "<mask token>\n\n\ndef load_data(train_source, train_dist, test_source, test_dist, max_len,\n vocab_size):\n \"\"\"\n fin = open(test_source, \"r\")\n data2 = fin.read()\n fin.close()\n fout = open(train_source, \"... | [
3,
4,
5,
6,
7
] |
# Stubs for docutils.parsers.rst.directives.tables (Python 3.6)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
import csv
from docutils.statemachine import StringList
from docutils.nodes import Node, system_message, table, title
from docutils.parsers.rst import Directive
from typing impo... | normal | {
"blob_id": "9abf2b9b90d18332ede94cf1af778e0dda54330b",
"index": 949,
"step-1": "<mask token>\n\n\nclass RSTTable(Table):\n\n def run(self) ->List[Node]:\n ...\n\n\nclass CSVTable(Table):\n option_spec: Dict[str, Callable[[str], Any]] = ...\n\n\n class DocutilsDialect(csv.Dialect):\n delim... | [
11,
19,
20,
22,
24
] |
import ctypes
import win32con
import request_spider
from selenium_tickets_spider import *
from threading import Thread
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import sys, time, re
import datetime
SESSION_DATA = False
SHOW_S_P = False
class Wor... | normal | {
"blob_id": "bc0846397a5ad73b1c4b85e12864b27ef4fd08d7",
"index": 5358,
"step-1": "<mask token>\n\n\nclass Ui_MainWindow(QMainWindow):\n threads = []\n keywordJudge = ''\n\n def __init__(self):\n super(Ui_MainWindow, self).__init__()\n self.buy_succeed_count = 0\n for func in [self.o... | [
25,
26,
30,
32,
33
] |
#Q7. Write a program to calculate the sum of digits of a given number.
n=int(input("Enter a number:\n"))
sum=0
while(n>0):
r=n%10
sum=sum+r
n=n//10
print("The total sum of digits is:",sum)
| normal | {
"blob_id": "78e3750a1bbe9f2f6680937729c1a810bd29fd4d",
"index": 4232,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile n > 0:\n r = n % 10\n sum = sum + r\n n = n // 10\nprint('The total sum of digits is:', sum)\n",
"step-3": "n = int(input('Enter a number:\\n'))\nsum = 0\nwhile n > 0:\n ... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 31 16:55:33 2018
@author: GEAR
"""
'''
在OpenCV中有超过150中进行颜色转换的方法,但我们经常用到的一般只有两种:
BGR <-> Gray 和 BGR <-> HSV
我们需要用到的函数有:cv2.cvtColor(input_image, flag),其中flag是转换类型
对于BGR <-> Gray,我们用到的flag为cv2.COLOR_BGR2GRAY,但我们要注意在OpenCV
中HSV格式中H 色彩/亮度 的取值范围是[0 179], S 饱和度 和 V 亮度的取值范围是
[0... | normal | {
"blob_id": "ea3b8fe602357fa3d1de4daefce1e71a7de6e010",
"index": 2117,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(flags)\n",
"step-3": "<mask token>\nflags = [i for i in dir(cv2) if i.startswith('COLOR_')]\nprint(flags)\n",
"step-4": "<mask token>\nimport cv2\nflags = [i for i in dir(cv2) i... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | normal | {
"blob_id": "deb8ee1d6327a6406244147a819821e8d2b2890e",
"index": 1385,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.sw... | [
0,
1,
2,
3,
4
] |
import json
import unittest
from music_focus.workflows.weibo_online import WeiboOnline
class Test(unittest.TestCase):
def setUp(self):
pass
def test(self):
workflow_input = {'result_type': 'posts'}
wf = WeiboOnline()
r = wf.run(workflow_input)
print(json.dumps(r, ensu... | normal | {
"blob_id": "7088f7233b67dcb855482a76d304aacc1a26abad",
"index": 3790,
"step-1": "<mask token>\n\n\nclass Test(unittest.TestCase):\n <mask token>\n\n def test(self):\n workflow_input = {'result_type': 'posts'}\n wf = WeiboOnline()\n r = wf.run(workflow_input)\n print(json.dumps(... | [
3,
4,
5,
6
] |
class MiniMaxSearch(object):
def __init__(self):
self.count = 0
self.explored = set()
def max_value(self, state, a, b):
self.count += 1
value = float('-inf')
if state in self.explored:
return state.evaluate()
if state.terminal():
self.... | normal | {
"blob_id": "15c61dbf51d676b4c339dd4ef86a76696adfc998",
"index": 4707,
"step-1": "\n\nclass MiniMaxSearch(object):\n def __init__(self):\n self.count = 0\n self.explored = set()\n\n def max_value(self, state, a, b):\n self.count += 1\n value = float('-inf')\n\n if state i... | [
0
] |
import models
import json
import reports.models
import common.ot_utils
def analyze_raw_reports(clean=True):
if clean:
delete_all_reports()
COUNT = 100
offset = 0
while True:
cont = analyze_raw_reports_subset(offset,COUNT)
offset += COUNT
if not cont:
return
... | normal | {
"blob_id": "c3527363cfc29ab7d598fe232d784b05ec2ef069",
"index": 388,
"step-1": "import models\nimport json\nimport reports.models\nimport common.ot_utils\n\ndef analyze_raw_reports(clean=True):\n if clean:\n delete_all_reports()\n COUNT = 100\n offset = 0\n while True:\n cont = analyze... | [
0
] |
#!/usr/bin/python
import sys
f = open('/etc/passwd','r')
users_and_ids = []
for line in f:
u,_,id,_ = line.split(':',3)
users_and_ids.append((u,int(id)))
users_and_ids.sort(key = lambda pair:pair[1])
for id,usr in users_and_ids:
print id,usr
| normal | {
"blob_id": "52426ec670dd5ca522c7fb0b659e3a42b16ff326",
"index": 8851,
"step-1": "#!/usr/bin/python\nimport sys\nf = open('/etc/passwd','r')\nusers_and_ids = []\nfor line in f:\n u,_,id,_ = line.split(':',3)\n users_and_ids.append((u,int(id)))\nusers_and_ids.sort(key = lambda pair:pair[1])\nfor id,usr in users... | [
0
] |
import cv2
import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg
df = pandas.read_csv("show.csv")
d = {'UK': 0, 'USA': 1, 'N': 2}
df['Nationality'] = df['Nationality'].map(d)
d = {'YES': 1, 'NO': 0}
df['... | normal | {
"blob_id": "c9cf65eeec49eba004312491cdd2321200fa6a61",
"index": 469,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ngraph.write_png('mydecisiontree.png')\n<mask token>\nplt.show()\nprint(X)\nprint(y)\n",
"step-3": "<mask token>\ndf = pandas.read_csv('show.csv')\nd = {'UK': 0, 'USA': 1, 'N': 2}\ndf['Na... | [
0,
1,
2,
3,
4
] |
# Main Parameters
FONTS_PATH = "media/battle_font.ttf"
LEVELS_PATH = "media/levels"
GAME_MUSIC_PATH = "media/sounds/DOOM.ogg"
MENU_MUSIC_PATH = "media/sounds/ANewMorning.ogg"
# GAME Parameters
FONT_SIZE = 30
CELL_WIDTH = 13 * 2
CELL_HEIGHT = 13 * 2
CELL_SIZE = (CELL_WIDTH, CELL_HEIGHT)
FPS = 30
DISPLAY_WIDTH = CELL_WI... | normal | {
"blob_id": "513d7e3c34cc9da030e2e018ad2db6972cf440dc",
"index": 5100,
"step-1": "<mask token>\n",
"step-2": "FONTS_PATH = 'media/battle_font.ttf'\nLEVELS_PATH = 'media/levels'\nGAME_MUSIC_PATH = 'media/sounds/DOOM.ogg'\nMENU_MUSIC_PATH = 'media/sounds/ANewMorning.ogg'\nFONT_SIZE = 30\nCELL_WIDTH = 13 * 2\nCEL... | [
0,
1,
2
] |
import requests
import json, csv
import pandas as pd
API_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'
list_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']
fieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount', 'favoriteCount', 'commentCount']
rows = []
for video_id in list_video_... | normal | {
"blob_id": "3c341b17f260cc745c8659ee769493216522ac19",
"index": 2073,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor video_id in list_video_id:\n url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +\n '&part=statistics&key=' + API_KEY)\n response = requests.get(url).js... | [
0,
1,
2,
3,
4
] |
i = 0
while i < 10:
print("Hello", 2 * i + 5)
i = i + 1 | normal | {
"blob_id": "e22574b5c458c23c48915274656f95a375cdc0e6",
"index": 6181,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile i < 10:\n print('Hello', 2 * i + 5)\n<mask token>\n",
"step-3": "i = 0\nwhile i < 10:\n print('Hello', 2 * i + 5)\ni = i + 1\n",
"step-4": "\r\ni = 0\r\nwhile i < 10:\r\n ... | [
0,
1,
2,
3
] |
# -*- coding:utf-8 -*-
import math
r = float(input())
print("{0:f} {1:f}".format(r*r*math.pi,2*r*math.pi)) | normal | {
"blob_id": "e28cca2273e1c3ad4b8a955843e7dfb45c00694c",
"index": 3246,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('{0:f} {1:f}'.format(r * r * math.pi, 2 * r * math.pi))\n",
"step-3": "<mask token>\nr = float(input())\nprint('{0:f} {1:f}'.format(r * r * math.pi, 2 * r * math.pi))\n",
"step-... | [
0,
1,
2,
3,
4
] |
__author__ = 'simon.hughes'
from sklearn.feature_extraction import DictVectorizer
from WindowFeatures import compute_middle_index
from collections import Counter
class WindowFeatureExtractor(object):
"""
A simple wrapper class that takes a number of window based feature extractor
functions and applies the... | normal | {
"blob_id": "48677d73f6489ce789884a9dff5d50c23f47d8b3",
"index": 260,
"step-1": "<mask token>\n\n\nclass WindowFeatureExtractor(object):\n <mask token>\n <mask token>\n <mask token>\n\n def transform(self, X, y=None):\n return self.vectorizer.transform(X, y)\n <mask token>\n <mask token>... | [
2,
7,
8,
9,
10
] |
"""
SteinNS: BayesianLogisticRegression_KSD.py
Created on 10/9/18 6:25 PM
@author: Hanxi Sun
"""
import tensorflow as tf
import numpy as np
import scipy.io
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
########################################################################... | normal | {
"blob_id": "a0a9527268fb5f8ea24de700f7700b874fbf4a6b",
"index": 4838,
"step-1": "<mask token>\n\n\ndef S_q(theta, a0=1, b0=0.01):\n w = theta[:, :-1]\n s = tf.reshape(theta[:, -1], shape=[-1, 1])\n y_hat = 1.0 / (1.0 + tf.exp(-tf.matmul(Xs, tf.transpose(w))))\n y = tf.reshape((ys + 1.0) / 2.0, shape... | [
4,
5,
7,
8,
11
] |
"""
Use the same techniques such as (but not limited to):
1) Sockets
2) File I/O
3) raw_input()
from the OSINT HW to complete this assignment. Good luck!
"""
import socket
import re
import time
host = "cornerstoneairlines.co" # IP address here
port = 45 # Port here
def execute_cmd(cm... | normal | {
"blob_id": "e0f25addad8af4541f1404b76d4798d2223d9715",
"index": 5116,
"step-1": "<mask token>\n\n\ndef execute_cmd(cmd):\n \"\"\"\n Sockets: https://docs.python.org/2/library/socket.html\n How to use the socket s:\n\n # Establish socket connection\n s = socket.socket(socke... | [
1,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
"""
python3
description :Fingerprint image enhancement by using gabor
"""
import os
import cv2
import math
import scipy
import numpy as np
from scipy import signal
def normalise(img):
normed = (img - np.mean(img)) / (np.std(img))
return normed
def ridge_segment(im, blksze, thresh):
... | normal | {
"blob_id": "9447d0d0481df3d0ee4273256d02977bc8044e4e",
"index": 8603,
"step-1": "<mask token>\n\n\ndef ridge_orient(im, gradientsigma, blocksigma, orientsmoothsigma):\n sze = np.fix(6 * gradientsigma)\n if np.remainder(sze, 2) == 0:\n sze = sze + 1\n gauss = cv2.getGaussianKernel(np.int(sze), gr... | [
5,
7,
8,
9,
10
] |
from django.urls import path
from .views import MainView
app_name = "bio"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('get_mtx_data', MainView.as_view()),
]
| normal | {
"blob_id": "e3a984294cad5830358df50fa00111017cbe226d",
"index": 3678,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'bio'\nurlpatterns = [path('get_mtx_data', MainView.as_view())]\n",
"step-3": "from django.urls import path\nfrom .views import MainView\napp_name = 'bio'\nurlpatterns = [pat... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
# coding: utf-8
import logging
import config
def get_common_logger(name='common', logfile=None):
'''
args: name (str): logger name
logfile (str): log file, use stream handler (stdout) as default.
return:
logger obj
'''
my_logger = logging.getLogger(name)
... | normal | {
"blob_id": "1754bce54a47cb78dce3b545d3dce835a4e0e69f",
"index": 947,
"step-1": "<mask token>\n\n\ndef get_common_logger(name='common', logfile=None):\n \"\"\"\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n \"\... | [
1,
2,
3,
4,
5
] |
from django.http import HttpResponse
from polls.models import Pregunta
from django.template import loader
def index(request):
preguntas = Pregunta.objects.order_by('-fecha')[:5]
template = loader.get_template('polls/index.html')
context = { 'listado': preguntas,}
return HttpResponse(template.render(c... | normal | {
"blob_id": "07dc058ecef323ffd41299245e4fcafdc9e41506",
"index": 2131,
"step-1": "<mask token>\n\n\ndef resultados(request, total):\n latest_question_list = Pregunta.objects.order_by('fecha')[:total]\n output = ', '.join([q.descripcion for q in latest_question_list])\n return HttpResponse(output)\n\n\n<... | [
1,
2,
3,
4,
5
] |
''' tk_image_view_url_io.py
display an image from a URL using Tkinter, PIL and data_stream
tested with Python27 and Python33 by vegaseat 01mar2013
'''
import io
# allows for image formats other than gif
from PIL import Image, ImageTk
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except... | normal | {
"blob_id": "7764effac0b95ad8f62b91dd470c1d0e40704a7d",
"index": 9705,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n import Tkinter as tk\n from urllib2 import urlopen\nexcept ImportError:\n import tkinter as tk\n from urllib.request import urlopen\n<mask token>\nroot.title(sf)\n<mask... | [
0,
1,
2,
3,
4
] |
import pyenttec, math, time
global port
MAX = 60
panels = [408, 401, 404, 16]
def render():
port.render()
def setColor(panel, color):
if panels[panel]:
port.set_channel(panels[panel] - 1, color[0])
port.set_channel(panels[panel], color[1])
port.set_channel(panels[panel] + 1, color[2]... | normal | {
"blob_id": "55252fc78c67e48c64e777e4c3a713c898312b81",
"index": 7166,
"step-1": "<mask token>\n\n\ndef render():\n port.render()\n\n\ndef setColor(panel, color):\n if panels[panel]:\n port.set_channel(panels[panel] - 1, color[0])\n port.set_channel(panels[panel], color[1])\n port.set_... | [
3,
4,
5,
6
] |
from app.models.tables import Warehouse, Contractor, Articles
class ContractorTools(Contractor):
"""
Работа со справочником КА
"""
@staticmethod
def add_contractor(**kwargs):
ca = Contractor(**kwargs)
ca.insert()
@staticmethod
def delete_contractor(**kwargs):
ca =... | normal | {
"blob_id": "79c4a2d4503c2639950675b398e000aae367ff4a",
"index": 8117,
"step-1": "<mask token>\n\n\nclass ArticleTools(Articles):\n <mask token>\n\n @staticmethod\n def add_article(**kwargs):\n ca = Articles(**kwargs)\n ca.insert()\n\n @staticmethod\n def update_article(**kwargs):\n ... | [
12,
15,
19,
20,
21
] |
# 0=RED, 1=GREEN, 2=BLUE, 3=ALPHA
#import tkinter as tk
#import tkinter.ttk as ttk
#from tkcolorpicker import askcolor
import time
c1 = [0,0,0,0] #this color
c2 = [0,0,0] #over this color
c3 = [0,0,0] #result
cont='y'
#--------------------------------
while cont=='y':
print('--enter underlay co... | normal | {
"blob_id": "5fa8ae36c4b4a5bffa64f4c65b74b74b29ba246f",
"index": 4578,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile cont == 'y':\n print('--enter underlay color in r,g,b--')\n c2[0] = int(input('red: '))\n c2[1] = int(input('green: '))\n c2[2] = int(input('blue: '))\n print('')\n ... | [
0,
1,
2,
3,
4
] |
import signal
import time
import sdnotify
n = sdnotify.SystemdNotifier()
if __name__ == '__main__':
n.notify("READY=1")
time.sleep(2)
| normal | {
"blob_id": "78dc2193c05ddb4cd4c80b1c0322890eca7fcf19",
"index": 789,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n",
"step-3": "<mask token>\nn = sdnotify.SystemdNotifier()\nif __name__ == '__main__':\n n.notify('READY=1')\n ... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''
@author: tanglei
@contact: tanglei_0315@163.com
@file: index.py
@time: 2017/11/1 16:26
'''
#需求:
#1.每个客户端需要监控的服务不同
#2.每个服务的监控间隔不同
#3.允许模板的形式批量修改监控指标
#4.不同设备的监控阀值不同
#5.可自定义最近n分钟内hit\max\avg\last\... 指标超过阀值
#6.报警策略,报警等级,报警自动升级
#7.历史数据的存储和优化 时间越久数据越失真
#8.跨机房,跨区域代理服务器
#第三方的soc... | normal | {
"blob_id": "886101e5d86daf6c2ac0fe92b361ccca6132b1aa",
"index": 3030,
"step-1": "<mask token>\n",
"step-2": "#!/usr/bin/env python\n#_*_ coding:utf-8 _*_\n'''\n@author: tanglei\n@contact: tanglei_0315@163.com\n@file: index.py\n@time: 2017/11/1 16:26\n'''\n#需求:\n#1.每个客户端需要监控的服务不同\n#2.每个服务的监控间隔不同\n#3.允许模板的形式批量修... | [
0,
1
] |
#!/usr/bin/env python
# KMeans
# 参考 https://qiita.com/g-k/items/0d5d22a12a4507ecbf11
#
# データを適当なクラスタに分けた後、クラスタの平均を用いてうまい具合にデータがわかれるように調整させていくアルゴリズム
# 任意の指定のk個のクラスタを作成するアルゴリズムであることから、k-means法(k点平均法と呼ばれている)
# k-meansの初期値選択の弱点を解消したのが、k-means++
# k-means++では、中心点が互いに遠いところに配置されるような確率が高くなるように操作する。
# 教師なし学習のアルゴ... | normal | {
"blob_id": "10bf7959f178d3b5c0ce6e97253e665d32363af7",
"index": 6015,
"step-1": "<mask token>\n\n\ndef kmeansplus(X, K, n_iter):\n n = X.shape[0]\n idx = np.zeros(X.shape[0])\n distance = np.zeros(n * K).reshape(n, K)\n centers = np.zeros(X.shape[1] * K).reshape(K, -1)\n pr = np.repeat(1 / n, n)\... | [
1,
2,
3,
4,
5
] |
import cv2 as cv
def nothing(x):
pass
cv.namedWindow('Binary')
cv.createTrackbar('threshold', 'Binary', 0, 255, nothing)
cv.setTrackbarPos('threshold', 'Binary', 127)
img_color = cv.imread('../sample/ball.png', cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
while(True):
thre = cv.get... | normal | {
"blob_id": "034d4027ea98bca656178b66c5c6e6e8b13e4b9e",
"index": 4219,
"step-1": "<mask token>\n\n\ndef nothing(x):\n pass\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef nothing(x):\n pass\n\n\ncv.namedWindow('Binary')\ncv.createTrackbar('threshold', 'Binary', 0, 255, nothing)\ncv.setTrackbarPos(... | [
1,
2,
3,
4,
5
] |
#Интегрирование точного решения кинетик затухания люминесценции символьным методом
#Из за сложности получаемых уравнений. Последующий подбор коэффициентов методом МНК
# и печать результата
#
import sympy as sym
def del_flu_sym(x ,t = 1 ,Ka = 1, Ktt = 0.5):
intens = x**2
return intens
x = sym.Symbol('x')
t ... | normal | {
"blob_id": "903a431ac39734338b4d464629b4b04a87dc9e8e",
"index": 1776,
"step-1": "<mask token>\n\n\ndef del_flu_sym(x, t=1, Ka=1, Ktt=0.5):\n intens = x ** 2\n return intens\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef del_flu_sym(x, t=1, Ka=1, Ktt=0.5):\n intens = x ** 2\n return intens\... | [
1,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
import json
from django.conf import settings
from pdf_generator.utils import build_pdf_stream_from
from django.http import JsonResponse
from helpers.views import ApiView
from pdf_generator.forms import PdfTempStoreForm
from pdf_generator.serializers import PdfTempStoreSerializer
class Report... | normal | {
"blob_id": "789f95095346262a04e7de0f9f9c5df6177e8fbc",
"index": 5114,
"step-1": "<mask token>\n\n\nclass ReportPdfView(ApiView):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ReportPdfView(ApiView):\n <mask token>\n\n def post(self, request, *args, **kwargs):\n data =... | [
1,
2,
3,
4,
5
] |
class A():
def m(self):
print("Class A")
class B():
def m(self):
print("Class B")
class C(B, A):
print("class C")
obj1 = C()
obj1.m()
print(C.mro()) # Method Resolution Order based on convention of "OBJECT" super class
| normal | {
"blob_id": "3d59b8d6a34935ff332028443276f161430a981c",
"index": 9687,
"step-1": "<mask token>\n\n\nclass B:\n <mask token>\n\n\nclass C(B, A):\n print('class C')\n\n\n<mask token>\n",
"step-2": "class A:\n <mask token>\n\n\nclass B:\n\n def m(self):\n print('Class B')\n\n\nclass C(B, A):\n ... | [
2,
4,
6,
7,
8
] |
__author__ = 'jamjiang'
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'hi!, I am', self.name
david = Person('David')
david.sayHi()
Person('leo').sayHi()
| normal | {
"blob_id": "fcc12b26308e3031de7e8fcf4ad43ec92279d400",
"index": 5922,
"step-1": "__author__ = 'jamjiang'\nclass Person:\n def __init__(self, name):\n self.name = name\n def sayHi(self):\n print 'hi!, I am', self.name\n\ndavid = Person('David')\ndavid.sayHi()\n\nPerson('leo').sayHi()\n\n"... | [
0
] |
# Generated by Django 2.0.13 on 2019-05-23 14:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0001_initial'),
('users', '0003_user_projects'),
]
operations = [
migrations.RemoveField(
model_name='user'... | normal | {
"blob_id": "547935a67fb079e551534126534234ceb96ed0dd",
"index": 7648,
"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 = [('projects', ... | [
0,
1,
2,
3,
4
] |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return "Test!"
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal'... | normal | {
"blob_id": "cc094f8aeff3b52bd9184f7b815320529ecb4550",
"index": 9928,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef root():\n return 'Test!'\n\n\n@app.route('/federal/geographic')\ndef federal_geographic():\n pass\n\n\n<mask token>\n\n\n@app.route('/state/geographic')\ndef state_geographic():\n pas... | [
4,
6,
7,
8,
9
] |
{
"targets": [
{
"target_name": "force-layout",
"sources": [ "src/main.cc", "src/layout.cc", "src/quadTree.cc" ],
'conditions': [
['OS=="win"', {
'cflags': [
'/WX', "/std:latest", "/m"
],
}, { # OS != "win"
'cflags': [
... | normal | {
"blob_id": "0f916a1f638bf149f6992355cf8f33f74bc9bdb1",
"index": 8439,
"step-1": "<mask token>\n",
"step-2": "{'targets': [{'target_name': 'force-layout', 'sources': ['src/main.cc',\n 'src/layout.cc', 'src/quadTree.cc'], 'conditions': [['OS==\"win\"', {\n 'cflags': ['/WX', '/std:latest', '/m']}, {'cflags... | [
0,
1,
2
] |
"""
The MIT License (MIT)
Copyright (c) 2015 Tommy Carpenter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, mer... | normal | {
"blob_id": "da0076ab18531e5b8a1de909cb9178de6327d6b0",
"index": 3440,
"step-1": "<mask token>\n\n\ndef _filtering_parsing_helper(filter_cols_key, filter_vals_key,\n filter_invert_key):\n filter_vals = os.environ[filter_vals_key].split('|')\n inverts = [int(y) for y in os.environ[filter_invert_key].spli... | [
5,
6,
7,
8,
9
] |
#!/usr/bin/env python3
x = "Programming is like building a multilingual puzzle\n"
print (x)
| normal | {
"blob_id": "95c0ba757b7561ef6cc0ad312034e2695f8420c3",
"index": 3933,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(x)\n",
"step-3": "x = 'Programming is like building a multilingual puzzle\\n'\nprint(x)\n",
"step-4": "#!/usr/bin/env python3\n\nx = \"Programming is like building a multilingua... | [
0,
1,
2,
3
] |
from __future__ import division
import abc
import re
import numpy as np
class NGram(object):
SEP = ''
def __init__(self, n, text):
self.n = n
self.load_text(text)
self.load_ngram()
@abc.abstractmethod
def load_text(self, text):
pass
def load_ngram(self):
counts = self.empty_count()
... | normal | {
"blob_id": "41e3c18b02f9d80f987d09227da1fbc6bde0ed1d",
"index": 4812,
"step-1": "<mask token>\n\n\nclass NGram(object):\n <mask token>\n <mask token>\n\n @abc.abstractmethod\n def load_text(self, text):\n pass\n\n def load_ngram(self):\n counts = self.empty_count()\n c = self... | [
7,
9,
11,
13,
15
] |
#! /usr/bin/python
import Nodo,CLS,copy,sys
from excepcion import *
sys.setrecursionlimit(100000)
# Match
def match(nodo1,nodo2):
#print 'MATCH\n -',nodo1,'\n -',nodo2
# if isinstance(nodo1,Nodo.Nodo) and isinstance(nodo2,Nodo.Nodo):
# print ' -',nodo1.type,'\n -',nodo2.type
# Fin de recursion
if (not isinsta... | normal | {
"blob_id": "1178ad09638a4822461f7394e6cabb2db9516053",
"index": 9664,
"step-1": "#! /usr/bin/python\nimport Nodo,CLS,copy,sys\nfrom excepcion import *\nsys.setrecursionlimit(100000)\n# Match\ndef match(nodo1,nodo2):\n\t#print 'MATCH\\n -',nodo1,'\\n -',nodo2\n#\tif isinstance(nodo1,Nodo.Nodo) and isinstance(nod... | [
0
] |
def slope_distance(baseElev, elv2, dist_betwn_baseElev_elv2, projectedDistance):
# Calculate the slope and distance between two Cartesian points.
#
# Input:
# For 2-D graphs,
# dist_betwn_baseElev_elv2, Distance between two elevation points (FLOAT)
# baseElev, Elevation of first ... | normal | {
"blob_id": "65b30bbe737b331447235b5c640e9c3f7f6d6f8c",
"index": 5851,
"step-1": "<mask token>\n",
"step-2": "def slope_distance(baseElev, elv2, dist_betwn_baseElev_elv2, projectedDistance\n ):\n import math\n numer = elv2 - baseElev\n denom = dist_betwn_baseElev_elv2\n print(numer, denom)\n ... | [
0,
1,
2
] |
import bnn
#get
#!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
#!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
#unzip
#!gzip -d t10k-images-idx3-ubyte.gz
#!gzip -d t10k-labels-idx1-ubyte.gz
#read labels
print("Reading labels")
labels = []
with open("/home/xilinx/jupyter_notebooks/... | normal | {
"blob_id": "da34eb25ec08c8311fa839a0cdcd164eff036a5d",
"index": 942,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Reading labels')\n<mask token>\nwith open('/home/xilinx/jupyter_notebooks/bnn/t10k-labels-idx1-ubyte', 'rb'\n ) as lbl_file:\n magicNum = int.from_bytes(lbl_file.read(4), byte... | [
0,
1,
2,
3,
4
] |
from pymongo import MongoClient
class MongoDB():
def __init__(self, host, port, db, table):
self.host = host
self.port = port
self.client = MongoClient(host=self.host, port=self.port)
self.db = self.client[db]
self.table = self.db[table]
# 获取一条数据
def get_one(self, q... | normal | {
"blob_id": "b5f88a6d119f2c3ce8fb77cf8c45b6c9252f5128",
"index": 7619,
"step-1": "<mask token>\n\n\nclass MongoDB:\n <mask token>\n\n def get_one(self, query):\n return self.table.find_one(query, property={'_id': False})\n <mask token>\n\n def add(self, kv_dict):\n return self.table.ins... | [
5,
6,
7,
8,
9
] |
N = int(input("Max value N? "))
s = set()
for i in range(2, N + 1):
s.add(i)
for num in sorted(s):
k = num + num
while k <= N:
if k in s:
s.remove(k)
k += num
print("Primes:", end = " ")
for num in sorted(s):
print(num, end = " ")
| normal | {
"blob_id": "bf5422792533f85967a5573d9e6f370a7967a914",
"index": 120,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(2, N + 1):\n s.add(i)\nfor num in sorted(s):\n k = num + num\n while k <= N:\n if k in s:\n s.remove(k)\n k += num\nprint('Primes:', end=' ... | [
0,
1,
2,
3
] |
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :AutoMailApp -> handle_yaml
@IDE :PyCharm
@Author :Mr. wang
@Date :2019/11/15 0015 19:53
@Desc :
=================================================='''
import yaml
from Common.dir_path import YAML_FILE_PATH
class Han... | normal | {
"blob_id": "08c309645a4ee59716bdd00556096be1c784331a",
"index": 2469,
"step-1": "<mask token>\n\n\nclass HandleYaml:\n \"\"\"\n 处理并封装yaml文件\n \"\"\"\n\n def __init__(self):\n with open(YAML_FILE_PATH, 'r') as fs:\n content = fs.read()\n self.ya = yaml.load(content, yaml.... | [
4,
5,
6,
7,
8
] |
"""
Create a function that takes two number strings and returns their sum as a string.
Examples
add("111", "111") ➞ "222"
add("10", "80") ➞ "90"
add("", "20") ➞ "Invalid Operation"
Notes
If any input is "" or None, return "Invalid Operation".
"""
def add(n1, n2):
if n1 == "" or n2 == "":
return "Invali... | normal | {
"blob_id": "7bcbcbe51217b2ea9044a7e4a4bebf315069c92d",
"index": 2953,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef add(n1, n2):\n if n1 == '' or n2 == '':\n return 'Invalid Operation'\n elif n1 == None or n2 == None:\n return 'Invalid Operation'\n return str(int(n1) + in... | [
0,
1,
2,
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.