text stringlengths 38 1.54M |
|---|
#!/usr/bin/python
import csv
import datetime
import eyed3
import os
import re
import shutil
import subprocess
import urllib
import urlparse
import cgi
import string
directory = os.path.abspath("data")
##############
# DATA MODEL #
##############
class Event(object):
def __init__(self, level, gender, category, ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
input_file = open('aoc_6_input_sample.txt').readlines()
letter_flags=[]
for i in range(0,26):
letter_flags.append(0)
letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
count_of_each_group=[]
# In[2]:
... |
# -*- coding: utf-8 -*-
# @Filename: index.py
# @Author: Yee
# @Email: rlk002@gmail.com
# @Link: https://wj.pe
# @Date: 2018-03-20 14:37:09
# @Copyright: :copyright: (c)2018
# @Last Modified by: Yee
# @Last Modified time: 2018-03-29 12:10:38
from yee.base.basehandler import BaseHandler, RequestMixin, JsonBodyMix... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Simon'
from hashlib import md5
import os
import sys
import random
import string
import time
import common_optMysql,common_optOracle, common_optOracle_billing
# def MD5String(str):
# m = md5()
# m.update(str)
# return m.hexdigest()
def getRandomStrin... |
import subprocess
import re
import collections
def dictionary_seq(identifier, filename):
# Returns a dict of a multi FASTA file with sequence header as keys and sequence as values.
dictionary = {}
for line in filename:
if line.startswith(">"):
C_seq = ''
C_split_line = line.split(' ')
C_name = C_split_... |
import pygame as pg
import loading as ld
import Server.dinosaur as dino
import Server.cactus as cac
import Server.bird as bd
import Server.background as bg
def screen():
pg.init()
delta_x, delta_y = (pg.display.Info().current_w, pg.display.Info().current_h)
display = pg.display.set_mode([pg.display.Info(... |
import datetime
from dataclasses import dataclass
from sqlalchemy import Column, Integer, String
from src import db
@dataclass
class Branch(db.Model):
"""
This is the table for branches and their codes. Each account belongs to a particular branch the
default branch is the head office (01) which will be ... |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
import string, random
from django.core.mail import BadHeaderError, EmailMultiAlternatives
class EmailBackend(ModelBackend):
def authenticate(self, request, email=None, password=None, **kwargs):
UserModel =... |
import pika
def on_message(channel, method_frame, header_frame, body):
print("Message body", body)
channel.basic_ack(delivery_tag=method_frame.delivery_tag)
credentials = pika.PlainCredentials('guest', 'guest')
parameters = pika.ConnectionParameters('localhost', credentials=credentials)
print(parameters)
c... |
from openpyxl import load_workbook # Openpyxl is a Python library for reading and writing Excel 2010
import datetime
WS_LIST = {} #тут перечисляем все названия листов, к-ые хотим прочитать
def repair_time(my_time): # функция для исправления типа даты и времени
if isinstance(my_time=my_time, datetime.datetime):... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import chainer
import cv2 as cv
import glob
import numpy as np
import os
import xml.etree.ElementTree as ET
class VOC(chainer.dataset.DatasetMixin):
LABELS = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
'bo... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# datetime:2020/12/24 9:40
# author:qiu
from appium import webdriver
import time
desired_caps = {
'platformName':'Android',
'deviceName':'949c3e52',
'platformVersion':'10.0.3',
'appPackage':'com.tencent.news',
... |
#!/usr/bin/env python3
import aiohttp
from aiohttp import web
import asyncio
from asyncio import Queue
from async_timeout import timeout
import json
import logging
import re
import signal
import os
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.exc import RPCError
from hbmqtt.client import MQTTClie... |
'''
Created on 28 nov. 2019
@author: Javier Fernández
'''
print(5/0)
raise ZeroDivisionError('5/0')
try:
raise ZeroDivisionError(5/0)
except ZeroDivisionError:
print("Se lanzo la excepcion")
raise |
# -*- coding: utf-8 -*-
# 医疗器械广告
import pickle
import re
from selenium import webdriver
from gjypjd.utils import *
import json
import time
def main():
option = None
mysql_db = DataBase()
# 配置文件中开启是否无头,生产阶段关闭
if if_headless():
option = webdriver.ChromeOptions()
option.add_argument(argu... |
# Generated by Django 3.2.7 on 2021-11-03 20:34
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0009_auto_20211103_1217'),
]
operations = [
migrations.AlterField(
model_name='user',
na... |
#!/usr/bin/env python3
"""
xnat/xnat_archive.py: Provide information to allow direct access to an XNAT data archive.
"""
# import of built-in modules
import logging
import logging.config
import os
# import of third-party modules
# import of local modules
import utils.file_utils as file_utils
# authorship informati... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import models
from odoo.api import Environment, SUPERUSER_ID
def _synchronize_cron(cr, registry):
env = Environment(cr, SUPERUSER_ID, {'active_test': False})
cron = env.ref('crm_iap_lead_enrich.ir_cron_... |
from django.db import models
from .request import Request
class RequestPhoto(models.Model):
request = models.ForeignKey(Request, related_name="photos", on_delete=models.CASCADE)
photo_url = models.CharField(max_length=500)
class Meta:
verbose_name = ("RequestPhoto")
verbose_name_plural =... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 16:03:31 2020
@author: qchat
"""
from core.api.database import system
from core.api.database.users import User
user = User(12)
#system.add_user('dummy')
#user2 = User(max(system.get_user_dict().keys()))
#system.add_user('hh')
print('user dict: ',system.get_user_dic... |
"""
lecture 5
"""
#a = [1,2,3]
#b = [1,2,3]
#print(a == b)
#print(a is b)
#print(id(a))
#print(id(b))
#x = None
#print(id(None))
#print(id(x))
#print(x is None)
#print(x == None)
#y = []
#x = None
#print(type(y))
#print(y == None)
#print(y is None)
#print(x is None)
#print(True and False )
#print (True or False)
... |
from .utils import *
from .simulation import *
from .split_data import *
from .create_data import *
from .execute_evaluate import *
from tempural_analysis.majority_rule import *
from tempural_analysis.majority_per_problem import *
from tempural_analysis.majority_last_trials import *
|
# Generated by Django 3.0.8 on 2020-11-12 13:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0031_auto_20201112_1820'),
]
operations = [
migrations.RenameModel(
old_name='Questions',
new_name='Qu... |
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
import time
MAX_WAIT = 10
class NewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
... |
from netCDF3 import Dataset
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as plt
import numpy as np
filename='soundings.nc';
nc_file=Dataset(filename)
var_names=nc_file.variables.keys()
print "variable names: ",var_names
print "global attributes: ",nc_file.ncattrs()
print "col_names: ",nc_file... |
'''
Author: Raisa
Date: 28-12-19
Python Script for train data
'''
import keras
import sys
sys.path.append('../')
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.optimizers import SGD
from keras.layers import BatchNormalization
... |
#
# Copyright (C) 2022 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0... |
import inspect
from django.template import Library, Node, TemplateSyntaxError
from django.urls import reverse
from django.utils.encoding import force_str
from django.utils.translation import get_language
from parler.models import TranslatableModel, TranslationDoesNotExist
from parler.utils.context import smart_overri... |
from django.db import models
from .mixins import TimeStampedMixin
from django.contrib.auth.models import User
class Category(TimeStampedMixin):
description = models.CharField(max_length=255)
icon = models.CharField(max_length=255)
def __str__(self):
return self.description
class Site(TimeStampe... |
class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}@sandy.com"
def explain(self):
return f"This employee is {self.fname} {self.lname}"
@property
def email(self):
if self.fname == None or self.ln... |
'''
Write a script that takes a list and turns it into a tuple.
'''
list_ = [1234, 'steve', '¥¥¥¥', 54321]
print(type(list_))
print(list_[0])
print(len(list_))
list_2 = tuple(list_)
print(type(list_2))
print(list_2)
|
import pandas as pd
import pickle
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
filename = 'preprocessing/vectorizer.pkl'
# Load data
df = pd.read_pickle("data/data.pkl")
descriptions = df["description"]
# Get features
try:
# vectorizer = pickle.load(... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
class PlotSpectrum:
def __init__(self,
energies,
intensities,
plt_energy_range,
gauss_width=None,
mixed_indcs=None,
norm_contrib_fl=None... |
def distance(seqA, seqB):
if len(seqA) != len(seqB):
raise ValueError("Sequences must be the same length")
if seqA != seqB:
zip_seq = list(zip(list(seqA),list(seqB)))
return [ele[0] == ele[1] for ele in zip_seq].count(False)
else:
return 0
|
import pygame
import sys
from Character.sprite import *
from Xuly.background import *
if not pygame.font: print('Warning, fonts disabled')
if not pygame.mixer: print('Warning, sound disabled')
pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
... |
import datetime
import sqlite3
class db_worker:
def __init__(self, path='DB/myDB.db'):
super().__init__()
self.conn = None
self.cur = None
self.connect(path)
def __del__(self):
self.cur.close()
self.conn.close()
def connect(self, path='DB/myDB.db'):
... |
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'lessons'
urlpatterns = [
path('', views.index, name = 'index'),
path('subjects/<int:subject_id>', views.subject, name = 'subject'),
path('itype/<int:subject_id>/<int:itype_id>', views.itype, name = 'ity... |
# -*- coding: utf-8 -*-
import QFramework
import ROOT
def parseSystematicsList(version, config):
vars_path = ROOT.TString()
if not config.getTagString(version, vars_path):
return list()
vars_full_path = QFramework.TQPathManager.findFileFromEnvVar(vars_path, "CAFANALYSISSHARE")
vars = list()
... |
# Generated by Django 2.2.5 on 2019-09-02 14:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
... |
#
# Copyright (c) 2018 Eric Faurot <eric@faurot.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTH... |
# Generated by Django 3.1 on 2020-11-10 05:23
from django.db import migrations, models
import ecom.models
class Migration(migrations.Migration):
dependencies = [
('ecom', '0024_auto_20201110_1111'),
]
operations = [
migrations.AddField(
model_name='item',
name='e... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='pyrosenv',
version='0.0.4',
author='Omri Rozenzaft',
author_email='omrirz@gmail.com',
url='https://github.com/omrirz/pyrosenv.git',
description='Set an environment for easy work with R... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, cookielib, urllib, urllib2, time
#-----------------------------------------
serv_id = '1'
siteUrl = 'zabava-htlive.cdn.ngenix.net'
httpSiteUrl = 'http://' + siteUrl
#sid_file = os.path.join(os.getcwd(), siteUrl+'.sid')
#cj = cookielib.FileCookieJar(sid_... |
a = "hello"
b = 100
try:
c =a+b
print(c)
print("try block get executed!!!!")
except:
d = a+str(b)
print(d)
print("except block get executed!!!!")
else:
print("else block get executed!!!!")
finally:
print("finally block get executed!!!!") |
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, request
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import os
import os.path as path
import json
import csv
from scraper import scrape
from geocoder import get_lat_long
from o... |
from SingletonMeta import SingletonMeta
class IO(metaclass=SingletonMeta):
openFiles = []
def readFileIntoLines(self, file_name):
f = open(file_name, 'r')
self.openFiles.append(f)
return f.readlines()
def writeLineToFile(self, file_name, lines):
f = open(file_name, 'w'... |
import pandas as pd
import matplotlib.pyplot as plt
w13 = pd.read_csv("2013Weather.csv", header = 22)
w14 = pd.read_csv("2014Weather.csv", header = 22)
w15 = pd.read_csv("2015Weather.csv", header = 22)
w16 = pd.read_csv("2016Weather.csv", header = 22)
w17 = pd.read_csv("2017Weather.csv", header = 22)
w = w13.append(... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pywt
'''
#Importing stock data
import yfinance as yf
from datetime import date,datetime,timedelta
ticker = '^GSPC'
first_day = datetime(2000, 1, 3)
last_day = datetime(2019, 7, 1)
data = yf.Ticker(ticker).history(interval = '1d', start=fi... |
import os
import cv2
import numpy as np
caminho_lfw = "treinamento" #caminho da base de treinamento LFW
nomes = os.listdir(caminho_lfw) #nomes das pessoas
nomes_auxiliar = []
def aplicaLBP (img):
cinza = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cascata = cv2.CascadeClassifier('lbpcascade_fronta... |
# -*- coding: utf-8 -*-
import unittest
import sys
class BaseTestCase(unittest.TestCase):
def tap(self, out):
sys.stderr.write("--- tap output start ---\n")
for line in out.splitlines():
sys.stderr.write(line + '\n')
sys.stderr.write("--- tap output end ---\n")
class TestCas... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 19:06:53 2016
@author: caiyi
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 19:06:53 2016
@author: caiyi
"""
"""
counting sheep
"""
def write_res(file_name, res):
with open(file_name,'w') as f:
res_str = ''
for i in ran... |
def calculate_rectangle_area(height, width):
## Todo: update `None` to contain the formula for `rectangle_area`
height = float(input("Enter the height"))
width = float(input("Enter the width"))
rectangle_area = height * width
return rectangle_area
print ("The rectangle area is:", rectangle_a... |
#!/usr/bin/env python
# Config stub that all modules can share, instead of reloading..
import configparser
import logging
import os
general = {}
payments = {}
pinpayments = {}
stripe = {}
smartwaiver = {}
# What if we just build one config object, instead?
Config = configparser.ConfigParser()
inifile='makeit.ini'
i... |
# 뱀과 사다리
import sys
from collections import deque
input = sys.stdin.readline
# 지도
board = []
visited = [False] * 110
for i in range(0,110) :
board.append([i,i])
n, m = map(int,input().split())
for _ in range(n+m) :
x, y = map(int,input().split())
board[x][1] = y
#print(board)
li = de... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from app import db
engine = create_engine('sqlite:///user.db', echo=True)
db_session = scoped_session(sessionmaker(autocomm... |
import os
import cv2
import pickle
import imutils
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as prfs
from tensorflow.keras.optimizers import Adam, SGD
from tensorflo... |
from gamelib import event
B_LEFT = 1 #to 3a
B_TOP = 2 #to 3g
TRIG = 89
DOOR = 71
TURRETS = [72, 73]
def go_top():
event.move_player(0, -50)
event.go_to_level('level_3g', True, True, True)
event.stop_music()
def go_left():
event.move_player(50, 0)
event.go_to_level('level_3a', True, T... |
a=input().split()
min=1000
for i in range(len(a)):
s=int(a[i])
if (s<min)and(s>0):
min=s
print(min) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 13:06:48 2019
@author: Ying-Fang.Kao
Pymc3 quick start
"""
%matplotlib inline
import numpy as np
import theano.tensor as tt
import pymc3 as pm
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_context('notebook')
plt.style.use('seaborn-darkgrid')
print(... |
import time
import traceback
from typing import Dict
from bearlibterminal import terminal
from debug import Debug
from engine.input.long_notation_parser import LongNotationParser
from engine.input.notation_parser import NotationParser, InvalidNotationException
from engine.map.components.board import Board, IllegalMov... |
# -*- coding: utf-8 -*-
import pandas as pd
def main():
# 1次元配列
data = pd.Series([158, 157, 157], index=['miho','saori','yukari'])
print(data)
if __name__ == "__main__":
main()
|
import cv2
import numpy as np
#调用笔记本内置摄像头,所以参数为0,如果有其他的摄像头可以调整参数为1,2
class Camera:
def __init__(self,NO):
self.cap = cv2.VideoCapture(NO)
self.face_cascade = cv2.CascadeClassifier("/anaconda3/pkgs/libopencv-3.4.2-h7c891bd_1/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
self... |
import requests, xmltodict, json
class PortalData:
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
def get_geonames(self):
geonames_url = 'http://api.geonames.org/extendedFindNearby?lat='+self.latitude+'&lng='+self.longitude+'&username=ondr... |
#!/usr/bin/python
import xmlrpclib
PASSWORD = 'test'
USER = 'admin'
# Get user_id and session
s = xmlrpclib.ServerProxy ('http://%s:%s@192.168.30.153:8069/test' % (USER, PASSWORD))
# Get the user context
context = s.model.res.user.get_preferences(True, {})
# Print all methods (introspection)
methods = s.system.list... |
#!/usr/bin/env python3
import sys
# Return the trie built from patterns
# in the form of a dictionary of dictionaries,
# e.g. {0:{'A':1,'T':2},1:{'C':3}}
# where the key of the external dictionary is
# the node ID (integer), and the internal dictionary
# contains all the trie edges outgoing from the correspo... |
import numpy as np
import pandas as pd
def main():
c_cols = ['2user_id','3ISBN','4bookrating']
current_user_data = pd.read_csv('book-dataset/BX-Book-Ratings.csv', sep=';', names=c_cols,encoding='latin-1')
print current_user_data['2user_id'][0]
d = {'1slno': [0], '2user_id': current_user_data['2u... |
import os
import csv
import json
import copy
class Persist:
def __init__(self, dir = None):
self.__set_filename()
self.dir = self.set_dir(dir)
self.fullpath = None
self.format = 'csv'
def __set_filename(self):
self.filename = self.tablename +'.csv'
def __define_fo... |
import tensorflow as tf
from layers import Layers
class HAN:
def __init__(self,config):
self.config = config
self.layers = Layers(config)
def build_HAN_net(self):
X_id = self.layers.X_input()
senti_Y = self.layers.senti_Y_input()
table = self.layers.word_embedding_table... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2014 Pexego Sistemas Informáticos All Rights Reserved
# $Marta Vázquez Rodríguez$ <marta@pexego.es>
#
# This program is free software: you can redistribute it and/or modify
# it unde... |
# Create your views here.
#IMPORT models
from .models import Movie,ApiUsers
#IMPORT LIBRARIRES/FUNCTIONS
#from django.shortcuts import render , HttpResponse
from django.http import JsonResponse
import json
from firstapp.customClasses import *
#IMPORT DJANGO PASSWORD HASH GENERATOR AND COMPARE
from django.contrib.auth.... |
def midpoint_integration(f, a, b, n=100):
h = (b - a)/float(n)
I = 0
for i in range(n):
I += f(a + i*h + 0.5*h)
return h*I
from math import *
import sys
from scitools.StringFunction import StringFunction
f_formula = sys.argv[1]
a = eval(sys.argv[2])
b = eval(sys.argv[3])
if len(sys.argv) >= 5:
... |
from __future__ import annotations
from abc import abstractmethod
from meiga import BoolResult
from petisco.base.domain.message.domain_event import DomainEvent
from petisco.base.domain.message.message_subscriber import MessageSubscriber
class DomainEventSubscriber(MessageSubscriber):
"""
A base class to mo... |
import requests
from bs4 import BeautifulSoup, Tag, NavigableString
from urllib.parse import urljoin
def scrape_mccormick_courses(dept="computer-science"):
# download the index page
index_url = "https://www.mccormick.northwestern.edu/"+dept+"/courses/"
index_page = requests.get(index_url)
# load the p... |
#10 진수, 2진수, 16진수 표기하기
num = 10
b_num = 0b1010
h_num = 0xa
print(num)
print(b_num)
print(h_num)
|
class Calculator:
def __init__(self, number1, number2, result, chc, div0):
self.a = number1
self.b = number2
self.result = result
self.choice = chc
self.d = div0
def add(self):
self.result = self.a + self.b
return self.result
def sub(self):
... |
import numpy as np
import pandas as pd
import unittest
from SetBinDiscretizer import SetBinDiscretizer
class TestSetBinDiscretizer(unittest.TestCase):
def test_1D_split(self):
X = [[-1], [-1], [0], [0], [0], [1], [1], [1], [1]]
est = SetBinDiscretizer(bin_edges_internal=[[-0.5, 0.5]], encode='or... |
#
# meteo-station obv BME280 Digitale Barometer Druk en Vochtigheid Sensor Module
#
# bron: https://www.tinytronics.nl/shop/nl/sensoren/temperatuur-lucht-vochtigheid/bme280-digitale-barometer-druk-en-vochtigheid-sensor-module
# Een zeer compacte barometer die werkt via I2C of SPI. De BME280 is een 3-in-1 module
# die t... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length<2:
return 0
profit = 0
currentBuy = -1
for i in range(length):
current = prices[i]
#Buy
if currentBuy =... |
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.popstack = []
self.pushstack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
if not self.pushstack:
while self.pops... |
# -*- coding: utf-8 -*-
"""
gites.walhebcalendar
Licensed under the GPL license, see LICENCE.txt for more details.
Copyright by Affinitic sprl
"""
from zope.configuration import xmlconfig
def parseZCML(package, configFile='configure.zcml'):
context = xmlconfig._getContext()
xmlconfig.include(context, configF... |
import os
class atm:
def __init__(self):
self.__account= {}
self.__counter = 0
def ReturnDetails(self, account_number):
return self.__account.get(account_number)
def CreateAccount(self, name, balance, pin):
details = {'name':name, 'balance':balance, 'pin':pin}
temp... |
from typing import Optional
from datetime import datetime
from pydantic import BaseModel
import uuid as pyuuid
class GenericData(BaseModel):
name: str
timestamp: datetime
optionaldata: Optional[str]
jsondata: dict
uuid: pyuuid.UUID
class GPS(GenericData):
class Config:
orm_mode = Tru... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import json
import glob
import codecs
import unicodedata
from scrapy.selector import Selector
import common
maps = dict(zip(['in_individual', 'in_profit', 'in_party', 'in_civil', 'in_anonymous', 'in_others', 'in_total', 'out_personnel', 'out_propagate... |
__author__ = 'venth'
import itertools
import sys
import unittest
import superdigit
class SuperdigitTest(unittest.TestCase):
def test_every_single_digit_has_equal_superdigit(self):
# given single digits
single_digits = [digit for digit in xrange(0, 9)]
# when super digit is calculated f... |
from .statement import Statement
from functions import Function
def functiondef(c, m):
"""Function definition. For instance:
function myMethod(ax) returns dx {
; code
}
"""
f = Function(
name=m.group(1),
params=m.group(2),
returns=m.group(3)
)
# ... |
# -*- utf8 -*-
from PIL import Image
from PIL.ExifTags import TAGS
import matplotlib.pyplot as plt
import os
import pandas as pd
# exif info from PIL
doc1 = """
ExifVersion
ComponentsConfiguration
ExifImageWidth
DateTimeOriginal
DateTimeDigitized
ExifInteroperabilityOf... |
import os
import cv2
import argparse
import numpy as np
import albumentations
import albumentations.pytorch
import multiprocessing as mp
import torch.nn.functional as F
import segmentation_models_pytorch as smp
from importlib import import_module
from prettyprinter import cpprint
import torch
from src.utils import s... |
from django.contrib.auth import get_user_model
from django.db import models
from rest_framework.authtoken.models import Token as DRFAuthTokenModel
from django.utils.translation import ugettext_lazy as _
# Create your models here.
from hospital.core.models import hospitals
USER = get_user_model()
class AuthToken(DRF... |
s, n, m = map(int, input().split(' '))
keyboards = list(map(int, input().split(' ')))
usbs = list(map(int, input().split(' ')))
nice = -1
for keyboard in keyboards:
for usb in usbs:
combo = keyboard + usb
if s >= combo and nice < combo:
nice = combo
print(nice)
|
from django.urls import path, include
from .views import (
RegistrationView,
PurchaseView,
WithdrawalView,
AccountView,
)
urlpatterns = [
path('oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
# account related
path('register/', RegistrationView.as_view(), name='re... |
# coding = utf-8
'''
封装 requests 方法
返回response
'''
'''
调试接口
1.4、获取一个城市所有监测点的NO2数据
地址 http://www.pm25.in/api/querys/no2.json
方法 GET
参数
* city:必选
* avg:可选
* stations:可选
返回
一个数组,其中每一项数据包括
* aqi
* area
* no2
* no2_24h
* position_name
* primary_pollutant
* quality
* station_code
* time_point
注意有些接口是放返回页面格式会出现乱码的... |
from yamale.validators.constraints import Constraint
from email.utils import parseaddr
class EmailDomain(Constraint):
keywords = {'domain': str}
fail = '%s does not contain a valid domain. The acceptable domain value is %s'
def _is_valid(self,value):
name, email_addr = parseaddr(value)
email_parts = email_addr... |
from .models import Answer
from django import forms
class Answerform(forms.ModelForm):
class Meta:
model = Answer
fields=["answer","question"]
|
# -*- coding: utf-8 -*-
"""
Created on 12/1/2018
@author: Grace Wu
PURPOSE: This script creates Supply Curves for RESOLVE for Wind, PV, and Geothermal
Previous filename: RESOLVEsupplyCurve_py3_112918.py
"""
##--------------------------------Preamble ----------------------------------
import arcpy
import numpy
impor... |
#! /usr/bin/env python
import os,sys
from time import strftime
fn = raw_input("file to create: ")
if os.path.exists(fn):
print "file exists!"
sys.exit(1)
hg = raw_input("Header guard: ")
f = open(fn , 'w')
f.write("""//
// """ + fn + """: redox language
// created """ + strftime("%Y-%m-%d %H:%M:%S") + """
// creat... |
# What is the largest prime factor of the number 600851475143?
NUMBER = 600851475143
primes = [2]
def get_max():
for num in range(3, int(NUMBER / 2), 2):
for i in range(3, int(num / 2), 2):
if num % i == 0 or NUMBER % num != 0:
break
else:
if num > primes[-... |
from matplotlib import pyplot as pl
def parser(name):
'''
Parse the output files for part 3
inputs:
name = The name of the file containing data
outputs:
'''
fpr = []
tpr = []
with open(name) as file:
for line in file:
values = line.strip().split(',')
... |
import torch
import torch.nn as nn
import torch.nn.init as init
import numpy as np
from torch.nn.modules.loss import _Loss
import math
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
... |
import pandas as pd
from requests import get
import sys
pathtk = r"D:\PPP"
sys.path.insert(0, pathtk)
import bfsearch
sp = {"sep":"\n\n", "end":"\n\n"}
base_url = "http://api.census.gov/data/timeseries/idb/5year"
secret_key = bfsearch.key
parameters = {"key": secret_key,
"get": ",".join(["NAME", "PO... |
## ========================================================================= ##
## Copyright (c) 2019 Agustin Durand Diaz. ##
## This code is licensed under the MIT license. ##
## hud_steering.py ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.