index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
997,800 | 9cf88b792884979d9cb68442b244364c63c53ebc | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flaskblog.config import Config
# Initialize Application
app = Flask(__name__)
app.config.from_object(Config)
# Extensions
db = SQLAlchemy(app)
bcrypt ... |
997,801 | d3d5999561aa9808c5442ed8bb0d3bc35f9f6344 | from ZeroScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
"c0450.bin", # FileName
"c0450", # MapName
"c0450", # Location
0x0024, # MapIndex
"ed7113",
0x00002000, ... |
997,802 | e0fa315f80ff2d25a72f7fcaa3436e4632cb83e7 | import FWCore.ParameterSet.Config as cms
###########################################################
##### Set up process #####
###########################################################
process = cms.Process ('ANA2')
process.load ('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.repor... |
997,803 | bd1d5bc65ceac832c78a24bc253a01f7e918a435 | from django.db import models
from django.core.validators import MaxValueValidator
# Create your models here.
class Semester(models.Model):
sem = (
('1st Semester', '1st Semester'),
('2nd Semester', '2nd Semester'),
('3rd Semester', '3rd Semester'),
('4th Semester', '4th Semester'),
... |
997,804 | c52a38da78bfc9cef3e57ee949be2c2201ad291d | from typing import NamedTuple
class VGATiming(NamedTuple):
x: int
y: int
refresh_rate: float
pixel_freq: int
h_front_porch: int
h_sync_pulse: int
h_back_porch: int
v_front_porch: int
v_sync_pulse: int
v_back_porch: int
vga_timings = {
'640x350@70Hz': VGATiming(
x ... |
997,805 | 3ca71fb72777a91b07f6bbb77d2a1db9216ca317 | import requests
import os, shutil
import json
import jsonpath
# 导入requests_toolbelt库使用MultipartEncoder
from requests_toolbelt import MultipartEncoder
url = "http://shibietu.wwei.cn/fileupload.html?op=shibietu_zhiwu"
headers = {
"Content-Type":"multipart/form-data",
"Referer":"http://shibietu.wwei.cn/zhiwu.html",
"Or... |
997,806 | 9f836525c5e6bb7d4c0cde388131e8ccac84200e | '''
Description: Copyright © 1999 - 2021 Winter. All Rights Reserved.
Author: Winter
Email: 837950571@qq.com
Date: 2021-04-16 15:15:43
LastEditTime: 2021-04-16 19:15:00
'''
import functools
from flask import jsonify, request
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from config import AUTH... |
997,807 | 91882be31c763859496a74cb5fc559006833a83a |
# This array shows the index positions, and category types/names, of our different kinds of ingredients in a recipe
KINDS = ["sugar", "flour", "salt", "butter", "baking powder", "milk", "egg", "vanilla", "chips", "baking soda", "other"]
'''
The recipe class reperesents a recipe which contains a name and a list of ing... |
997,808 | 9a7392bdb67e676a824edf1c99c0745e5ef0a49d | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from csdn.items import CsdnItem
from scrapy.selector import Selector
class CsdnaSpider(CrawlSpider):
name = 'csdna'
allowed_domains = ['blog.csdn.net']
start_urls = ['http://b... |
997,809 | 8b4e76e6ca1332612bea16c0a2e2d0e4f99ee6c4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
from requests_futures.sessions import FuturesSession
from concurrent.futures import wait
import requests
import re
import os
import sys
if(len(sys.argv)>1):
n = int(sys.argv[1])
if(len(sys.argv)>2):
p = True
else:
p = False
else:
... |
997,810 | 0f8cfcf3dd662ef53cb8d5fe087f69a8717b5836 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/15 18:27
# @Author : AsiHacker
# @File : __class__.py
# @Software: PyCharm
# @notice : True masters always have the heart of an apprentice.
from python笔记.aaa基础内置.类相关.抽象类定义 import C
obj = C()
print(obj.__module__) # 输出 lib.aa,即:输出模块
print(obj.__cl... |
997,811 | 8958e3d28b6ff72f7da04c9172a6ecdfa4ef0abd | import numpy as np
import cv2
import imutils
import sys
import pytesseract
import pandas as pd
import time
import pymysql.cursors
from PIL import Image
from pyzbar.pyzbar import decode
print(cv2.__version__)
image = cv2.imread('cartest18.jpg')
image = imutils.resize(image, width=500)
# * . : )
cv2.imsho... |
997,812 | af03b14a6eea12a89e1c926764d4bd5894e01c29 | import os
import unittest
import datetime
import tempfile
from cStringIO import StringIO
from mock import Mock, sentinel, call, patch
from stock_pricer import StockPricer
from util import Money
from invest import *
stock1 = Stock('SYM1', 'bond')
stock2 = Stock('SYM2', 'bond')
stock3 = Stock('SYM3', 'world')
stock4 =... |
997,813 | 138ef47f7ff9579a1d622907ddff5869e7fda458 | #Author:Zhao fei
file1="j1226_1"
file="./data/j12.mm/"+file1+".mm"
print(file) |
997,814 | 86b33b7e7c31e15694ad5fe25c763815dccfea0c | import pandas as pd
def import_data_from_files(tickers, path):
df_list = []
sym_list = []
for ticker in tickers:
file = path + '/' + ticker + '.csv'
df = pd.read_csv(file, index_col=0)
df.index = pd.to_datetime(df.index)
df_list.append(df)
sym_list.append... |
997,815 | 138cc6c4f36c5de0804b5eec68d428be534359e8 | import sqlite3
from bottle import *
import api.users
import api.messages
class ConnectionHandler():
def __init__(self, loc='main.db'):
self.connection = sqlite3.connect(loc)
self.semaphore = threading.Semaphore()
def get(self):
self.semaphore.acquire()
return self.connection
... |
997,816 | 21f3944325c09b4a4ac989d260111e0c60258a0f | import time
import math
from selenium import webdriver
from selenium.webdriver.support.ui import Select
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
link = "http://suninjuly.github.io/selects1.html"
new_link = "http://suninjuly.github.io/selects2.html"
browser = webdriver.Chr... |
997,817 | 16b5b71ef98c3b3d307447f9b9e664b04a05af73 | class Solution:
def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
count = [[0] * width for _ in range(height)]
for r in range(height - sideLength + 1):
for c in range(width - sideLength + 1):
for ro in range(sideLength):
... |
997,818 | 6e83992271b476298b92fb62aeceffc09f72dba1 | import calendar
import concurrent
import datetime
import time
from concurrent.futures.thread import ThreadPoolExecutor
from QUANTAXIS import QA_util_code_tolist, QA_util_time_stamp, QA_util_log_info, QA_util_to_datetime, \
QA_util_datetime_to_strdate
from dateutil.relativedelta import relativedelta
import tushare... |
997,819 | 6c2d16e22313666ee3293276fb2f8ffa4850785e | from os import path
import yaml
from kubernetes import client, config
def main():
# Configs can be set in Configuration class directly or using helper
# utility. If no argument provided, the config will be loaded from
# default location.
config.load_kube_config()
body = client.V1Service(
... |
997,820 | a57c6f6bef52c134139108449795b379f0880a81 | from editlive.adaptors.base import BaseAdaptor
class TextAdaptor(BaseAdaptor):
"""The TextAdaptor is used for Text fields.
"""
def __init__(self, *args, **kwargs):
super(TextAdaptor, self).__init__(*args, **kwargs)
if self.form_field:
self.attributes.update({'data-type': 'textF... |
997,821 | e68a26e12f59ad8cac2a38bbed4b7481326d949c | # -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... |
997,822 | 51bf2d50852e5b6d91a77557ec56e2012f5c4365 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from nata.utils.formatting import array_format
from nata.utils.formatting import make_as_identifier
@pytest.mark.parametrize(
"input_, expected",
[
(np.array(1), "1"),
(np.array(None), "None"),
(np.array([1]), "[1]"),
(n... |
997,823 | 185034fea89f17e0d3ad0e40d9dffdd0a559cb28 | # if we enter string it will throw error
# ValueError Exception
age = int(input("Age:"))
list_item = [1, 2]
print(list_item[3]) # IndexError
|
997,824 | 076e2b8c8597ba34b2c4bfbe2c9bba9dbf3e3464 | # The following iterative sequence is defined for the set of positive integers:
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that this sequence (starting at 13 and finishing at... |
997,825 | 063f367f05cc5cd1b5943dc758450ed937e6d81c | from django.utils import unittest
from django.test import TestCase
from django.test import Client
class SimpleTest(unittest.TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.client = Client()
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
... |
997,826 | f13e706415e9e63209f8dd32a822697d11db2700 | # coding: utf-8
from __future__ import unicode_literals, print_function, division
#!/usr/bin/env python
__author__ = 'setten'
import timeit
import os
def test_write(m):
"""
file write test function
"""
l = []
for i in range(m):
l.append(i)
f = open('test', 'w')
f.write(str(l))
... |
997,827 | 4e55b9697d6600f0fcc837c52a4c84286fcf6ee3 | import re
def create_index(messages, user_info):
user_words, user_channels, channel_words, user_msgs = {}, {}, {}, {}
for user, channel, message, n_reactions in messages:
if user in user_words:
user_channels[user][channel] = user_channels[user][channel]+1.0 if channel in user_channels[user]... |
997,828 | 11ce1465a4fc674902f39c60d2d9edb7610e0275 | """freshmenu URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
997,829 | 655fab90800e5b3705db6304efc66b9d9e98d75d | # coding=utf-8
"""
Contains functions to manage the catalog table, locally (client side requests) and remotely (server
side actions).
Usage: LocalCatalog.create_dtable(catalog_database_filename)
LocalCatalog.record_ddl(socket, command_list)
LocalCatalog.record_partition(socket, command_list)
Local... |
997,830 | 44ea6c902cd6d4f24fc2f723e7bcb71ccd793e97 | import threading, time, random, Queue
TIME_TO_RUN = 10
class Producer:
def __init__(self):
self.product = ['a','b','c','d','e','f','g']
self.next = 0
def run(self):
global q
while time.clock() < TIME_TO_RUN:
if self.next < time.clock():
f = self.pro... |
997,831 | 865ab052edfeb3ce96c047a93bd2bb336d368949 | from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.http.response import JsonResponse
from django.views.generic import View # 通用类视图 as_view的使用
from .models import cateType,UserInfo
import json,re
from django.core import serializers
class asyData(View):
"""异步数据获取"""
def... |
997,832 | a99f9098bbeaa409e9886506bccd6c7e00ec9400 | """A simple implementation of a greedy transition-based parser. Released under BSD license."""
from os import path
import os
import sys
from collections import defaultdict
import random
import time
import pickle
import re # For sentence splitting only
SHIFT = 0; RIGHT = 1; LEFT = 2;
MOVES = (SHIFT, RIGHT, LEFT)
STA... |
997,833 | 337e3f85934b0abe59b526ed90cf0cb965049d5c | import subprocess
import os
import time
status = subprocess.Popen("python status-server.py", shell=True, stdout=subprocess.PIPE)
while 1:
# check every 5 minutes whether nfd is alive
time.sleep(300)
try:
output=subprocess.check_output('nfd-status | grep \"memphis.edu/internal\"', shell=True)
... |
997,834 | c6ede32397cc521e1f40bee78fc9ce6759165143 | '''This file has been used for the research project course (ENGN8601/ENGN8602) by Namas Bhandari of the Australian National University. The file can be found on github.com/namas191297/evaluating_mvs_in_cpc'''
import numpy as np
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage
from matplotlib import cm
f... |
997,835 | d51576bdc428a3d138eb33366af6352e01ed811d | from toolz import curry
@curry
def pair(first, second):
"""Takes two arguments, fst and snd, and returns [fst, snd]"""
return [first, second]
|
997,836 | c44798efe82c4be83503d135e0a1a545eecf4b5d | a = [11, 21, 31, 11, 21, 31, 41, 51]
d = {}
for i in a:
d[i] = d.get(i, 0) + 1
print d.items()
|
997,837 | 83d7d8622cfd0d7c6b6ddafeb0ebc08ff9ceb851 | #!/usr/bin/env python
import itertools
import os
import pygame
import random
import sys
import time
import thorpy
from pygame.locals import *
import common
LEFT_MOUSE = 1
RIGHT_MOUSE = 3
class MineCell(common.Cell):
def __init__(self, r, c, w, h, border, font):
super().__init__(r, c, w, h, border, font... |
997,838 | c553bd0281b55628e82e1173e315013c0f42c0b5 | from mdp import EpidemicMDP # changed from import mdp
import random
from collections import defaultdict
import matplotlib.pyplot as plt
infections = {'Nigeria' : 1}
resources = 15
# resp_csv = 'data/FR_MAUR_NIG_SA_responseIndicators.csv'
# trans_csv = 'data/FR_MAUR_NIG_SA_transitions.csv'
resp_csv = 'data/country_res... |
997,839 | f55ec6af83d35a25f61c826f42fb6bb7ed4a62a5 | shopping_list.remove("milk")
shopping_list.append("brownie")
|
997,840 | a6f557bcfdf7fbc60351c2c9dd5130d2a76f5742 | """
A Python script that runs the fmr.R R script.
"""
# Import the commands module and run the fmr.R script.
import commands
result = commands.getstatusoutput("Rscript --verbose fmr.R")
# Check the exit status to see if the run was successful
# and print the output.
if result[0] == 0:
print "*** Successful run! ***... |
997,841 | 97699d09fdee02cf3ca6ef0e383a60ea6331f109 |
# helperFunction: uses all the other functions
#permList is the final list or array of all possible permutations
def helperFunction(inputString):
permList = [];
permList.append(permutateReverse(inputString))
permList += permutateInitials(inputString)
permList += permutateNumbers(inputString)
permList += fir... |
997,842 | 7afc53bdbab10831c52a21c3922f25f95b82c85d | from gym.envs.registration import register
register(
id='CrowdSim-v0',
entry_point='crowd_sim.envs:CrowdSim',
)
register(
id='CrowdSim_mixed-v0',
entry_point='crowd_sim.envs:CrowdSim_mixed'
)
|
997,843 | c64ce76c63dfb2c7282d04051be4c994f7c17aa4 | import json
def getCurrentUser():
user = {}
with open("../db.json") as f:
user = json.load(f)
return user["current-user"]
triviaPos = 0
def getNextTrivia():
triv = []
with open("../trivia.txt") as f:
for line in f.readlines():
triv.append(line.strip().split("/"))
... |
997,844 | 57f9a718bafa47f58dcfbd5057c7413ffd6de95a | from .classification import ClassificationNetwork
from .configuration import Configuration
from .logging import Logger, TimeLogger, ProgressLogger
from .segmentation import SegmentationNetwork
from .training import TrainingUtils
from .utils import Utility
from .validation import ValidationUtils
from .windowing import P... |
997,845 | b6b6f114d959cf6601a2be408fb8a8ef0bc559ae | import sys, subprocess
import getpass
try:
import pkg_resources
except ImportError:
raise Exception("you must have setuptools installed to run the tests")
pkg_resources.require('quixote>=2.3')
from quixote.server.simple_server import run
from io import StringIO
import os
import socket
import urllib.request, ... |
997,846 | 265c460ca19c07fe867c5a1843890739f2382075 | import sys
ksize = int(sys.stdin.readline().rstrip())
original = str(sys.stdin.readline().rstrip())
kmerlist = list()
for i in range(0, len(original) - ksize + 1):
kmer = original[i:(i+ksize)]
kmerlist.append(kmer)
for kmer in sorted(kmerlist):
print(kmer)
|
997,847 | ddd039dac7ca035d1663aedd730b7d726187e63a | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 19 14:48:44 2019
@author: andy3
"""
#First,we need to download the file on kaggle"cat-vs-dogs"
import os,shutil
original_dataset_dir=r'C:\Users\andy3\train'
base_dir=r"C:\Users\andy3\cats_and_dogs_small"
if not os.path.isdir(base_dir):os.mkdir(base_dir)
train_dir=os.... |
997,848 | 9a8ef4e5e654f91b1e1edc190016b2d5f58ada32 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import StudlUser
class StudlUserAdmin(UserAdmin):
list_display = ('id', 'email', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_admin', 'is_staff')
search_fields = ('id', 'email', 'first_name', 'last_nam... |
997,849 | b238ae2ab9eb9fa645793256d9a554e09968cc90 | tot1 = 0
tot2 = 0
sumtot = 0
for num in range(1, 101):
tot1 += (num*num)
tot2 += num
tot2 *= tot2
sumtot = tot2-tot1
print("tot1: ", tot1, " tot2: ", tot2, " sumtot: ", sumtot)
|
997,850 | 0fb8c5b9a0b23d9d5ad8bf011269eb4bae13b2d0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def book_id(book):
def ord2str(mychr):
return str(ord(mychr))
return ''.join(list(map(ord2str, [mychr for mychr in book])))
def id_lens(book):
return len(book_id(book))
|
997,851 | 1c5c3a191e2e5753d3781c39344e7b793e7f056b | from urllib.request import urlopen, quote
import json
import requests
def get_map_location(address):
"""根据传入的地址返回对应的地址编码
:param address:详细地址
:return:对应地点的地址编码
"""
url = 'https://restapi.amap.com/v3/geocode/geo'
output = 'json'
key = '51087efef5b53e73d939bad91cf21a40'
address = quote(a... |
997,852 | da424381a4c825948089942f32f2b64e6307e78f | def first():
num = int(input("Кратно число:"))
count = int(input("Брой на кратни:"))
for i in range(num, count * num + 1, num):
print(i)
def second():
vocalsstr = str(input("Please type a sentence: "))
vocalseng = "aeiou"
vocalsbg = "аъеиоу"
for v in vocalseng:
... |
997,853 | 9ffaa925870aba3b5eace4731980043d72c61786 | from django.shortcuts import render
from .models import suggest_movies
# Create your views here.
def index(request):
login = request.session.get("email")
movies_suggested = suggest_movies(login)
print(movies_suggested)
context = {"recommedation": movies_suggested}
#print(context["recommedation"])
... |
997,854 | a006f8a5609cf3a675cc91a2e1a06290005d9585 | import re
import sys
import json
import subprocess
import traceback
import xml.etree.ElementTree as ET
import os
import pickle
from io import StringIO
import pdfminer.high_level
import tarfile
import re
import multiprocessing
from functools import partial
import itertools
import signal
import time
def pdf2txt(fp):
o... |
997,855 | 3ac3402abeb1396ffadae45e269e46b0c1161d21 | #regular expression
def isphonenumber(a):
if(len(a)!=12):
return False
elif(a.find('-')!=3 and a.rfind('-')!=7 ):
return False
elif(a[:3].isdigit() and a[4:7].isdigit() and a[8:11].isdigit() ):
return True
else:
return False
print(isphonenumber('111-111-1111'))
b=input("enter string ")
... |
997,856 | 6719b3c8a56b2856e5861f9b46bf8e6f2ff8e55e | """Dev-Server for model"""
from bottle import route, run, request
from predict import *
import PIL
import urllib
@route('/req', method= "GET")
def index():
res = urllib.request.urlretrieve(request.params["url"], "test.jpg")
im = PIL.Image.open("test.jpg")
return {'result': str(predict(im))}
run(host='localhost', ... |
997,857 | 00b508cee014d4b0ee0d14edebd78ef04bd06afc | import csv
import time
import numpy as np
import matplotlib.pyplot as plt
def read(filename, date_idx, date_parse, year, bucket=7):
days_in_yr = 365
freq = {}
for period in range(0, int(days_in_yr/bucket)):
freq[period] = 0
with open(filename, 'r') as csv_file:
reader = csv.reader(csv_... |
997,858 | 1b48e123dc293bf5a4d169f9dd27b4311563a5ef | #4. If the ages of Mr.X, Mr.Y and Mr.Z are inout through the keyboard, Write a Python program to determine the oldest person among them.
x = int(input("Enter the Age of Mr.X: "))
y = int(input("Enter the Age of Mr.Y: "))
z = int(input("Enter the Age of Mr.Z: "))
if (x>y)and (x>z):
print("The Oldest Person is Mr.X wi... |
997,859 | 89c67b93423a5f0b3a88d63533ea910fa0275032 | #!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
import os
os.system("find ./ | sed 's,^./,TranslateActivity.activity/,g' > MANIFEST")
os.system('rm TranslateActivity.xo')
os.chdir('..')
os.system('zip -r TranslateActivity.xo TranslateActivity.activit... |
997,860 | bbdcead657837e9f44139167ed19169e07bbecf7 | import os
import sys
import subprocess
sys.path.append(snakemake.config['args']['mcc_path'])
import scripts.mccutils as mccutils
def main():
mccutils.log("popoolationte2","setting up for PopoolationTE2")
ref_fasta = snakemake.input.ref_fasta
fq1 = snakemake.input.fq1
fq2 = snakemake.input.fq2
log... |
997,861 | 619688dd822db106756f5b85258d6a740fa53ef7 | from .conversion import mol_to_smiles
def adock(receptor_input,
smiles,
ligand_name,
center_x=7.750,
center_y=-14.556,
center_z=6.747,
size_x=20,
size_y=20,
size_z=20,
vina='qvina2',
seed=None,
cpu=1,
lig_dir = './docking_s... |
997,862 | e9ad66ae4af617a8bbfc11538eeaebca0842e1e4 | <<<<<<< HEAD
class TestingConfig(Config):
TESTING = True
SECRET_KEY="GGggjjjfk887856$%kk"
# Disable CSRF protection in the testing configuration
WTF_CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(basedir, "test.sqlite")
=======
GOOGLE_CIENT_ID = ${{ secrets.GOOGLE_CLIENT_... |
997,863 | 7fd1d4234fdf6bb47be2da870b1514626906030a | """
Задание 1. При старте приложения запускаются три потока. Первый поток заполняет
список случайными числами. Второй поток находит сумму элементов списка,
а третий поток среднеарифметическое значение в списке. Полученный список, сумма и
среднеарифметическое выводятся на экран.
Задание 2. Пользователь с клавиатуры вво... |
997,864 | 62671266ec66006931d8d5b15f0a08e71c09c460 | import numpy as np
import matplotlib
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from astropy.stats import sigma_clipped_stats
from image_eval import psf_poly_fit, image_model_eval
def multiband_fourier_templates(imszs, n_terms, show_templates=False):
all_templates = []
for ... |
997,865 | 50ec9b783d82ca837b0818100d587be673e90a50 | import sys
import unittest
import xmlrunner
import csv
import os
from datetime import datetime, date, timedelta
class TestCovidCsvData(unittest.TestCase):
#first argument: defines where to look for the data
DIRECTORY = "./data/us-ak/ak-dhss"
#second arg: line to start reading headers at
HEADER_LINE = 1... |
997,866 | b122dd192359b55f82b828ecd24930c392626dae | from multiprocessing import Process
import time
# def timeit(f):
# def wrapper(*args,**kwargs):
# start_time = time.time()
# res = f(*args,**kwargs)
# end_time = time.time()
# print('%s函数执行时间:%.6f'%(f.__nmae__))
def prime_number():
for i in range(2,11):
for j in rang... |
997,867 | 28335056e2b8bfce94579996506674d54b5f55db | import curses
from .menu import Application, Stack, CheckBox, msgBox, Text, Menu, TextPanel
from .event import listener
import termcolor
from termcolor import COLORS, ATTRIBUTES
T = """
1. The Zen of Python, by Tim Peters
2. Beautiful is better than ugly.eautiful is better thaeautiful is better tha
3.Explicit is better... |
997,868 | 5e79bd31173fa2723fed6fb3bfec3fada0399f44 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def add(num1,num2):
return (num1+num2)
>>> add(3,5)
8
>>> add.__doc__
>>> def try(n1):
SyntaxError: invalid syntax
>>> def trytry(n1):
'wendang'
#zhus... |
997,869 | 8c061fd8f380be6b6cd71f94361b24c2c9b8db53 | countries = ['Romania', 'France', 'Germany', 'Netherlands', 'Spain', 'Portugal']
sexes = ['F', 'M']
years = [2017, 2018]
health_indexes = [3.4, 4, 78, 12, 78.1, 79]
dataset = [
(country, year, sex, health_index)
for country in countries
for year in years
for sex in sexes
for health_index in health_... |
997,870 | 7168fc41e2440e81ee63aa79447e4d7572cf9745 | import math
def mysqrt(a):
estimate = 1
epsilon = 0.0001
while True:
if abs(estimate ** 2 - a) < epsilon:
return float(round(estimate, 1))
else:
estimate = (estimate + a / estimate) / 2
def test_square_root():
print('a ', 'mysqrt(a) ', 'math.sqrt(a)', 'di... |
997,871 | 507ae99250db868cda8b0557e403c4ab68fd8899 | # --- Day 5: Sunny with a Chance of Asteroids ---
# You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get the air conditioner working by upgrading
# your ship computer to support the Thermal Environment Supervision Terminal.
# The Thermal Environment Supervision Terminal (T... |
997,872 | 585276c3bd26248fe6af1f9ead68e5d0aa19268b | from django.contrib import admin
# Register your models here.
from .models import Member
class Memberadmin(admin.ModelAdmin):
list_display=('id','name','university','age','address') #for admin panel like datebase
list_display_links = ('id','name')
list_filter = ('name',) #for filtering
list_editable =... |
997,873 | e64eed7c4df803048ce106bbd9ee22dfb3ebab0e | import datetime
import os
import random
from collections import defaultdict
import service_file
from service_write_html import fill_html, fill_html2, get_template
BASE_DATE = (
'сегодня',
'вчера',
'2 дня назад',
'3 дня назад',
'4 дня назад',
'5 дней назад',
'6 дней назад',
'7 дней наза... |
997,874 | 197ec47f7e51e8dca6337ba0965f764488786a62 | """
Len()-> Retorna o tamanho, ou seja, o número de itens de um iterável
Abs() -> Retorna o valor absoluto de um número sem consideral o seu sinal
Sum()-> Soma total de um iteravel
Round() -> Retorna o número arredondado para o digito de precisão após a casa decimal, se a precisão não for informado retorna o mais pr... |
997,875 | 20701861d815375fb81f533834d5c367459b95b8 | def eelarve(arv):
return 55+10*arv
var1 = eelarve(int(input("Mitu inimest on kutsutud? ")))
var2 = eelarve(int(input("Mitu inimest tuleb? ")))
print(var1)
print(var2)
|
997,876 | 1294b8444d4606b6817867d75cf90cae1b7214b7 | from typing import Optional, Union
from py262.abstract_ops.value import type_of
from py262.completion import Completion
from py262.environment import (DeclarativeEnvironmentRecord,
FunctionEnvironmentRecord,
GlobalEnvironmentRecord, LexicalEnvironment,
... |
997,877 | 40dc3f04b708528f5b24bdc07ec07c46d5e25770 | """
Data models as described by the Trompa CE and Schema.org definitions.
"""
from .sdo_thing import Thing
from .sdo_organization import Organization
from .sdo_person import Person
from .sdo_place import Place
from .sdo_creative_work import CreativeWork
from .sdo_media_object import MediaObject
from .sdo_audio_object i... |
997,878 | 3f07d9531c1acc87f0e45965abd2a4464b9cc0a1 | with open('input.txt', 'r') as file:
data = file.read()
def to_coords(input):
result = []
for pair in input.strip().split('\n'):
s = pair.split(',')
result.append((int(s[0]), int(s[1])))
return result
def bounding_box(coords):
return max([c[0] for c in coords]) + 1, max([c[1] for... |
997,879 | 57e509feb74cdc4624e704985d6885be0045f19b | from flask import Flask, render_template_string
from sucuri import rendering
app = Flask(__name__)
@app.route("/")
def index():
template = rendering.template('template.suc',{"text": "Hello! I'm here!", "var":[1, 2, 3, 4]})
return render_template_string(template) |
997,880 | 8c193afbb7ecadadcb7a722878d8e9a3e2680923 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
import logging
_logger = logging.getLogger(__name__)
import calendar
import datetime
from openerp.tools import SUPERUSER_ID, DEFAULT_SERVER_DATE_FORMAT
import openerp.addons.decimal_precision as dp
LINE_TYPE_EXCEPTION = 'x'
LINE_TYPE_RECURRENT = 'r'
L... |
997,881 | 3974d7e25a6f7b7efca295945cdb5611df2041c8 | import sys
sys.path.append('/Users/zac/Research/muon_g2_2015/nmr/bloch_fit')
import matplotlib.pyplot as plt
from pulse import NMRPulsePhaseFit
import util as u
import math
p = NMRPulsePhaseFit(u.get_pulse_path(),
zc_use_filter = True,
init_signal_cut = 4.0e-4,
... |
997,882 | f2cb0d36d93ee1ede97b6657d652f6f903686fee | # coding:utf-8
# 快速排序的实现方法是设置两个游标,一个从前往后,一个从后往前,如果左侧游标所指数据大于右侧,
# 两数据进行交换,直到两个游标指向同一数据,则第一趟遍历结束。结束时游标所在数据,左侧都比其小
# 右侧都比其大,接下来对游标前后的两个序列进行递归操作。
# 最优时间复杂度: O(nlogn)
# 最坏时间复杂度: O(n²)
# 稳定性: 不稳定
def quick_sort(alist, first, last):
"""
:param alist: 一个列表
:param first: 起始位置
:param last: 结束位置
:return:... |
997,883 | cf737094c833ee327b5b371c423af695976ad479 | from datetime import datetime
from event_data_discovery.activity_identifier_discovery import ActivityIdentifierDiscoverer
from event_data_discovery.activity_identifier_predictors import make_sklearn_pipeline
# ____________________________________________________________________________________________________________... |
997,884 | 239facd0e281e9c7246fd6880b4e793281d0cc8f | import simplegui
import random
def new_game():
global list_2, exposed, t, state
state = 0
t = 0
list_1 = list(range(0, 8))
list_2 = list_1 * 2
random.shuffle(list_2)
label.set_text("Turns = " + str(t))
exposed = [False] * 16
def mouseclick(pos):
global t, state, click1, click2
... |
997,885 | d60e3487cec11c3dac203a55fc9e528ec5c3518d | #!usr/bin/env python
# coding=utf-8
import os
import sys
# !/usr/bin/python3
import sys
# 跟普通函数不同的是,生成器是一个返回迭代器的函数,
# 只能用于迭代操作,更简单点理解生成器就是一个迭代器。
# 在调用生成器运行的过程中,
# 每次遇到 yield 时函数会暂停并保存当前所有的运行信息,
# 返回yield的值。
# 并在下一次执行 next()方法时从当前位置继续运行。
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
... |
997,886 | 476ecacfe94c773efab10cb92b96c36b4abdbf0d | import collections
import copy
class Solution:
def minFlips(self, mat: list) -> int:
M, N = len(mat), len(mat[0])
q = collections.deque()
def foo(mat):
return sum([sum(row) for row in mat]), tuple([tuple(row) for row in mat])
summ, t = foo(mat)
if summ == 0:
... |
997,887 | 96dcbd4642a44c3fddb5c92ba8110e7ef901c573 | import random
def jogar():
print("*********************************")
print("Bem Vindo no jogo da Adivinhação")
print("*********************************")
numero_random = random.randrange(1, 101)
numero_secreto = (numero_random)
total_de_tentativa = 0
pontos = 100
print('q... |
997,888 | 6561cd8eb17754b716bb06bf95f624e986cdf49e | from ScrapBooker import ScrapBooker
from ImageProcessor import ImageProcessor
sb = ScrapBooker()
imp = ImageProcessor()
arr = imp.load("42AI.png")
print(arr)
arr = sb.juxtapose(arr, 3, 1)
imp.display(arr)
|
997,889 | d7cb203b9cac1f8cd63f1037826ab4d5b4e6c3eb | import util
import numpy as np
import itertools
test_dimension = ['.#.',
'..#',
'###']
start_dimension = util.parse_file_as_list('input_files/day_17.txt')
def enter_the_matrix_again(dimensions=4):
universe = np.array([[1 if char == '#' else 0 for char in line] for line in sta... |
997,890 | 0692da1f2f79aba81391776deb7b8d8bd50a04a3 | /Users/hm/anaconda3/lib/python3.6/sre_compile.py |
997,891 | 6305e90de998b0dd767cc5ba035afa6829438e3a | from setuptools import setup, find_packages
setup(name='thesis', version='1.0', packages=find_packages())
|
997,892 | 7faf76ad1d2d22e0c611da3d3f8588cbba8faf78 | from setuptools import setup
setup(
name="project2",
version="0.1",
scripts=["data2.py"],
) |
997,893 | a734cb0c9f3ec6c93b869fc7cd5735bbdf539aca | class Keyboard:
def keyboard():
pass |
997,894 | aa13400ab86ba142ec4057b20c2639fcfbef64df | from subprocess import call
if __name__ == '__main__':
N = [1, 2, 3, 1, 2, 3, 3, 3, 3, 2, 2, 2]
deltas = [0, 0, 0, 0.05, 0.05, 0.05, 0.05, 0.005, 0.0005, 0.05, 0.05, 0.05]
sentenceLengths = [50, 50, 50, 50, 50, 50, 50, 50, 50, 10, 50, 100]
for n, delta, sentenceLength in zip(N, deltas, sentenceLengt... |
997,895 | 10de7d067573e22ca76a3fce56c5bdefdb8e32f4 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width','300')
Config.set('graphics', 'height',... |
997,896 | 7685bd3dda3c061e91aeff673a03a21a897ec0df | from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import pandas as pd
import pylab
"""
Discussion: Recall the article on Interest Rate Swap Valuation available at http://tinyurl.com/mnan8ok,
we assumed that the Swap Fixed Rate was already interpolated. The aim of this post is
to examine differen... |
997,897 | 4cdcfd342ad5586c48f69cdf332dfdded17a28e2 | from setuptools import setup
setup(
name='per_level_logging',
version="0.1.0",
author="Akira Tanimura",
author_email="autopp.inc@gmail.com",
description="Implementation of logging.Handler to change the output per level.",
license="Apache Software License 2.0",
keywords="logging",
url="h... |
997,898 | ad9b30b440f0672b567cf077a7b5b92e98535bf8 | #! python3
# -*- coding: utf-8 -*-
#
# Solution to Practice Project "Mad Libs"
# from "Automate The Boring Stuff", by Al Sweigart,
# Chapter 8.
#
# "Create a Mad Libs program that reads in text files and lets the user add
# their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears
# in the text file."... |
997,899 | 7777e1364bb60e58800a655c34202b7ef4db7c3c | import asyncio
from typing import Iterable, AsyncIterable, Union, Optional, Dict, Any, Tuple
import websockets
from bxcommon.rpc.provider.abstract_ws_provider import AbstractWsProvider
from bxcommon.rpc.rpc_errors import RpcError
from bxcommon.rpc.ws.ws_client import WsClient
class MockWebSocket(websockets.WebSocke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.