content stringlengths 5 1.05M |
|---|
import numpy as np
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = -1
self.sum = 0
self.count = 0
def update(self, val, n=1):
if v... |
from leapp.libraries.actor import iscmodel
from leapp.libraries.common import isccfg
from leapp.models import BindFacts
def model_paths(issues_model):
paths = list()
for m in issues_model:
paths.append(m.path)
return paths
def get_facts(cfg):
facts = iscmodel.get_facts(cfg)
assert isinst... |
import numpy as np
import pickle
from ..util import BaseCase
from pygsti.objects import FullGaugeGroupElement, Basis, ExplicitOpModel, TPPOVM, UnconstrainedPOVM
import pygsti.construction as pc
import pygsti.objects.spamvec as sv
class SpamvecUtilTester(BaseCase):
def test_convert_to_vector_raises_on_bad_input(... |
def divide(l, direction):
if direction in ("F", "L"):
return l[: (len(l) // 2)]
elif direction in ("B", "R"):
return l[(len(l) // 2) :]
return None
def seat(code):
row = range(128)
i = 0
while i < 7:
row = divide(row, code[i])
i += 1
column = range(8)
j ... |
import numpy as np
# Too lazy to copy Q3 ans, so just predefine primes
primes = np.array([2,3,5,7,11,13,17,19])
buckets = np.zeros_like(primes)
def findFactors(x):
factors = []
for i in range(len(primes)):
p = primes[i]
while(x % p == 0):
x //= p
factors.append(i)
... |
#!/usr/bin/env python
#
# Copyright 2018 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import sys
import pytest
from yt_napari._data_model import InputModel, _store_schema
from yt_napari.schemas._manager import Manager
skip_win = "Schema manager is not for windows."
@pytest.mark.skipif(sys.platform == "win32", reason=skip_win)
def test_schema_version_management(tmp_path):
m = Manager(schema_db=... |
# -*- coding: utf-8 -*-
# Created by lvjiyong on 16/5/6
HOST = '192.168.0.1'
PORT = 8888
|
from ..broker import Broker
class AuthRoleBroker(Broker):
controller = "auth_roles"
def index(self, **kwargs):
"""Lists the available auth roles. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using this method is most eff... |
# -*- coding: utf-8 -*-
import yfinance as yf
import time
import numpy as np
from ..utils.time_utils import *
class Stock:
"""
This class allows to get data from the stock market
with an API
"""
def __init__(self, name, date, simulation_time, fixed_commission, prop_commission, moving_window, decr... |
import logging
import os
import requests
from ....core.reporting.utils import convert_svg_to_png, is_image, SVG_SUFFIX, PNG_SUFFIX
TELEGRAM_BASE_URL = os.environ.get("TELEGRAM_BASE_URL", "https://api.telegram.org")
class TelegramClient:
def __init__(self, chat_id: int, bot_token: str):
self.chat_id = ch... |
import ecg_plot
import argparse
import matplotlib.pyplot as plt
import preprocess
import os
import read_ecg
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Plot ECG from wfdb')
parser.add_argument('path', type=str,
help='Path to the file to be plot.')
pars... |
"""
ScalyMUCK has several base exceptions for the ScalyMUCK core and
ScalyMUCK modifications that may be loaded into the MUCK server.
This software is licensed under the MIT license.
Please refer to LICENSE.txt for more information.
"""
class ModApplicationError(Exception):
""" Generic exception for Sc... |
#!/usr/bin/python
#
# Copyright (c) 2020 by VMware, Inc. ("VMware")
# Used Copyright (c) 2018 by Network Device Education Foundation,
# Inc. ("NetDEF") in this file.
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above c... |
import math
import main
from graphics import *
window_width = 600
window_height = 400
class Road(object):
def __init__(self, inner_points=None, outer_points=None, distance_check_points=None,
start=None, back_check=None, finish=None, starting_direction=None):
self.win = GraphWin(title="Se... |
"""
Broadworks OCI-P Interface Exception Classes
Exception classes used by the API.
"""
import attr
@attr.s(slots=True, frozen=True)
class OCIError(Exception):
"""Base Exception raised by OCI operations.
Attributes:
message: explanation of why it went bang
object: the thing that went bang
... |
from sklearn.cross_validation import KFold
from sklearn.linear_model import LinearRegression, ElasticNet
from sklearn.datasets import load_boston
import numpy as np
boston = load_boston()
x = np.array([np.concatenate((v, [1])) for v in boston.data])
y = boston.target
FIT_EN = False
if FIT_EN:
model = ElasticNet(f... |
# Copyright 2018 QuantRocket LLC - 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 applicable law... |
# MIT License
# Copyright (c) 2019 Georgios Papachristou
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... |
from .config import add_posenet_config
from .backbone import *
from .checkpoint import *
from .proposal_generator import *
from .roi_heads import * |
from view.gui.application_settings import initialize_app_settings
from view.gui.flags_search import get_flags_index, query
from view.python_core.flags import FlagsManager
import pprint
def index_creation_test():
"""
Testing creation of flags index
"""
initialize_app_settings()
flags = FlagsManage... |
"""
********************************************************************************
compas_rhino.artists
********************************************************************************
.. currentmodule:: compas_rhino.artists
Artists for visualising (painting) COMPAS objects in Rhino.
Primitive Artists
============... |
def nth_smallest(arr, pos):
|
import pytest
from eth_abi.abi import (
encode_single,
)
from ..common.unit import (
CORRECT_SINGLE_ENCODINGS,
)
@pytest.mark.parametrize(
'typ,python_value,_1,single_type_encoding,_2',
CORRECT_SINGLE_ENCODINGS,
)
def test_encode_single(typ, python_value, _1, single_type_encoding, _2):
actual = ... |
import sys
import math
from collections import defaultdict, deque
sys.setrecursionlimit(10 ** 6)
stdin = sys.stdin
INF = float('inf')
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()
H, W, K = na()
grid = []
for _ in range(H):
grid.append(ns())
t... |
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain r... |
# pylint:disable=line-too-long
"""
The tool to check the availability or syntax of domains, IPv4, IPv6 or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ ████... |
import json
class DashboardEncoder(json.JSONEncoder):
"""Encode dashboard objects."""
def default(self, obj):
to_json_data = getattr(obj, "to_json_data", None)
if to_json_data:
return to_json_data()
return json.JSONEncoder.default(self, obj)
|
from flask import Flask
from flask import jsonify
from providentia.core.brain import ProvidentiaBrain
app = Flask(__name__)
@app.route('/keywords')
def keywords():
brain = ProvidentiaBrain()
data = brain.fetch_top_keywords()
top_keywords = data.get('top_keywords',[])
return jsonify(data={
'entr... |
import os
from keras.models import Sequential, load_model
from keras.layers import Activation, Embedding, Dense, TimeDistributed, LSTM, Dropout
MODEL_DIR = './model'
def save_weights(epoch, model):
if not os.path.exists(MODEL_DIR):
os.makedirs(MODEL_DIR)
model.save_weights(os.path.join(MODEL_DIR, 'epo... |
from urllib.parse import parse_qs, urlparse
import os
import requests
import pytest
from trackbelt import search_soundcloud
real_request = requests.request
def mock_request(raw_url, **kwargs):
url = urlparse(raw_url)
method = 'GET'
assert url.scheme in ('http', 'https')
assert url.netloc == 'soundcl... |
import io
import os
from configparser import ConfigParser
def read_bots():
lista = list()
config = ConfigParser()
config.read('config.env')
bots = config.sections();
print ("I have " + str(len(bots)) + " bots")
for x in bots:
bot = dict()
info = config.options(x)
... |
from django.contrib import admin
from maestrofinder_app.models import Musician, Request
# Register your models here.
admin.site.register(Musician)
admin.site.register(Request) |
#!/usr/bin/python3
#
# Copyright 2017, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions... |
from fastapi import APIRouter, status, HTTPException, Depends, Request
from core.multi_database_middleware import get_db_session
from sqlalchemy.orm import Session
from api.schemas.role_schema import UserRoleSchemaRequest, RoleSchemaRequest, RoleSchema, RoleRequestAccessSchema
from models.role_model import RoleModel, ... |
# coding=utf-8
# ${PROJECTNAME}
# (c) Chris von Csefalvay, 2015.
"""
test_FPS is responsible for [brief description here].
"""
from time import sleep
from unittest import TestCase
from processpathway import FPS
class TestFPS(TestCase):
def setUp(self):
self.fpsc = FPS()
def test_update(self):
... |
#!/usr/bin/env python3
def main():
#import required modules
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium ... |
import fileinput
from itertools import count
from utils import parse_nums
def gcd(a, b):
"""Compute the greatest common divisor of a and b"""
while b > 0:
a, b = b, a % b
return a
def lcm(a, b, *args):
"""Compute the lowest common multiple of a and b"""
return a * b / gcd(a, b)
positi... |
# -*- coding: latin-1 -*-
# Copyright (c) 2008 Pycircuit Development Team
# See LICENSE for details.
""" Test high-level circuit definition
"""
from pycircuit.circuit.hdl import Behavioural
import sympy
import numpy as np
def test_resistor():
"""Verify simple resistor model"""
class Resistor(Behavioural... |
expr = str(input("Digite uma expressão:"))
pilha = 0
for cont in expr:
if cont == "(":
pilha += 1 # Para cada parenteses aberto é somado 1
if cont == ")":
pilha -= 1 # Para cada parenteses Fechado é subtraido 1
if pilha < 0: # Se o numero da pilha for negativo significa que foi fechado um... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threathunter_common.util import millis_now
from threathunter_common.util import run_in_thread
from .generator import gen_generator
from .parser_initializer import get_fn_load_parsers
current_generators = []
last_update_ts = 0
def get_current_generators():
"""
... |
_FONT = {
32: [3, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63],
33: [3, 63, 63, 63, 51, 51, 51, 51, 51, 51, 63, 51, 63, 63, 63],
34: [5, 1023, 1023, 1023, 819, 819, 819, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023],
35: [7, 16383, 16383, 16383, 13119, 13119, 3, 13119, 15567, 3, 15567, 15567, 16383, 16383,... |
from django.contrib.syndication.feeds import Feed
from blogserver.apps.blog.models import Post,Category# Category
class LatestPosts(Feed):
title = "Latest Posts"
link = ""
description = "The Latest posts from the blog."
def items(self):
return Post.live.order_by('-date_published') [:10]
... |
import requests
import json
from generateReport import creation
def report_link(db,user_id,sheet_name,flag):
user_detail = db.find_one({"user": user_id})
# print("------------------------------------------")
# print(user_detail)
# print("-----------&&&&&&&&&&-------------------------------")
# pri... |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... |
import math
from typing import Callable
import torch
import torch.nn as nn
from torchlibrosa.stft import STFT
from bytesep.models.pytorch_modules import Base
def l1(output: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:
r"""L1 loss.
Args:
output: torch.Tensor
target: torch.T... |
# This script will accept two numbers from user, then add them and give the result.
# Import modules.
import platform
import os
# Clear the screen as per the OS type.
os_name=platform.system()
if os_name == "Windows":
os.system("cls")
elif os_name == "Linux":
os.system("clear")
else:
print(f"The OS is n... |
#!/usr/bin/env python
import sys
from oppai import *
# prints timing points (just a test for this interface)
ez = ezpp_new()
ezpp(ez, sys.argv[1])
for i in range(ezpp_ntiming_points(ez)):
time = ezpp_timing_time(ez, i)
ms_per_beat = ezpp_timing_ms_per_beat(ez, i)
change = ezpp_timing_change(ez, i)
print("%f |... |
import math
from datetime import datetime, timedelta
import sys
from airflow.models import Variable
import pandas as pd
import numpy as np
sys.path.insert(0, '/home/curw/git/DSS-Framework/db_util')
# sys.path.insert(0, '/home/hasitha/PycharmProjects/DSS-Framework/db_util')
from gen_db import CurwFcstAdapter, CurwObsAd... |
import DataAugment
import os
import sys
import glob
import random
import cv2
import numpy as np
from matplotlib import pyplot as plt
# set data augmentation method
# if methos = 1 -> use
DataAugmentMethod = {
'_avg_blur' : 0,
'_gaussain_blur' : 1,
'_gaussain_noise' : 1,
'_img_shift' : 1,
'_img_rotation' : 1,
... |
import numpy as np
import numpy.random as rd
import tensorflow as tf
from lsnn.guillaume_toolbox import einsum_bij_ki_to_bkj
b = 2
i,j,k = 3,4,5
a = rd.rand(b,i,j)
b = rd.rand(k,i)
tf_a = tf.constant(a)
tf_b = tf.constant(b)
prod2 = einsum_bij_ki_to_bkj(tf_a,tf_b)
sess = tf.Session()
np_prod_1 = np.einsum('bij,ki... |
from deephaven.plugin.json import Node
output = Node({
'str': 'bar',
'int': 1,
'float': 3.14,
'None': None,
'True': True,
'False': False,
'empty_list': [],
'empty_tuple': (),
'empty_dict': {},
'list': ['hello', 'world'],
'tuple': ('Devin', 1987),
'dict': {
'foo':... |
import numpy as np
import pytest
from shapes.shape import Triangle, Rectangle, QuadrangleBrush, Quadrangle, Ellipse, Curve, \
from_index, index_of
from shapes.shape.shape import crop_bounds
def test_should_leave_bounds_unchanged_if_no_need_to_crop():
bounds = np.array([[50, 60, 50], [50, 60, 51], [50, 60, 52... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2020 by ShabaniPy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT license.
#
# The full license is in the file LICENCE, distributed with this software.
# ----------------... |
import subprocess
cat = subprocess.Popen(
['cat', 'index.rst'],
stdout=subprocess.PIPE,
)
grep = subprocess.Popen(
['grep', '.. literalinclude::'],
stdin=cat.stdout,
stdout=subprocess.PIPE,
)
cut = subprocess.Popen(
['cut', '-f', '3', '-d:'],
stdin=grep.stdout,
stdout=subprocess.PIPE,... |
def quick_sort(arr, low, high):
if len(arr) == 0:
return 'cannot sort an empty array'
if len(arr) == 1:
return arr
if low < high:
p = partition(arr, low, high)
quick_sort(arr, low, p - 1)
quick_sort(arr, p + 1, high)
return arr
def partition(arr, low, h... |
import os
import requests
import urllib.request
import zipfile
TYPE="20w18a:server"
def _clone(url,fp):
urllib.request.urlretrieve(url,fp)
print(f"Requesting release tree...")
json=[e for e in requests.get("https://launchermeta.mojang.com/mc/game/version_manifest.json").json()["versions"] if e["id"]==TYPE.spl... |
import pandas as pd
from pdia.utils.createUniqueRunID import createUniqueRunID
from pdia.qc.dropStudents import dropStudents
def dropStudentsWithRepeatedBlock(df,
saveDroppedAs=None,
studentId='BookletNumber',
block... |
import unittest
from oslash.either import Right, Left
class TestEither(unittest.TestCase):
def test_either_right_map(self) -> None:
a = Right(42).map(lambda x: x * 10)
self.assertEqual(a, Right(420))
def test_either_left_map(self) -> None:
a = Left(42).map(lambda x: x*10)
se... |
from setuptools import find_packages
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='lcmap-merlin',
version='2.3.1',
description='Python client library for LCMAP rasters',
long_description=readme(),
classifiers=[
'Devel... |
# Copyright 1999-2019 Alibaba Group Holding Ltd.
#
# 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 a... |
# Testing relative imports inside Rust binary
# Testing absolute imports inside Rust binary
from helloworld.speaker import say_bye
from . import talker
def main():
talker.say_hello()
say_bye()
# In .bzl config, setting python_config.run_module = "helloworld.main" should cause this to run as the entry point... |
import telebot
from telebot import types
import json
import db
import configure
bot = telebot.TeleBot(configure.config["token"])
id1 = ""
firstname = ""
lastname = ""
university = ""
faculty = ""
category = ""
skills = ""
portfolio = ""
edit_type = ""
check = False
@bot.message_handler(commands=['start'])
def a... |
n1 = int(input('digite um numero: '))
n2= int(input('digite outro numero: '))
s = n1 + n2
print('A some entre {} e {} é {}'.format(n1, n2, s)) |
import numpy as np
import pandas as pd
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from torch.autograd import Variable
import torch.utils.data as data
from sklearn.metrics import roc_auc_sco... |
import altair as alt
import pandas as pd
from tweets import tweets
# %%
terms = [
"covid",
"lockdown",
"furlough",
"open",
"close",
"takeaway",
"collect",
"delay",
"supply",
"brexit",
"online",
"deliver",
]
tweets["text"] = tweets.text.str.lower()
for term in terms:
... |
import cobra
from scipy import sparse
from straindesign import MILP_LP, parse_constraints, lineqlist2mat, linexpr2dict, linexprdict2mat
from straindesign.names import *
from typing import Dict
# FBA for cobra model with CPLEX
# the user may provide the optional arguments
# constraints: Additional constraints ... |
# -*- encoding: utf-8 -*-
import json
import requests
from ..consts import DOCKER_HUB_API_ENDPOINT, PER_PAGE
from .config import Config
class DockerHubClient:
""" Wrapper to communicate with docker hub API """
def __init__(self):
self.config = Config()
self.auth_token = self.config.get('auth_t... |
# Copyright 2018-2019 CRS4
#
# 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 writing, softwa... |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
import os
import site
from shutil import copy2
from os.path import join as pjoin
files = [
'datatables.css',
'datatables.js'
]
def main():
sitepackages = site.getsitepackages()
static_base_... |
import armapy
from .data import Data
# TODO: implement SED
class SED:
data = None
seds = None
def __init__(self, data):
if type(data) is not Data:
data = Data(data)
self.data = data
def __download_properties__(self):
self.data.head.download_SVO_properties()
d... |
import warnings
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
url = "https://data.rivm.nl/covid-19/COVID-19_aantallen_gemeente_per_dag.csv"
def get_data(url: str = url) -> pd.DataFrame:
"""
Get data from url
url: url to csv
"""
return pd.read_csv(url, sep=";", parse_... |
#!/usr/bin/env python3
from bpylist import bplist
import sqlite3
import urllib.request
chat_sqlite = 'iphonex/Line.sqlite'
dload_dir = '_stickers'
date_limit = ('1529848800000',) # before 25/06/2018 00:00 (1 month anniv. + 2d)
query = 'SELECT ZCONTENTMETADATA FROM `ZMESSAGE` WHERE `ZCHAT` = 3 AND `ZCONTENTT... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli... |
from __future__ import absolute_import
from subprocess import Popen, PIPE
import tempfile
import shutil
import socket
import os
import json
class DisposableConsul(object):
DEFAULT_CONSUL_BIN = 'consul'
def __init__(self, consul_bin=DEFAULT_CONSUL_BIN):
self.consul_bin = consul_bin
self.temp_... |
# -*- coding: utf-8 -*-
# ########################## Copyrights and license ########################## #
# #
# Copyright 2020 Greg Caufield <greg@embeddedcoffee.ca> #
# ... |
"""
Given an array of integers and a target integer sum, return whether there exist a pair of integers in the array which add up to sum.
See if you can come up with an O(n^2) solution first. Then—can you come up with an O(n log n) one?
"""
import time
import random
import numpy as np
import matplotlib.pyplot as plt
D... |
class HashItem:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self):
self.size = 256
self.slots = [None for i in range(self.size)]
self.count = 0
def _hash(self, key):
mult = 1
hv = 0
for ch ... |
from topic_model import Topic
def test_topic_serialization():
root = Topic('root', layer=0)
c1 = root.add_child('c1', [("foo", 0.5), ("bar", 0.3)])
c1_1 = c1.add_child('c1-1', [("baz", 0.5)])
c2 = root.add_child('c2', [("yolo", 0.5)])
stored = root.store_recursively()
topic_dict = Topic.resto... |
import logging
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
from ui.Ui_Preferences import Ui_PreferencesDialog
def _bool(settings, directive, fallback):
value = settings.value(directive)
if isinstance(value, bool):
return value
logging.debug(f"_bool(): {directive!r} is {valu... |
import argparse
def argparse_config_train():
parser = argparse.ArgumentParser('')
parser.add_argument('--num-epoch', type=int, default=30,
help='number of training epochs')
parser.add_argument('--save-epoch', type=int, default=10,
help='frequency of m... |
#!/usr/bin/env python
import rospy
from light_classification.tl_classifier import TLClassifier
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight
from styx_msgs.msg import Lane
from sensor_msgs.msg import Image
from cv_bridge import... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def decay_lr(opt, max_iter, start_iter, initial_lr):
"""Decay learning rate linearly till 0."""
coeff = -initial_lr / (max_iter - start_iter)
for pg in opt.param_groups:
pg['lr'] += coeff
def getGradNorm(mo... |
import graphene
from catalog.schema import Query as CatalogQuery
from enrollment.schema import Query as EnrollmentQuery
from forms.schema import Query as FormsQuery
from grades.schema import Query as GradesQuery
from playlist.schema import Query as PlaylistQuery
from user.schema import Query as UserQuery
from user.sch... |
"""
Purified fields for Django forms.
"""
from django import forms
from purifier import HTMLPurifier
class PurifyedCharField(forms.CharField):
"""
Extendable django.forms.CharField
Add named argument `white_list` - dict of allowed tags and attributes
"""
def __init__(self, white_list={},... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Produce a HTML page called VTKColorSeriesPatches.html showing the available
color series in vtkColorSeries.
It also shows how to select the text color based on luminance.
In this case Digital CCIR601 is used which gives less weight to the
red and blue components of ... |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.urls import reverse
from homeschool.referrals.forms import ReferralForm
from .forms import ProfileForm
@login_required
def settings_dashboard(request):
"""A das... |
import os
import logging
import subprocess
from glob import glob
from time import sleep
from argparse import ArgumentParser
from configparser import ConfigParser
def main():
# Syntax
parser = ArgumentParser()
parser.add_argument('-m', dest='mAp', type=float)
parser.add_argument('-e', dest='eps', ... |
# ! /usr/bin/python3
# -*- coding:utf-8 -*-
from conf.base import BaseDB, engine
import sys
from sqlalchemy import (
Column,
Integer,
String,
DateTime
)
class Users(BaseDB):
"""table for users
"""
__tablename__ = "users"
# 定义表结构,包括id,phone,password,createTime
id = Column(Integer, p... |
# Lesson 4.13 - Timing Python operations
import numpy as np
import time
def test_run():
t1 = time.time()
print ("ML4T")
t2 = time.time()
print("The time taken by print statement is ", t2 - t1, " seconds")
if __name__ == "__main__":
test_run() |
import os
import csv
from collections import Counter
vote_count = 0
khan = 0
correy = 0
li = 0
otooley = 0
py_poll= "election_data.csv"
votes = []
runners = []
with open(py_poll, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
next(csvreader)
for ro... |
import os
import json
import boto3
from os import listdir, environ, path
from os.path import isfile, join
from zipfile import ZipFile
DEPLOY_TAG = 'latest' # datetime.now().strftime("%Y%m%d%H%M")
ECS_URI = environ.get('ECS_REPOSITORY_URI')
BATCH_JOB_ROLE = 'city-scrapers-batch-job-role'
SPIDER_PATH = join(
path.... |
from . import conversion
from . import measure
|
from math import sqrt
N = int(input())
nums = sorted(int(input()) for _ in range(N))
diff = nums[-1] - nums[0]
cands = set(elem
for div in range(1, int(sqrt(diff))+1)
if diff % div == 0
for elem in (div, diff // div))
Ms = sorted(cand
for cand in cands
if c... |
class OpenMLStudy(object):
'''
An OpenMLStudy represents the OpenML concept of a study. It contains
the following information: name, id, description, creation date,
creator id and a set of tags.
According to this list of tags, the study object receives a list of
OpenML object ids (datasets, fl... |
"""
API input/output manipulation utility functions
"""
import json
from alignment.PyHELM_simple import HelmObj
def extract_helm_from_json(input_json):
"""Extracts the HELM strings out of a JSON array.
:param input_json: JSON array of Peptide objects
:return: output_helm: string (extracted HELM strings... |
#!/usr/bin/env python
# coding=utf-8
################################################################################
import sys, os
curr_path = os.path.dirname(__file__)
parent_path = os.path.dirname(curr_path)
sys.path.append(parent_path) # add current terminal path to sys.path
#####################################... |
from flask import Blueprint, jsonify, request
usuarios_app = Blueprint('usuarios_app',__name__,template_folder='templates')
@usuarios_app.route('/usr', methods=['POST'])
def cadastrar():
|
#Submitted by thr3s0ld
class Solution:
def longestDupSubstring(self, S: str) -> str:
def check(mid, roll):
a = 0
for i in range(mid):
a = (a * 26 + ans[i]) % roll
dic = {a}
aL = pow(26, mid, roll)
for pos in range(1, n - mid + 1):
... |
import numpy as np
import pandas as pd
import sklearn.preprocessing
from sensai.data_transformation import DataFrameTransformer, RuleBasedDataFrameTransformer, DataFrameTransformerChain, DFTNormalisation
class TestDFTTransformerBasics:
class TestDFT(DataFrameTransformer):
def _fit(self, df: pd.DataFrame)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.