text stringlengths 38 1.54M |
|---|
#https://www.runoob.com/python/python-exercise-example19.html
#一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
##分析
# 1.整体流程:算出因数分解,因数求和判断是否符合条件,循环
from functools import reduce
tag = True
inputNumber = 100
Dividend = inputNumber
Divisor = 1
reslut = []
perfect = []
#因数分解
def fenjie(Dividend=28,Divisor = 1):
... |
import sys
import re
import argparse
#Regexes for step entities
def GetRegexFromFuncName(step_func):
if step_func == 'closed_shell':
return 'closed_shell\(.*,.*\((.*)\).*\)'
if step_func == 'open_shell':
return 'open_shell\(.*,.*\((.*)\).*\)'
elif step_func == 'advanced_face':
retur... |
# coding=utf-8
"""
根据关键词抓取人群属性,包括年龄分布和性别分布
"""
import json
import random
import time
from urllib.parse import quote
import requests
from requests抓取百度指数.DBHelper import DBHelper
# 固定时间段为1个月,手动更改日期段列表
from requests抓取百度指数.config import COOKIES
date_range_list = [
(20180601, 20180701),
(20180701, 20180801),
... |
#!/usr/bin/env python
from lsm303d import lsm303d
from lps25h import lps25h
from l3gd20h import l3gd20h
from ls20031 import ls20031
from kalman import kalman
from numpy import *
from threading import Thread
from numpy.linalg.linalg i... |
from .summarize_recordings import summarize_recordings
from .sort_recordings import sort_recordings
from .sort_recordings import multi_sort_recordings
from .summarize_sortings import summarize_sortings
from .compare_sortings_with_truth import compare_sortings_with_truth, GenSortingComparisonTable
from .aggregate_sortin... |
from imio_survey.queriers import IQuerier
from arcrest.server import MapService
from arcrest.geometry import Envelope, Polygon, Point, Polyline, Multipoint
from django.utils import simplejson
if __name__ == "__main__":
#url = "http://geoservices.wallonie.be/arcgis/rest/services/NATURA2000/NATURA2000_EP/MapServer"... |
import hashlib
def working():
return True
cached_items = []
class CacheObject(object):
"""
An object to hold Cached Things
Attributes:
Key: a hash of the value, can be set by hand, but not advised
Value: supplied when creating calling the set method
"""
def __init__(self... |
import re
import json
import requests
from bs4 import BeautifulSoup as bs4
def codeforces_status(handle) :
RContest = set()
VContest = set()
SolvedInContest = set()
Upsolved = set()
Wrong = set()
url = "https://codeforces.com/api/user.status?handle="+handle
res = requests.get(url)
if res.status_code != 20... |
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import os
Bot = commands.Bot(command_prefix= "..")
@Bot.event
async def on_ready():
game = discord.Game(r"DSHBot.io | ..help")
await Bot.change_presence(status=discord.Status.online, activity=game)
@Bot.event... |
"""
This file is used for visualization. No big changes should be required to this file.
The only function that can be updated is map_running. You may add additional info to be printed such as a/c in the radar range yourself.
Visualization code in this file is based on graduation work by K.Fines and T. Noortman.
"""
i... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
#
# Copyright (c) Jason Young (杨郑鑫).
#
# E-Mail: <AI.Jason.Young@outlook.com>
# 2020-11-17 11:37
#
# This source code is licensed under the WTFPL license found in the
# LICENSE file in the root directory of this source tree.
import gc
import torch
import numpy
import ... |
#!/usr/bin/python
# adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py
import sys, termios, tty, os, time
from math import *
import pigpio
import threading
import RPi.GPIO as GPIO
from ina219 import INA219, DeviceRangeError
from rockBlock import rockBlockProtocol
#import dht11
... |
from django.urls import path
from . import views
app_name = "subdataset_modification"
urlpatterns = [
path('get_columns_with_missed_values', views.get_columns_with_missed_values,
name='get_columns_with_missed_values'),
path('delete_rows_with_missed_values', views.delete_rows_with_missed_v... |
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import numpy as np
from mpl_toolkits import mplot3d
from Bezier import Bezier
from numpy import array as a
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
#Reto Interpolacion de mortero con curvas de Bezier
#Juan C... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 18 10:49:57 2019
@author: Tristan Guest
attempt #2: track one cobble at a time
"""
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
homechar = "C:\\"
tide = "tide19"
vidspec = "vid_1540304255"
imgdir = os.path.join(homechar, "Projects", "Adv... |
N, M = map(int, input().split())
c = [0] * N
for _ in range(M):
a, b = map(int, input().split())
c[a - 1] += 1
c[b - 1] += 1
print(*c, sep='\n') |
# Dependencies
import requests as req
url = "http://www.omdbapi.com/"
movies = [
('Aliens', 'Director', 'The director of Aliens was '),
('Gladiator', 'Rated', 'The rating of Gladiator was '),
('50 First Dates', 'Year', 'The movie 50 First Dates was released in '),
('Moana', 'Writer', 'The writer of Moana was '),
... |
from abc import ABC, abstractmethod
import json
import logging
import requests
from fastapi import HTTPException
from msal import ConfidentialClientApplication
from oauthlib.oauth2 import WebApplicationClient
from starlette.responses import RedirectResponse
from backend import cache
from backend import config
from ba... |
import datasets
import load_data
import numpy as np
import multiprocessing
import extract_data
from numba import njit
from scipy import optimize
from sklearn.cluster import KMeans
from tqdm.auto import tqdm
from multiprocessing import Queue
from cmaes import CMA
from collections import Counter
parameter_index = 3
trai... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 liangliang <liangliang@Liangliangs-MacBook-Air.local>
#
# Distributed under terms of the MIT license.
class Solution(object):
def solveSudoku(self, brd):
"""
:type board: List[List[str]]
:rtype: None Do not... |
# -*- coding: utf-8 -*-
# @Time : 2020/5/7 0:52
# @Author : BaoBao
# @Mail : baobaotql@163.com
# @File : add_threading.py
# @Software: PyCharm
import threading
def thread_job():
print('this is added Thread, number is %s'%threading.current_thread())
def main():
added_thread = threading.Thread(target=threa... |
import json
import asyncio
from sanic import Sanic
from sanic import response
app = Sanic(__name__)
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
queue = asyncio.Queue()
@app.websocket('/subscribe')
async def subscribe(request, ws):
while True:
data = await queue.get(... |
# Generated by Django 2.1.4 on 2019-01-17 09:19
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('core', '0008_province'),
]
operations = [
migrations.CreateModel(
name='Municipalit... |
#!/usr/bin/env python
import sys
import os
import subprocess
def get_nimissiontime_mjdtt(mjd_tt):
"""
aetimecalc version 2007-05-14
Written by Y.ISHISAKI (TMU)
Built on ANL HEADAS converter 1.81 for ANL version 1.81
any of prompt/mission/date/date_tt/mjd/mjd_tt/yday[date_tt] date
date string in UTC, 'yyyy-mm-... |
import numpy as np
import matplotlib.pyplot as plt
import math
import gym
from multiprocessing import Process, Lock , Queue
class Discretizer:
discretization = None
base = None
ranges = None
validDims = None
maxSteps = 500
task = None
env = None
def __init__(self, task):
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('registration', views.registration),
path('form', views.form),
path('auth', views.auth),
path('log_out', views.log_out),
]
|
from keras.layers import Input, Dense, Dropout, Lambda, Concatenate, Subtract, Add, Multiply, Activation
from keras.models import Sequential, Model
from keras.optimizers import Adam
import keras.backend as K
import numpy as np
import time
from utils import Log
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d i... |
# -*- coding: utf-8 -*
# 输入文件grammer.txt包含LL(1)文法
# 输出first(X),follow(X)X是非终结符
# 约定:大写字母表示非终结符,其他表示终结符,空用@表示
# 输入的都是合法的LL(1)文法,一个产生式一行,即如果有 | 的话要分成几个产生式
# 样例就看grammer.txt吧...
from genarate_follow_table import *
for X in nonterminal :
follow[X].discard('@')
print 'first(' + X + ') = ', first[X], '\t... |
# -*- coding: utf-8 -*-
import os
import psycopg2
import urllib.parse
class Database:
cur = None
conn = None
# connect to database
def __init__(self, database_url):
urllib.parse.uses_netloc.append('postgres')
url = urllib.parse.urlparse(database_url)
self.conn = psycopg2.conne... |
import numpy as np
import random
import matplotlib.pyplot as plt
runs = 1000
d = 2
def prob8_9_10():
error = 0
points = 1000
for q in range(runs):
xs = np.random.uniform(-1,1, (points, d))
xs = np.c_[np.ones(points), xs]
out_sample = np.random.uniform(-1,1, (points, d)... |
"""A program for the supermarket."""
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3}
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15}
def supermarket():
"""A program for the supermarket."""
sell_all_total = 0
groceries = [... |
import sqlite3
class Model:
def __init__(self, db_name):
self.db = sqlite3.connect(db_name)
def check_code(self, code):
c = self.db.cursor()
query = "SELECT * FROM all_students WHERE code='%s'" % str(code)
c.execute(query)
result = c.fetchall()
c.close()
... |
"""
Test auth function.
"""
import unittest
from app import create_app, db
from app.models import User, Post, Follow, Permission, permissions_dict
import time
from datetime import datetime
import hashlib
class UserModelTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
def ... |
from .Constants import *
from .Validator import *
import requests
from requests.exceptions import *
def ErrCallBackMaker(errType):
return {"success" : False, "type" : errType, "reason" : errorMsg[errType]}
def SuccessCallBackMaker(html):
html = str(html)
return {"success" : True, "html" : html}
def WebThief(url):... |
import sys
from collections import deque
input = sys.stdin.readline
N, K = map(int, input().split())
seat = deque()
answer = []
for i in range(1, N+1):
seat.append(i)
while len(seat) >= 1:
for _ in range(K-1):
seat.append(seat.popleft())
answer.append(seat.popleft())
print('<%s>' % ', '.join(map(... |
#!/usr/bin/env python
# encoding: utf-8
# @author: liusir
# @file: exception_demo_14.py
# @time: 2020/9/20 4:05 下午
import requests
from requests.exceptions import MissingSchema, RequestException
try:
response = requests.get(url='www.baidu.com')
except MissingSchema as e:
print('https/http前缀没加')
except Connect... |
import uuid
from django.conf import settings
from django.contrib.auth import login, authenticate, update_session_auth_hash, logout, get_user_model
from django.core.mail import send_mail
from django.db import transaction
from django.shortcuts import render
from django.template import loader
from django.urls import reve... |
import globes
import os
import subprocess
import memo
import re
#level 1 indentation
def debug( s ) : globes.debug( s, 1 )
#######################################################################
############ Plink #############################################
###################################################... |
import sqlite3
import click
from dataclasses import dataclass
import datetime
import dropbox
import initialize
# Click uses its own echo function. It's importants only if using ASCII colors
connector = sqlite3.connect("contact_book.db")
@dataclass
class Contact:
""" The class is used to customize the string re... |
# Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e soma(). A primeira função vai sortear 5 números e vair colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores PARES sorteados pela função anterior.
import time
import random
def sorteia():
... |
import argparse
import sys
import json
from io import open
from src import FBCrawler
def usage():
return """
python main.py
"""
def arg_required(args, fields=[]):
for field in fields:
if not getattr(args, field):
parser.print_help()
sys.exit()
def create_group(username, ... |
# encoding=utf-8
from django.shortcuts import render, redirect
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def index(request):
return render(request, 'index.html')
def login(request)... |
"""
Copyright (c) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
import sys
def flip(string, pos):
if string[0] == '-':
new = ""
for num in range(pos, -1, -1):
if string[num] == '+':
new += '-'
else:
new += '+'
ans = new[0:pos + 1] + string[pos + 1:]
return (ans, 1)
else:
... |
# coding: utf-8
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 1:
return strs[0]
result = None
m = None
for s in strs:
if result == None:
r... |
from inspect import signature
import typing
from typing import List
import logging
import inspect
from pydantic import create_model, ValidationError, StrictStr, StrictInt
from typeguard import typechecked
#============================================================
class EnforcePydanticTypes(type):
__slots__... |
# these two lines are to support type hints
from __future__ import annotations # this works only for python 3.7 and above
from typing import List
#This is an enum example . An enum is useful when we want to restrict the value of a string ( as an example )
from enum import Enum
class Sex(Enum):
MALE = "M"
FEM... |
import pandas as pd
import os
from collections import namedtuple
from strategy.strategy import Exposures, Portfolio
from strategy.rebalance import get_relative_to_expiry_instrument_weights, \
get_relative_to_expiry_rebalance_dates, get_fixed_frequency_rebalance_dates
from strategy.calendar import get_mtm_dates
de... |
import os
import lyric_config
import logging
from gensim.models import word2vec
from pipes import quote
import scipy.io.wavfile as wav
import numpy as np
from config import nn_config
import parse_files
import config.nn_config as nn_config
conf = lyric_config.lyric_conf()
def getdict(train = False):
binfilename = c... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Calculating mean
def mean(arr):
sum= np.sum(arr)
mean= sum/arr.shape[0]
return mean
#Calculating standard deviation
def std_dev(arr):
var= np.sum(np.subtract(arr, mean(arr))**2, axis=0)/(arr.shape[0]-1)
std_dev= np.sqrt(var)
return std_dev... |
#! /usr/bin/env python
# from wsgiref.simple_server import make_server
import generate_html
import urlparse
import simplejson
import convert
import db
dispatch = {
'/' : 'index',
'/recipes.html' : 'recipes',
'/inventory.html' : 'inventory',
'/liquor_types.html' : 'liquor_types',
'/convert.html'... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Rohit Lodha
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
from collections import defaultdict
from typing import Counter, List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
words.sort(key=len)
temp = ... |
from django.apps import AppConfig
class PortalConfig(AppConfig):
name = 'app'
verbose_name = "Корпоративный портал" |
import numpy as np
from PIL import Image
import cv2
import os
import pandas as pd
def printview(a):
for i in range(16):
for j in range(24):
if(a[i][j]==0):
print(' ',end='')
else:
print('* ',end='')
print('')
fin = np.zeros((1... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
img_shape=(150,150)
data_shape=(150,150,3)
def getdataset(path_dir=''):
if path_dir=='':
return -1,None,None
train_ds=tf.keras.preprocessing.image_dataset_from_directory(
path_dir,
validation_split=0.2,
subset='training',
... |
'''
Main routes
'''
from fastapi import APIRouter
from app.web import chat
from app.web import index
from app.web import api
from app.web import ws
from fastapi.middleware.cors import CORSMiddleware
routers = APIRouter()
routers.include_router(chat.router, prefix="", tags=["chat"])
routers.include_router(index.route... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if (not p and q) or (p and not q):
return False
... |
from flask import Flask, request, render_template
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
from show_all import load_all_from_mysql
from show_id import load_one_from_mysql
app = Flask(__name__)
app.secret_key = 'dklsdfjs... |
import iris.coord_categorisation
import matplotlib.style as style
from cf_units import Unit
import iris.quickplot as qplt
import iris.plot as iplt
import matplotlib.pyplot as plt
import iris.analysis as ia
import numpy as np
style.use("seaborn")
##### region Parse
# Pull in data from file
eastward_wind = iris.load('... |
# this is the reddit rip module
import praw
class PullCategory(praw.Reddit):
"""
This class is a blueprint for various instances of
sending specific things to Telegram. Child to praw.Reddit class
"""
def __init__(self, subredt="all", num_urls=4):
self.subredt = subredt
... |
import time
from django.utils.crypto import get_random_string
from celery import shared_task
@shared_task
def create_random_word():
random_word = get_random_string(12)
return '{}'.format(random_word)
@shared_task
def create_random_word_long():
time.sleep(60)
random_word = get_random_string(12)
... |
from rest_framework import routers
from .views import TaskViewSet
router = routers.DefaultRouter()
router.register(r'tasks', TaskViewSet)
urlpatterns = router.urls
|
from googletrans import Translator
import sys
def translate_text(input_file, output_file, target_language):
# Read the content from the input text file
with open(input_file, 'r', encoding='utf-8') as file:
text = file.read()
# Create a Translator object
translator = Translator()
... |
#1
def solution(n, arr1, arr2):
answer = []
for i in range(n):
tmp = bin(arr1[i] | arr2[i])
tmp = tmp[2:].zfill(n)
tmp = tmp.replace('1', '#').replace('0', ' ')
answer.append(tmp)
return answer
#2
def solution(n, arr1, arr2):
answer = []
for i, j in zip(arr1, arr2):... |
# Utilities for authn/z
import base64
import json
import os
import re
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from flask import g, request, abort
from flask_restful import Resource
import jwt
from config import Config
from errors import PermissionsExcept... |
class User:
def __init__(self, name, email, branch, balance):
self.name = name
self.email = email
self.account = BankAccount(branch, balance)
def make_deposit(self, amount):
self.account+= amount
return self
def make_withdrawal(self, amount):
self.account-= ... |
import re
from types import SimpleNamespace
from bs4 import BeautifulSoup
from requests import Session
class MoodleSession:
def __init__(self, account):
self._session = None
self._account = account
self._logout_url = None
self._test_url = 'https://moodle.uni-heidelberg.de/user/pro... |
#coding=utf-8
import requests
from collections import defaultdict
import json
import re
from urllib.parse import urlparse, parse_qs, unquote
QUALITY_PROFILES = {
# flash
5: ('flv', '240p', 'Sorenson H.263', 'N/A', '0.25', 'MP3', '64'),
# 3gp
17: ('3gp', '144p', 'MPEG-4 Visual', 'Simple', '0.05', 'AAC... |
# -*- coding=UTF-8 -*-
# pyright: strict, reportTypeCommentUsage=none
from __future__ import absolute_import, division, print_function, unicode_literals
import nuke
import wulifang.nuke
from wulifang._util import (
workspace_path,
cast_str,
)
nuke.pluginAddPath(cast_str(workspace_path("plugins")))
# TODO: fu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.ScenicInfo import ScenicInfo
class PaginationScenicInfo(object):
def __init__(self):
self._page_no = None
self._page_size = None
self._scenic_info = N... |
#
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counter = collections.Counter(nums)
ans = 0
for k, v in counter.items():
if k + 1 in counter:
ans = max(ans, v + counter[k + 1])
return ans
|
# Structurally Constrained Recurrent Network (SCRN) Model
#
# This gives an implementation of the LSTM model for comparison with the SCRN model given in Mikolov et al. 2015,
# arXiv:1412.7753 [cs.NE], https://arxiv.org/abs/1412.7753 using Python and Tensorflow.
#
# This model is superceded by the Delta-RNN model given ... |
from django.contrib import admin
from apps.patient.models import Patient
admin.site.register(Patient)
|
# Copyright 2018 The Batfish Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from functools import partial
from matplotlib import pyplot as plt
import numpy as np
from numpy.polynomial import polynomial as pl
from numpy.polynomial.polynomial import Polynomial
plt.rcParams["patch.force_edgecolor"] = True
N = 13
x = np.array([-(N % 3), -(N % 3) + 0.1, -(N % 3) + 0.3, -(N % 3) + 0.45, -(N % 3) + ... |
__author__ = ''
__version__ = 'latest'
__doc__ = """ this is the third file to be run
create 'feature_vectors' directory to store generated feature files
"""
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import scipy.io
train = pd.read_csv('./data/preprocessed_training_docs.csv', )... |
#!/usr/bin/python3
from models.engine.fileStorage import FileStorage
storage = FileStorage()
storage.reload() |
from flask import jsonify,make_response
def ok(values,message):
res = {
'values': values,
'message': message
}
return make_response(jsonify(res)),200
def badRequest(values, message):
res = {
'values': values,
'message': message
}
return make_response(jsonify(r... |
from PyQt5.QtCore import QObject, pyqtSignal
import os
import socket
import json
import threading
from math import ceil
def leer_parametros():
with open("parametros.json", "r") as file:
return json.load(file)
class ClienteNet(QObject):
network_procesador_signal = pyqtSignal(dict)
def __init__(... |
import pytest
from jwst.pipeline.calwebb_detector1 import Detector1Pipeline
from jwst.tests.base_classes import BaseJWSTTest
@pytest.mark.skip
@pytest.mark.bigdata
class TestSloperPipeline(BaseJWSTTest):
input_loc = 'fgs'
ref_loc = ['test_sloperpipeline', 'truth']
def test_fgs_detector1_1(self):
... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_pulsedive"""
try:
from resilient import ImportDefinition
except ImportError:
# Support Apps running on resilient-circuits < v35.0.195
from resilient_circuits.util import ImportDefinition
def codegen_reload_data():
"""
... |
import os
dirpath = os.pardir
import sys
sys.path.append(dirpath)
import torch.utils.model_zoo as model_zoo
from torch.autograd import Variable
from torch.optim import lr_scheduler
import resnet_epi_fcr
import resnet_vanilla
from common.data_reader import BatchImageGenerator
from common.utils import *
class ModelA... |
import logging
from homeassistant.core import callback
from homeassistant.components.climate import ClimateEntity
from homeassistant.helpers.event import async_track_state_change
from homeassistant.components.climate.const import (
HVAC_MODE_OFF, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_DRY,
HVAC_MODE_FAN_ON... |
import random
import string
from datetime import date, datetime
from time import sleep
from typing import List, Optional
from conftest import create_group
from meetup_search.models.group import Event, Group
def generate_search_dict(
query: Optional[str] = None,
page: Optional[int] = None,
limit: Optional... |
import PySpice
import PySpice.Unit as U
from PySpice.Spice.Netlist import Circuit
import numpy as np
PySpice.Spice.Simulation.CircuitSimulator.DEFAULT_SIMULATOR = 'xyce-serial'
from configuration.configuration_manager import Configuration
from configuration.models import Models
from run_stages.common_run_stage impor... |
__author__ = 'achoudhary'
def mapy_plotter(var):
import operator
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.preprocessing import LabelEncoder
from mpl_toolkits.basemap import Basemap
train_df = pd.rea... |
#! /usr/bin/env python
import os,sys
import PMPformat as PMP
from rdkit import Chem
### Function to extract data to pmp
def ProcessGDMAdata(fname, multipole=2):
''' Process GDMA output
Return AtomPropDict{pname:[values..]}, MolPropDict{pname: value}'''
with open(fname) as f:
lines = f.readlines(... |
from tkinter import *
import base64
import sys
class GUIDemo(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.inputText = Label(self)
self.inputText["text"] = "Input:"
self.inp... |
# importing libraries
import os
import requests, json
from flask import Flask, request, Response, jsonify
from flask_mail import Mail, Message
from datetime import datetime
from werkzeug.security import safe_str_cmp
from db import db
from models.sessions import Session
from models.card import Card
from models.error... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-11 12:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('enot_app', '0105_card_published'),
('enot_app', '0105_merge_20170608_1355'),
]
oper... |
from rest_framework import views
from rest_framework.request import Request
from rest_framework.response import Response
from .domain.behavior.codezine_behavior import CodezineBehavior
from .domain.behavior.gizmodo_behavior import GizmodoBehavior
from .domain.item_list import ItemList
from .serializers import CodezineS... |
# coding: utf-8
from test.test_catalog import TestCatalogBase
class TestCatalogLayerGroup(TestCatalogBase):
def test_getlayergroups(self):
# ws = self.catalog.get_default_workspace()
layersgroups = self.catalog.get_layergroups()
print("Layergroups: {}".format(layersgroups))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-03-13 15:09:08
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
class Solution(object):
def smallestK(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: Lis... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sup3rs3cr3t/', include(admin.site.urls)),
url(r'^',include('mysite.urls')),
url(r'^markdown/',include('django_markdown.urls')),
url(r'^blog/',include('posts.urls'... |
# coding:utf-8
import boto3
sns = boto3.client('sns')
def lambda_handler(event, context):
response = sns.publish(
TopicArn='arn:aws:sns:ap-northeast-1:{AcountId}:{Name}',
Message=u'Publishできました',
Subject=u'LambdaからのPublish'
)
return 'return Hello from Lambda'
|
# encoding:utf-8
#! python3
# readCensusExcel.py - Tabulates population and number of census tracts for each county.
import openpyxl,pprint,os
print('Opening workbook...')
print(os.getcwd())
wb=openpyxl.load_workbook('censuspopdata.xlsx')
sheet=wb['Population by Census Tract']
countydata={}
# TODO:Fill in countydata wi... |
# Generated by Django 2.0.2 on 2018-02-16 16:33
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',
field... |
"""
Contains classes for representing in excited states of some bosonic mode.
The creation/annihilation operators have a symbolic variable which can for example
be the frequency of the excited state.
"""
from collections import defaultdict
from itertools import permutations
from qualg.scalars import DeltaFunction
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.