index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
998,000 | c6371a29a595b002e069d21647646721d4e1da47 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# bmconv.py - Read Delicious.com bookmark file and convert it into a list of dictionaries.
import re
bookmark_file = 'delicious.html'
def main():
"""Return a list of dictionaries of bookmarks."""
lines_list = []
with open(bookmark_file, 'r') as f:
line... |
998,001 | 9c6f8bf98f7721cf849b2770124347337af95eee | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-17 21:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('currencies', '0003_auto_20180417_2056'),
]
operations = [
migrations.Alter... |
998,002 | e6a3d20fe9445ae88f78af2a2f5be869b8bbd4ec | from __future__ import annotations
from miscutils import ReprMixin
from pathmagic import File
from subtypes import Dict
from .element import Comment, LexicalElement
from .section import DefinesSection
from .parser import DefinesParser
from .. import config
class DefinesDocument(ReprMixin):
def __init__(self, p... |
998,003 | f282555a204d3df4212166457a040b5da57c97cd | import pandas as pd
import requests
from bs4 import BeautifulSoup
import collections
import re
import os
from datetime import datetime
def getvineyards(parent_url):
page = requests.get(parent_url).text
soup = BeautifulSoup(page, "lxml")
# Get list of all the wineries
linkrefs = soup.findAll('li' , at... |
998,004 | 9dd5f548d98076ff74dbe70975dcfdf0cd48af7a | from .config import cfg
from .preprocess import TrainPreprocessor, Preprocessor
|
998,005 | 9960f654529057d91e33d1bf18c7a0398417a38b | from django_filters import FilterSet, CharFilter, ModelChoiceFilter, DateFromToRangeFilter
from .models import Product, Category, Comment
from django.contrib.auth.models import User
class ProductFilter(FilterSet):
class Meta:
model = Product
fields = {
'name': ['icontains'],
... |
998,006 | c92f20d08e71de0c970e65805fc0346e227861f8 | #!/usr/bin/env python
"""
Build FRB bits and pieces
"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
def parser(options=None):
import argparse
# Parse
parser = argparse.ArgumentParser(description='Build parts of the CASBAH database; Output_dir = $CASBAH_GALAXIES [v1.... |
998,007 | 322fe24e26bd2efdf0de75f152468b280ac822ff | # Code borrowed from:
# https://www.edureka.co/blog/web-scraping-with-python/
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from PIL import... |
998,008 | e711559599f1af5246144b0bca5bd637f44d1669 | # Taken from https://gist.github.com/st4lk/6287746
import logging
import logging.handlers
f = logging.Formatter(fmt='%(asctime)s %(levelname)s:%(name)s: %(message)s '
'(%(filename)s:%(lineno)d)',
datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.StreamHandler()
root_logger = lo... |
998,009 | a1a85d898410a934ad8a792fd15200bcd0def1e5 | import torch
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
from lnets.models.layers.conv.base_conv2d import BaseConv2D
from lnets.utils.math.projections import get_weight_signs, get_linf_projection_threshold
class LInfProjectedConv2D(BaseConv2D):
def __init__(self, in_channels, out_cha... |
998,010 | a0564ceb2fec6415056158c6af1b3ceff0ab2732 | """
TESTS is a dict with all you tests.
Keys for this will be categories' names.
Each test is dict with
"input" -- input data for user function
"answer" -- your right answer
"explanation" -- not necessary key, it's using for additional info in animation.
"""
TESTS = {
"0. Random X":
{
... |
998,011 | eb17ecf2990034f3674f2b0e2c9ea376ecda21c5 | #! /usr/bin/env python3
from rift import *
def fact(n):
if n < 0:
return 0
if n == 0:
return 1
return n * fact(n-1)
@Test
def test_fact_correct():
test_values = [0, 1, 7, 13, 20]
for i in test_values:
ret, stdout, stderr = rift.call(lib.fact, rift.c_longlong, i)
if ... |
998,012 | cd25075f712fef95d9ffdf5ae966b6369f63f0cd | #2
print('Hello' + __name__)
'''If you are running calc , this name will be main but if you are import calc
in other module then it will print thename of mudule'''
|
998,013 | 4107431fe7b859ae2c158ee286bde5b846092bde | """This module contains the general information for GlVnicTemplate ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class GlVnicTemplateConsts():
pass
class GlVnicTemplate(ManagedObject):
"""This is GlV... |
998,014 | c38652771c1da0d1036cac1edefa29bde859b6d9 |
from PIL import Image
import sys
import glob
files = glob.glob("img/1.jpg")
count = 0
for i in files:
im = Image.open(i)
pixdata = im.load()
count += 1
strCount = str(count)
for y in xrange(im.size[1]):
for x in xrange(im.size[0]):
if 185 < pixdata[x, y][0] or 185 < pixdata[... |
998,015 | f1cd4ce2d2a86e93fcb53b3bcd21c40e08917f18 | """
Usage:
scripts/oneoff/fix-agreement-extensions.py <stage> <api_token> <download_directory> [--dry-run]
"""
import sys
sys.path.insert(0, '.')
import os
import re
import magic
from docopt import docopt
from dmapiclient import DataAPIClient
from dmutils.s3 import S3
from dmscripts.env import get_api_endpoint_... |
998,016 | 5fac533690a2cded1f2a602d5ff9ee3a523841dd | # Generated by Django 3.2.4 on 2021-06-06 05:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("taxonomy", "__first__"),
]
operations = [
migrations.CreateModel(
name="Ani... |
998,017 | 7dc59bf4be8552144274d27722c9e7b29e0333c0 | import cv2 as cv
import numpy as np
# 轮廓发现:
'''
是基于图像边缘提取的基础寻找对象轮廓的方法。
所以边缘提取的阈值选定会影响最终轮廓发现结果
'''
# 对边缘操作
def contours_demo(image):
'''
dst = cv.GaussianBlur(image,(3,3),0)
gray = cv.cvtColor(dst,cv.COLOR_BGR2GRAY)
ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY | cv.THRESH_OTSU) #二值化
... |
998,018 | b270018e1a4caed3d772c239610e5a05c6988df9 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-10-06 04:21
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('seedsource', '0005_transferlimit_elevation'),
]
... |
998,019 | 4d75f78e5fed9ff711c6e8f0c554096cf0486ec1 | # A - Discount Fare
# https://atcoder.jp/contests/abc113/tasks/abc113_a
X, Y = map(int, input().split())
print(X + Y//2)
|
998,020 | 763c141ed67ef685a64700b7af6dfec38d14caae | from pyramid.httpexceptions import HTTPForbidden
from pyramid.threadlocal import get_current_request
from kindergarden.lib import helpers
from kindergarden.lib.i18n import ugettext as _
# from kindergarden.models import SYSTEM_SCHEMA, PUBLIC_SCHEMA, DBSession
def add_renderer_globals(event, request=None):
if req... |
998,021 | 5815ba7aed36396e1099ebbf631518431539f1a3 | from django.shortcuts import render
from django.http import HttpResponse
from .models import M1301,M1332,M1333,M1352,M1376,M1377
from .forms import HelloForm
def index(request):
# data = M1301.objects.all()
dekidaka_list = []
takane_list = []
owarine_list = []
company = {}
params = {
... |
998,022 | c011430fe1cb974a29bb90f860310b23bc6e2821 |
import pymongo
# connecting mongoDB Atlas and accessing database
client = pymongo.MongoClient("mongodb+srv://himanshu:Database%40123@cluster0-ktyqe.mongodb.net/test?retryWrites=true&w=majority")
mydb = client.University
# to add student in Students collection on mongoDB cloud
def add_student(name,age,roll_no... |
998,023 | 2d60f0b8592e7376aa7379adca3d1631a7eefb58 | import torch
from torch.utils.data import Dataset
class SideInformationDataset(Dataset):
def __init__(self, data, side_information, min_th, max_th):
self.data = data
self.side_information = side_information
self.min_th = min_th
self.max_th = max_th
def __len__(self):
r... |
998,024 | ad3881729f05f9471a5a8f2ca167e528a9f32929 | #This example is about how to read arguments on python
from sys import argv
script, first, second, third = argv
print("This script is called:", script);
print("First :",first);
print("Second :", second);
print("Third :", third);
|
998,025 | b44c2edf4536ffe05bd430d0732544a1203aee85 | import os.path
import sys
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
import json
class FileController:
key_path = "./keys/"
sym_key_path = '... |
998,026 | 29bcf7902d6b7fba8e492a5542734832276794f1 | a = [1,2,3,4,5]
b = [[3,1,2,1],[2,2],[3,3],[4,4],[5,5]]
def log_list(c, d):
for element in c:
print(element)
index = a.index(element)
print(type(b[index]))
def find_index_in_list(d):
for i in d:
print i
index_matched = i.index(1)
print index_matched
if __name... |
998,027 | 400030ce527eb27706e79f9a4f566a19e9b5754e | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-10 13:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',... |
998,028 | 98f793a10dc0b25f03f758d2ce0b438476790aae | import urllib, urllib2, json
from collections import defaultdict
from cards import Card
class DeckBrewError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class Request(object):
filter_types = {'status': str, 'set': str, 'name': str, 'format': ... |
998,029 | f6986b269707e593405ea6b2cb680cb944fff1c5 | # Generated by Django 3.2 on 2021-04-12 21:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0005_auto_20210412_2105'),
]
operations = [
migrations.AlterField(
model_name='calendarevent',
name='descrip... |
998,030 | 71565563e4f458e5afea86f6f5b515e430d5f7e3 | '''
Created on Jul 7, 2017
@author: Karim Hammouda
'''
#solution1 based on building alphabatical histogram (All letters) => O(n)
def anagram_solution1(s1,s2):
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(s1)):
pos = ord(s1[i]) - ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):... |
998,031 | 9bd8ee79a7aebd7b1f1dcd208fd8c8bb2e38327c | # -*- coding=utf-8 -*-
'''
@creatdate: 2016-12-19
@author: YuhuiXu
@description
'''
from Selenium2Library import Selenium2Library
class testlib(Selenium2Library):
"""Added By Yuhuixu"""
def if_page_contain_elemet(self, locator, loglevel='INFO'):
'''
Verifies that current page contains `locator... |
998,032 | 1438793e10aadd63a8c58e1579f6d62a2b05be1b | '''Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58 '''
altura = float(input('Digite a sua altura: '))
p_ideal = (72.7 * altura) - 58
print(f'O seu peso ideal é', p_ideal)
|
998,033 | 510e9c58e6350e285456c13c2390cbe48cde600f | from common import *
# 2-sides checkerboard
def draw(**kwargs):
imgsz=np.array([2*1024]*2)
def radial_warp(i,j):
cx,cy=imgsz/2
a,r=np.arctan2(i-cy,j-cx),np.sqrt((i-cy)**2+(j-cx)**2)
r=r*(1+0.1*np.sin(0.008*r))
a=a*6/4
return cx+np.cos(a)*r,cy+np.sin(a)*r
im=checkerb... |
998,034 | ba453d124d3965737edcc457f9d33169e6174463 | import math
x = int(input('podaj liczbe do sprawdzenia: '))
i = 2
y = True
if (x == 1 or math.sqrt(x)%1==0):
y = False
else:
while(x > i):
if (x % i == 0):
y = False
break
i += 1
print (y)
|
998,035 | 5f7c4fe0f4113606ea38ac162f56ea707f134614 | import csv
from random import randint
clues = []
with open('crossworddata.csv','r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
clues.append(row)
length = len(clues)
while True:
randNumber = randint(0,length)
randWord = clues[randNumber][1]
randAnswer = randWord.replace(" ", ""... |
998,036 | c2742273d7b9725ce14e202bbe78c7bd8f01df4a |
# Author Ilya Bilyi
import math
RESPONCE="\t Що виконати?\n*******************************\n 1 додавання \n 2 Віднімання \n 3 Ділення \n 4 множення \n 5 до степеня\n 6 сінус \n 7 косинус \n 8 аргсінус \n 9 аргкосинус \n*******************************\n "
print ('$$$ Вітаю це я калькулятор! $$$')
# loop while prec... |
998,037 | f88d44ec7f9c5479ed4050786747f3cebd9b339b | import unittest
from src.Display.IOTest import IOTest
from src.Display.ConsoleInputs import getVolume
from unittest.mock import MagicMock
class GetVolumeTest(unittest.TestCase):
def test_getValidVolume(self):
logger = IOTest()
logger.setInputList(["5"])
self.assertEqual(0.5, getVolume(log... |
998,038 | 4c2ec65ef3b2db292c2be961b22f29e767d10be7 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import django_filters
from .models import Article
class ArticleFilter(django_filters.rest_framework.FilterSet):
category = django_filters.rest_framework.BaseInFilter(field_name='category_id')
category_name = django_filters.rest_framework.CharFilter(method='catego... |
998,039 | 04def9989d2861045b364079f8d87ed09ead572b | class Details:
def __init__(self, F, L):
self.first = F
self.last = L
@property
def Name(self):
return self.first + ' ' + self.last
@Name.setter
def Name(self, N):
self.first = N[1:2]
self.last = N[3:]
R = Details('Ryan', 'Alderson')
Fullname = R.Name
prin... |
998,040 | 6d0bd5fcf0866efaea3aeeae54f2e23315edfc7c | import time
start = time.time()
def printElapsedTime(prefix=None):
print((prefix + ' ' if prefix else '') + str(time.time() - start))
|
998,041 | d2327e8c85dfca4b15e751253bafd4b8cbf6d69d | import json
import os
with open('data/error_funds.json', 'r') as fp:
error_fund = json.load(fp)
DATAPath = '/home/kuoluo/data/fund_data'
good_funds = []
for _file in os.listdir(DATAPath):
with open(DATAPath + '/' + _file, 'r') as fp:
json_data = json.load(fp)
if json_data[0]['fund_id'] not in ... |
998,042 | 6ab2481617c4b77c4b7056c87b2e80097c94ad02 | #!/usr/bin/python
import cgi, cgitb
import datetime
import os
import sys
#from datetime import *
cgitb.enable()
page='Content-type: text/html\n\n'
form=cgi.FieldStorage()
user = form["username"].value
project=form["projectname"].value
citationtype=form['style'].value
citationtype+=form['type'].value
f1=open(citation... |
998,043 | a55bc963a5253d76e7ef2b6d9dc13e0f2c023717 | import csv
import json
import datetime
source_base = "../data/ml-1m/"
print("Converting users...")
users = []
occupation_list = []
with open(source_base + "users.dat") as infile:
reader = csv.reader((line.replace("::", ";") for line in infile),
delimiter=";")
for row in reader:
... |
998,044 | 0cbba22cba7827052dbe959fba7d5814ff14ea3b | formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"hello, it's",
"me",
"can you",
"hear me?",
... |
998,045 | 4529a940f1630ba74a57f9e49c0b555b409f7814 | # Generated by Django 3.0.7 on 2020-08-16 20:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('movies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Bi... |
998,046 | 717d617544e0372b162cf3ac788d55bc5deaef14 | #!/usr/bin/env python3
import argparse
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import os
import smtplib
import requests
def send_mail(to, fro, subject, text, files=None, ser... |
998,047 | 833b7abb71a27e4d523d1fb3db3187d1f5fa7207 |
from marshmallow import Schema, fields
class EventSchema(Schema):
name = fields.Str()
title = fields.Str()
when = fields.Dict(
keys=fields.Str(),
values=fields.Str()
)
|
998,048 | 3727f358477024deca172df4fb7afbebcd3a1327 | a = int(input('请输入一个数字'))
if a>=1 and a<=10:
print('胜利')
else:
print('错误')
|
998,049 | b23afde1c94cc7a70b0414109a2a471dc7ff443f | import os
import requests
from redis import Redis
# Default configurations can be set with environment variables
REDIS_ADDRESS = os.environ.get('REDIS_ADDRESS', 'redis-service')
PROXY_ADDRESS_0 = os.environ.get('PROXY_ADDRESS_0',
'redis-proxy-cache-service-0')
PROXY_PORT_0 = os.enviro... |
998,050 | 41e9b1e8f88e0edbb231a23a2d6260b3dbfbe24f | #!/usr/bin/python3
from models.amenity import Amenity
from models.base_model import BaseModel
from models.city import City
from models.engine.file_storage import FileStorage
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User
all_classes = {"Ameni... |
998,051 | 48450c0609b7eec8be936625f34ff3cb9dcae486 | addon_id="script.icechannel.TheVideo.settings"
addon_name="iStream - TheVideo - Settings"
import xbmcaddon
addon = xbmcaddon.Addon(id=addon_id)
addon.openSettings()
|
998,052 | 190b5e110becd20f5115ccf3061b98d7d9f8d332 | # c = get_config()
# c.TerminalIPythonApp.display_banner = True
# c.InteractiveShell.autoindent = True
# c.InteractiveShell.deep_reload = True
# c.PromptManager.in_template = '>> '
# c.PromptManager.in2_template = ' .\D.: '
# c.PromptManager.out_template = ' '
# c.PromptManager.justify = True
# c.InteractiveShell... |
998,053 | 1b78cf6ca8e7426fc74d6b8ac0e3a3758110f022 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ''
# 65 -> A
while n:
n -= 1
result = chr(65 + n%26) + result
n /= 26
re... |
998,054 | 773a2fe9cae1a48689066d6fdf195a5b0ce97bd9 | pattern_zero=[0.0, 0.0475, 0.09, 0.1, 0.1275, 0.1475, 0.16, 0.1875, 0.19, 0.2, 0.21, 0.2275, 0.24, 0.2475, 0.25, 0.26, 0.2875, 0.29, 0.3, 0.31, 0.3275, 0.34, 0.3475, 0.35, 0.36, 0.3875, 0.39, 0.4, 0.41, 0.4275, 0.44, 0.4475, 0.45, 0.46, 0.4875, 0.49, 0.5, 0.51, 0.5275, 0.54, 0.5475, 0.55, 0.56, 0.5875, 0.59, 0.6, 0.61,... |
998,055 | 435f443ba8a0f25e0a64402da5df95f104dcadd7 | from django.contrib import admin
from .models import Company
from apps.client.models import Client
class ChoiceInline(admin.StackedInline):
model = Client
extra = 0
max_num = 10
class CompanyAdmin(admin.ModelAdmin):
fieldsets = (
('Customer Company', {
'fields': (
'... |
998,056 | c5ef5aaf45451a48980f2ae7f92bd0df35f136cd | # Generated by Django 3.1 on 2020-08-29 20:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0007_auto_20200829_2356'),
]
operations = [
migrations.AlterField(
model_name='director',
name='id',
... |
998,057 | f84c77b3375cd21cc505d1e8be20765a72605ad1 | from flask import Flask, request, send_from_directory, send_file
from flask_cors import CORS
import importlib
import json
app = Flask(__name__)
CORS(app)
# api path setup:
@app.route('/api/<resource>')
def call_api(resource):
res = importlib.import_module("api.{}".format(resource)).get(request)
return json.... |
998,058 | df5b19cb1353af4b1ea729fd1c2486c0d6b773de | n1=int(input("Digite a primeira nota: "))
n2=int(input("Digite a segunda nota: "))
m=(n1+n2)/2
if m>=9 and m<=10:
print("Ótimo")
elif m>=7 and m<=8.9:
print("Bom")
elif m>=6 and m<=6.9:
print("Suficiente")
elif m>=0 and m<=5.9:
print("Insuficiente")
|
998,059 | 511a28bee002e82ad0e3f70c4d6bdabb63c77256 | # Samuel #
cadena=[]
i='1'
while i!='':
i=input()
cadena.append(i)
print(cadena)
|
998,060 | a5b21b7e57c83376f71aa272bec4e2fb81dedf5e |
import glob
import os
from scripts.build_support import *
Import ('*')
files = glob.glob (env['rootdir'] + 'src/tools/logview/*.c')
envcopy = env.Copy ()
envcopy.ParseConfig ('pkg-config libglade-2.0 libxml-2.0 --cflags --libs')
file_list = strip_path_from_files (files)
add_include_path (envcopy['CPPPATH'], '#src/... |
998,061 | d6634e2bee5266cbacfdca2dc27a954c7d2e72df | # Numbers in decimal expansions
#
#Let p = p1 p2 p3 ... be an infinite sequence of random digits, selected from {0,1,2,3,4,5,6,7,8,9} with equal probability.
#It can be seen that p corresponds to the real number 0.p1 p2 p3 ....
#It can also be seen that choosing a random real number from the interval [0,1) is equival... |
998,062 | 8930ee57d4a9eca07998323585b6da94cb9fd0cd | # -*- coding:utf -*-
import random
import copy
from mahjong_project.server.common.logger import LogConfig
log_type = "console"
logger = LogConfig(log_type).getLogger()
class Table(object):
u"""该类主要抽象牌桌的行为,该类在整个流程只实例化一次。
该类的方法对应玩家的动作,因此玩家在牌桌上的每个动作都需要一个处理函数。
"""
# 记录所有桌的信息
all_table_info = list()
def check_... |
998,063 | 900fae9016ae98689692e00b0877e6ea4476d976 | # -*- coding: utf-8 -*-
"""Models for API requests & responses."""
import dataclasses
import typing as t
import marshmallow_jsonapi.fields as mm_fields
from ..base import BaseModel, BaseSchemaJson
from ..custom_fields import SchemaBool, field_from_mm
class SignupRequestSchema(BaseSchemaJson):
"""Schema for perf... |
998,064 | 77e2f77ee0a0194ce178324503e8ddce89ffbf3b | ee = True
|
998,065 | 96aaeb7ea95ea569251725e1ef56cf765a3a6f95 | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, random
import sys
sys.path.append(r"C:... |
998,066 | 3b2fb476e1460c09b213d6cfcee391c0eca8a4a7 | class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
elif len(strs) == 1:
return strs[0]
most_right = len(strs[0])
for i in range(1, len(strs)):
for j in range(most_right):
if j == ... |
998,067 | 64a95c0c3f063b13263023280cde3bb8f33b9b49 | from cunsumer.consumer_confluent_kafka import KafkaConsumer
ERROR_CODE_ZERO = 0
class ConsumerHandler:
def __init__(self, bootstrap_servers, group_id, client_id, timeout, auto_commit, config):
self._consumer = KafkaConsumer(bootstrap_servers, group_id, client_id, timeout, auto_commit, config)
def m... |
998,068 | 38b2e9fc3bee69c7bb0b47a837859bf2b46b2617 | from django.db import models
# Create your models here.
class Supplier(models.Model):
supplier_name = models.CharField(max_length=50,null=True, blank=True)
quantity = models.IntegerField(null=True, blank=True)
class Meta:
verbose_name = '供应商'
verbose_name_plural = '供应商'
class Overdue(mod... |
998,069 | 9ccf561ddd79a2e2e13f55f207b73e6323f9c510 | import math
pi =(round(math.pi,3))
print("Approximation of pi:",round(pi,3))
rad = eval(input("Enter the radius:\n"))
print("Area:", round(3.14159*(rad**2),3)) |
998,070 | f812a8c33b879647644c89d6470b16e12706ff92 | import pytest
import asyncio
from unittest.mock import MagicMock
from aiocache.backends.memory import SimpleMemoryBackend
@pytest.fixture
def memory(event_loop, mocker):
SimpleMemoryBackend._handlers = {}
SimpleMemoryBackend._cache = {}
mocker.spy(SimpleMemoryBackend, "_cache")
return SimpleMemoryBa... |
998,071 | 814cfc5a34effc2a440c60d5aa43db239f6266bb | """
Module to aggregate transactions, routes and counters
1. RouteAggregator - Conflates long routes to short ones
2. TxnAggregator - Classifies transaction based on a predicate and aggregates elasped cycles
Author: Manikandan Dhamodharan, Morgan Stanley
"""
from xpedite.txn.classifier import DefaultClassifie... |
998,072 | 652e0cf06f2bc34459839dc3825a340ec3bcaa6d |
class Emoji:
def __init__(
self,
id,
name,
is_animated = False
):
self.id = id
self.name = name
self.is_animated = is_animated |
998,073 | b35e58c7f5af54cc089dd862820fa8d3f3fa5565 | __author__ = '123'
# coding=utf-8
from common.base import Base
from common.myTest import MyTest
from common.logger import logger
from common.connectMysql import ConnectMysql
from common.connectRedis import ConnectRedis
from common.jsonparser import JMESPathExtractor
import time, unittest
class TestCase(MyTest):
... |
998,074 | 374b0a89bd96cc4afa7b8926bd7220795ca19a99 | # -*- coding: utf-8 -*-
import os
import sqlite3
import urllib.request
from bs4 import BeautifulSoup
def get_feeds(url):
# RSSフィードの取得
response = urllib.request.urlopen(url)
xml = response.read()
soup = BeautifulSoup(xml, 'html.parser')
# 結果格納用の箱を準備
result = []
# RSSを分解して今回必要な要素を結果に詰め込む
... |
998,075 | 21f317a020d17e2417ae118928f74ffecd4a716c | '''
Doxygen Comments Generator
--------------------------
Author : Anish Kumar
Date : 23/06/2018
'''
import time
import re, sys
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog, tkMessageBox
import os
import subprocess
from collections import Counter
Str = '''***********************************... |
998,076 | df31b69ad14c34f54012ffaf2ff371e0528ef0fa | ## setについて
## listを重複を省いて集合にする。
my_list={11,12,13,14,15,12}
my_set=set(my_list)
print(my_set) |
998,077 | 13b90a2c95a672dd7d12a131b415f1ab8fd84f36 | """ec2 instances scheduler."""
from typing import Dict, List
import boto3
from botocore.exceptions import ClientError
from .exceptions import ec2_exception
from .filter_resources_by_tags import FilterByTags
class InstanceScheduler:
"""Abstract ec2 scheduler in a class."""
def __init__(self, region_name=N... |
998,078 | ab54564901cac6b49e153919be3d926bef5af324 | # Obtaining the current date and time
import datetime
current_date_time = datetime.datetime.now()
print("Current datetime: ", current_date_time)
current_date = datetime.datetime.now().date()
print("Current date: ", current_date)
current_year = datetime.datetime.now().date().year
print("Current year: ", current_year)... |
998,079 | fd2a4fe3c3896fcdb249590d078b9821eff45784 | #!/usr/bin/env python
# encoding: utf-8
"""
Metadata object module
"""
__author__ = 'Christoph Piechula'
import os
import archive.util.times as utl
import archive.crawler.extractor as extractor
import archive.util.mimextractor as mime
class MetaData(dict):
"""
Metadata Builder Class, generates a meta obje... |
998,080 | 2a3a6197db1ac2ac235dd5700e6c8dfde9fc63f8 | from itertools import product
import en_core_web_md
from collections import defaultdict
from tqdm import tqdm
from ent_extractor import EntitiesExtraction
from common import RELATION, TEXT, PERSON, ORG, is_the_same
class RelationSentence:
def __init__(self, idx, text, analyzed, entities):
self.idx = idx... |
998,081 | 6800e14558f9f0fabc561e556b5c06ab2159bbce | from save_beer import save_beer
from lookup_beer import lookup_beer |
998,082 | 18e003d7b3f182430fa9a177be4a82f9e6aa1247 | """
Flask-FIDO-U2F
-------------
Flask plugin to simplify usage and management of U2F devices.
"""
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than t... |
998,083 | 21ef83dc8a63c36f464ad95ee6dcb69bacf05c99 | from django.db import models
class Company(models.Model):
name = models.CharField(max_length=200)
category = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Companies"
class Ad(models.Model):
Company = models.ForeignKey(Company,on_delete=... |
998,084 | ec865eb3d583fbf2c67725fbe7b978d890a4ea25 | from . import views
from django.urls import path
from django.conf.urls import url, include
from django.views.decorators.csrf import csrf_exempt
from django.views import static
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('post/<slug:slug>/', views.PostDetail.as_view(), name='post_detai... |
998,085 | 770def2dc19cf2664e0e5639ad53e0293fddee54 | a, b, c, d = input().split()
a = int(a + b)
c = int(c + d)
print(a + c) |
998,086 | 54384c8ed8215ee18956c722420982004a632337 | import subprocess
import os
import pickle
import re
import shutil
import tempfile
from game_controller import GameController
from textwrap import wrap
from PIL import Image, ImageDraw, ImageFont
from math import log10
from fnmatch import fnmatch
def get_image_format(data):
'''Gets image format from its data (byte... |
998,087 | 9ae7e6d766060d900331780f18d9220631bd2cfe | import sys
import collections
import sklearn.naive_bayes
import sklearn.linear_model
import nltk
import random
random.seed(0)
from gensim.models.doc2vec import LabeledSentence, Doc2Vec
nltk.download("stopwords")
# Download the stop words from nltk
# User input path to the train-pos.txt, train-neg.txt, test-pos.txt, ... |
998,088 | e5a950490c17edacdcdb327ed7d220de3af6b5d5 | import numpy as np
import matplotlib.pylab as plt
import sys
sys.path.append('../zdrojaky')
from tsplot import tsplot
from nig import NiG
from scipy.io import loadmat
datafile = loadmat('/tmp/Gi.mat')
rolling_data = datafile['CDsel']
start = 300
end = 850
data = rolling_data[start:end,10]
ndat = data.size
tsplot(dat... |
998,089 | 192d7d4e1ac871b10995323768df28c131dfb936 | import argparse
import logging
import os
from . import __version__, DEFAULT_PAGINATE_BY
from .main import do_everything
def main():
# Setup command line option parser
parser = argparse.ArgumentParser(
description='Parametric modeling of buckling and free vibration in '\
'prismatic... |
998,090 | da6696aec3fbec14780a784de21b57fde95d5f13 | """
Refer to https://github.com/BramVanroy/bert-for-inference/blob/master/introduction-to-bert.ipynb for a quick intro
Code credits to: Bram Vanroy
"""
from transformers import BertModel, BertTokenizer
import torch
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Convert the string "granola bars" t... |
998,091 | 912b67e4021c1ec05471437069ec0fea4a8a0a9c | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-26 09:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cats', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
998,092 | 234f58be7cfcc6260500903dccdf4c244908bb5b | #!/usr/bin/env python
from scipy.sparse import coo_matrix
class Matrix:
"""A sparse matrix class (indexed from zero). Replace with NumPy arrays."""
def __init__(self, matrix=None, size=None):
"""Size is a tuple (m,n) representing m rows and n columns."""
if matrix is None:
self.dat... |
998,093 | 948b64a3f9226b0f27cffc0476e68e8116e7f438 |
"""
prompt user to input number as of todays toppings
set factn as 1
if n is < 0 print "It is not possible to have minus toppings."
else for i in range 1 to n plus 1
factn equals factn multiplied by i
print "Factorial of", number, "is", factn" to show how program works
prompt user to input number as of stanard toppi... |
998,094 | 952b76bdbda889a5f48bd954b3cb1806cefc89c1 | # Created by Qixun Qu
# quqixun@gmail.com
# 2017/04/03
#
# This script provides a test on generating
# SIFT descriptors on images which consist
# of digits. This script and relative
# functions are tested under Python 3.5.2.
import numpy as np
import generate_SIFT as gs
import classify_SIFT as cs
# ----------------... |
998,095 | 7aa8b6334639369c87f6d24690121404a99cbf02 | import paho.mqtt.client as mqtt
MQTT_HOST="172.20.0.2"
MQTT_PORT=1883
MQTT_TOPIC="hw3"
CLOUD_MQTT_HOST="169.61.16.130"
CLOUD_MQTT_PORT=1883
CLOUD_MQTT_TOPIC="facedetection"
def on_connect(client, userdata, flags, rc):
print("Connected to jetson")
def on_connect_cloud(client, userdata, flags, rc):
print("Con... |
998,096 | d016d4ec47ed5793c50d425593ecbd10a9645ca4 | #!/usr/bin/env python
"""cardapios_spider.py: Very simple spider to crawl through the
online menus of the University of São Paulo :D ."""
__author__ = "Juliano Garcia de Oliveira"
__copyright__ = "Copyright NULL, Planet Earth"
import scrapy
from scrapy_splash import SplashRequest
# Color constants
W = '\... |
998,097 | da10fd716218978df1a89477060adb8c076f1d71 | from bluetooth import *
import subprocess
target_name = "NJ's Cellphone"
target_address = "00:1A:75:C2:61:CE"
#target_address = "00:1A:89:3A:6B:FF"
flag = 0
flag1 = 0
while flag1 == 0 :
nearby_devices = discover_devices(duration=4)
if(len(nearby_devices) != 0) :
for address in nearby_devices :
... |
998,098 | 4771fde616560cdc67ecc0ee840b7206be11f838 | from first_class_functions_asgnmnt import *
nums_list = [1, 2, 3, 4, 5]
# a higher order function which takes a function and an array of numbers as args
# here, we wil pass in a square func to which every num from the array is passed to be squared
def func_array_as_args(func, num_array):
num_squares = []
for... |
998,099 | 9ea06a7e48831279057e06b5ec983264c7728877 | from day22.grid import Grid
from day22.node import Node
from day22.solver import Solver
with open('input.txt') as f:
lines = [line[:-1] for line in f.readlines() if len(line) > 0][2:]
nodes = [Node.from_string(line) for line in lines]
# viable_pairs = 0
# for node1 in nodes:
# for node2 in node... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.