text stringlengths 3.07k 12.6k |
|---|
"""Module to handle messages from Home Assistant cloud."""
import asyncio
import logging
import pprint
from aiohttp import hdrs, client_exceptions, WSMsgType
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.components.alexa import smart_home as alexa
from homeassistant.components.google_ass... |
import model.specs as specs
from eth2spec.utils.ssz.ssz_impl import hash_tree_root
def extract_state(s):
validators = s["network"].validators
validator = validators[1]
head = specs.get_head(validator.store)
current_state = validator.store.block_states[head].copy()
return current_state
def current... |
import logging
import os.path as osp
import torch
from torch import nn
from tensorboardX import SummaryWriter
from lib.test import test
from lib.utils import checkpoint, precision_at_one, \
Timer, AverageMeter, get_prediction, get_torch_device
from lib.solvers import initialize_optimizer, initialize_scheduler
f... |
# Generated file, please do not change!!!
import datetime
import enum
import typing
from ._abstract import _BaseType
from .common import ImportResource
if typing.TYPE_CHECKING:
from .common import (
Asset,
CategoryKeyReference,
ChannelKeyReference,
CustomerGroupKeyReference,
... |
# -*- coding: utf-8 -*-
"""
UI Python Module
This module uses dash and the handler script to create and update the UI.
The main components handled are the text box for input, the submit button, the
recommended articles box, the word cloud, the article sentiment display and
the top topics. Each has their own call to t... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 10:34:47 2018
<NAME>us air density equations
@author: <NAME>
@license MIT
"""
#import numpy
import math as m
def get_frost_point_c(t_air_c, dew_point_c, debug=False):
"""Compute the frost point in degrees Celsius
:param t_air_c: current ambient temperature in ... |
# flake8: noqa
# This file contains google utils: https://cloud.google.com/storage/docs/reference/libraries
# pip install --upgrade google-cloud-storage
# from google.cloud import storage
import os
import platform
import subprocess
import time
from pathlib import Path
import torch
def gsutil_getsize(url=''):
# ... |
# -*- coding: utf8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import auth
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm
from english.models import group, phoneme, pretestspeaking, ... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket 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 applicab... |
import argparse
import sys
import codecs
from operator import itemgetter
import torch
from modules.data_loader import DataLoader
import modules.data_loader as data_loader
from modules.transformer import Transformer
def define_argparser():
p = argparse.ArgumentParser()
p.add_argument(
'--model_fn',
... |
# -*- coding: utf-8 -*-
""" Codec for the Punicode encoding, as specified in RFC 3492
Written by <NAME>.
"""
import codecs
##################### Encoding #####################################
def segregate(str):
"""3.1 Basic code point segregation"""
base = bytearray()
extended = set()
for c in str:... |
import matplotlib.pyplot as plt
import numpy as np
from MAP.maze import RIGHT, UP, LEFT, DOWN
# Q表的可视化以及完整走迷宫过程的呈现
def draw_qtable(ax, qtable_model, time_, fire_flag):
n_rows, n_cols = qtable_model.my_maze.maze.shape
ax.clear()
ax.set_xticks(np.arange(0.5, n_rows + 1, step=1))
ax.set_xticklabels([])
... |
# Originaly developed by rcarson
# <EMAIL>
# based on http://www.kaggle.com/c/axa-driver-telematics-analysis/forums/t/12321/python-code-to-automatically-draw-repeated-trips
#
# Modified by <NAME> in an attempt to improve speed an clarity
# added vector operation where applicable
# added numpy and sklearn api where app... |
import argparse
import sys
import logging
from collections import Counter
from dataclasses import dataclass
from typing import List
from xml.etree import ElementTree as ET
from kloppy import load_statsbomb_event_data, event_pattern_matching as pm
from kloppy.infra.utils import performance_logging
sys.path.append("."... |
#!/usr/bin/env python3
import time
import pwncat
from pwncat.util import console
from pwncat.manager import Manager
from pwncat.modules import ModuleFailed
from pwncat.commands import Complete, Parameter, CommandDefinition
def get_user_choices(command: CommandDefinition):
if command.manager.target is None:
... |
import zlib
from hematite.compat import OrderedMultiDict as OMD
from hematite.compat.dictutils import PREV, NEXT, KEY, VALUE, _MISSING
ORIG_KEY = VALUE + 1
class Headers(OMD):
"""
Headers is an OrderedMultiDict, a mapping that preserves order and
subsequent values for the same key, built for string keys ... |
import sys
import time
import pyautogui
pyautogui.FAILSAFE = False
autogui_map = {"ESCAPE":"escape",
"ESC":"esc",
"ENTER":"enter",
"UP":"up",
"DOWN":"down",
"LEFT":"left",
"RIGHT":"right",
"UPARROW":"up",
"DOWNARROW":"down",
"LEFTARROW":"left",
"RIGHTARROW":"right",
"F1":"f1",
"F2":"f2",
"F3":"f3",
"F4":"f4",
"F5":"f... |
import os.path as osp
from math import inf
import mmcv
from mmcv.runner import Hook
from torch.utils.data import DataLoader
from mmaction.utils import get_root_logger
class EvalHook(Hook):
"""Non-Distributed evaluation hook.
This hook will regularly perform evaluation in a given interval when
performin... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Tests for MultiplexForecaster and associated dunders."""
__author__ = ["miraep8"]
import pytest
from sktime.datasets import load_shampoo_sales
from sktime.forecasting.arima import AutoARIMA
fr... |
import sys
import logging
import torch
import main_class
from mean_teacher.cli import parse_dict_args
from mean_teacher.run_context import RunContext
import math
import os
LOG = logging.getLogger('runner')
acc_n = []
ema_acc_n = []
auc_n = []
ema_auc_n = []
spe_n = []
ema_spe_n = []
sen_n = []
e... |
#!/usr/bin/env python3
import click
import functools
import os
import signal
import sys
print = functools.partial(print, flush=True)
PLANNER = 'planner'
DMC = 'dmc'
DPMC = 'dpmc'
DPMC_SOLVERS = (PLANNER, DMC, DPMC)
GAUSS = 'gauss'
MAXHS = 'maxhs'
UWR = 'uwr'
SOLVERS = DPMC_SOLVERS + (GAUSS, MAXHS, UWR)
HTD = 'htd'... |
# Portions of this plugin are inspired by RPyC
# https://rpyc.readthedocs.io/
#
# The license for that software is reproduced below
#
# Copyright (c) 2005-2013
# <NAME> (<EMAIL>)
# Copyrights of patches are held by their respective submitters
#
# Permission is hereby granted, free of charge, to any person obtaining a... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''Script that calculates F-score by sentence length for number of input-files or folders
Creates a plot using matplotlib'''
import argparse
import os
import matplotlib.pyplot as plt
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('A... |
#!/usr/bin/env python
'''
@Author: <NAME>
Manipal University Jaipur
This is just the python translation of MATLAB code given by <NAME> (original source),
refer https://sites.google.com/site/scarabotix/ocamcalib-toolbox
'''
import math
import numpy as np
def get_ocam_model(filename): ## get_o... |
import asyncio
import discord
from discord.ext import commands
import os
import re
import tempfile
import shutil
import plistlib
from Cogs import DL
from Cogs import Message
def setup(bot):
# Add the bot and deps
settings = bot.get_cog("Settings")
bot.add_cog(Plist(bot, settings))
clas... |
#!/usr/bin/env python3
import csv
import sys
from operator import itemgetter
import matplotlib.pyplot as plt
sum_fields = ['init time', 'warmup time', 'total query time', 'run count', 'average time']
def aggregate_runtimes(filename: str, key_fields: list[str]) -> list[dict[str, int]]:
aggregated = {}
with o... |
# This file is part of OctoBot (https://github.com/Drakkar-Software/OctoBot)
# Copyright (c) 2021 Drakkar-Software, All rights reserved.
#
# OctoBot is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from enum import Enum
from typing import Any, Callable, Dict, Iterable, List, Set, Type, Union
import torch
from detectron2.config import CfgNode
from .lr_scheduler import WarmupCosineLR, WarmupMultiStepLR
_GradientClipperInput = Union[torch.Ten... |
import os
import re
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask import (
Flask,
render_template,
request,
session,
flash,
redirect,
url_for,
logging,
)
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from functools ... |
import numpy as np
import matplotlib.pyplot as plt
# This is a short python script to play around with JumpDiff
import jumpdiff as jd
# %% Let's first integrate a jump-diffusion process
# Define:
# integration time and time sampling
t_final = 10000
delta_t = 0.01
# A drift function
def a(x):
return -0.5*x
# and... |
# Copyright (c) 2019 Inria
# Copyright (c) 2012, 2017-2018 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardwar... |
import time
import argparse
import os
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
parser = argparse.ArgumentParser('ODE demo')
parser.add_argument('--method', type=str, choices=['dopri5', 'adams'], default='dopri5')
parser.add_argument('--data_size', type=int, default=1000)
parser.add_arg... |
"""SDL mouse and cursor functions.
.. versionadded:: 13.5
"""
from __future__ import annotations
import enum
from typing import Any, Optional, Tuple, Union
import numpy as np
from numpy.typing import ArrayLike, NDArray
import tcod.event
import tcod.sdl.video
from tcod.loader import ffi, lib
from tcod.sdl import _ch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define the costs used on link states / actions.
"""
from abc import ABCMeta
import numpy as np
import pyrobolearn as prl
from pyrobolearn.rewards.cost import Cost
from pyrobolearn.utils.transformation import quaternion_distance
__author__ = "<NAME>"
__copyright__ = "C... |
"""
$Id$
$HeadURL$
Commands:
.autoop add/del/status/list
.op
Nick-format: nick!<EMAIL>
Supports adding/deleting multiple autoop-rules:
.autoop add #testchannel firstNick!<EMAIL> secNick!<EMAIL>
In add/del #channel needed, if changes done in query. If changes are made in #channel, defaults to current #channel.
conf... |
import os
import neat
from neat import activations
# TODO: These tests are just smoke tests to make sure nothing has become badly broken. Expand
# to include more detailed tests of actual functionality.
class NotAlmostEqualException(Exception):
pass
def assert_almost_equal(a, b):
if abs(a - b) > 1e-6:
... |
#vim:tabstop=2:softtabstop=2:shiftwidth=2:expandtab
"""
Decodes the path info and fetches the corresponding tile from pymongo
Accepts urls in the form of
server/tile.py/database/collection/filename.jpg:
"""
import pymongo
from bson import Binary
import sys
import os
import time
from PIL import Image
import Stri... |
from __future__ import print_function
from builtins import range
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
import shutil
from tempfile import mkdtemp, mkstemp
import numpy as np
from nipype.testing import assert_equal, assert_true, asser... |
# Copyright 2019 The iqt Authors.
#
# 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 writ... |
#!/usr/bin/env python3
import hashlib
import sys
import math
class MerkleNode:
def __init__(self, data, left, right, level=None):
self.data = data
self.left_child = left
self.right_child = right
self.hash = self.generate_hash()
self.level = level
def generate_hash(sel... |
import os
import subprocess
import argschema
import renderapi
import tempfile
import json
class RenderClientParameters(argschema.schemas.DefaultSchema):
host = argschema.fields.Str(required=True, description='render host')
port = argschema.fields.Int(required=True, description='render post integer')
owner ... |
# https://zhuanlan.zhihu.com/p/335753926
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from collections import OrderedDict
import numpy as np
import cv2
import torch
from pytorchocr.base_ocr_v20 import BaseOCRV20
class RecV20RecConverter(BaseOCRV20):
def __init__(s... |
"""
Caffe network visualization: draw the NetParameter protobuffer.
NOTE: this requires pydot>=1.0.2, which is not included in requirements.txt
since it requires graphviz and other prerequisites outside the scope of the
Caffe.
"""
from caffe.proto import caffe_pb2
from google.protobuf import text_format
import pydot
... |
import os
import glob
import numpy as np
import pandas as pd
from tqdm import tqdm
from keras.optimizers import Adam
from sklearn.metrics import log_loss, accuracy_score, mean_squared_error, roc_auc_score
from sklearn.model_selection import train_test_split
from models import (
get_generator,
get_discriminator... |
#from sklearn.pipeline import Pipeline
from typing import List
from sklearn.model_selection import GridSearchCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
import logthis
import pandas as pd
import numpy as np
from sklearn.svm import LinearSVC
... |
"""
Generate Carbon Diamond Lattice
@author: <NAME>
Derived from similar form by <NAME>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import numpy as np
from ..system.lattice import Lattice
from . import lattice_gen_utils
from six.moves import range
###########... |
# This file is part of the smt-switch project.
# See the file LICENSE in the top-level source directory for licensing information.
from collections import Sequence
from . import sorts
from . import functions
from . import terms
from .solvers import SOLVERS
def check_solver(f):
def eval_f(self, *args):
if ... |
import math
from time import time
from yearn.common import Tvl
from yearn.apy.common import Apy, ApyFees, ApyPoints
import requests
from brownie.network.contract import Contract
from joblib import Parallel, delayed
from yearn.prices import magic
from yearn.prices.curve import curve
from yearn.utils import contract_... |
import pytest
from astropy.tests.helper import assert_quantity_allclose
from astropy.units import allclose as quantity_allclose
from astropy import units as u
from astropy.coordinates import Longitude, Latitude, EarthLocation
from astropy.coordinates.sites import get_builtin_sites, get_downloaded_sites, SiteRegistry
... |
"""Mocked implementations of Kubernetes API for use in unit tests.
Aims to provide a simple yet configurable implementation of CRUD methods,
allowing to keep track of actions in an in-memory "database" or trigger
arbitrary problems for specific test needs.
"""
import contextlib
import copy
from unittest.mock import Ma... |
import typing as tp
from argparse import ArgumentParser
import numpy as np
from typing import Callable, Sequence
import mlir.ir as ir
debug_constraints = False
def save_module(module, module_save_filename):
"""Helper function to save a module to a file."""
with open(module_save_filename, 'w') as f:
f.writ... |
""" Custom net to hopefully avoid memory leak """
import torch
import torch.nn as nn
import torch.nn.init as init
import utils.pytorch_utils as utils
from collections import namedtuple
from torchvision import models
from custom_lpips.base_model import BaseModel
import os
##############################################... |
#--------------------------------------------------
# rqtt.py
# this file allows generic mqtt calls to the system
# rqtt is to prevent name collisions
# RapidFlasks's mqtt system - rqtt
# introduced 19/05/2019 (u8)
#--------------------------------------------------
import time
#flask routing imports
from flask impor... |
from __future__ import unicode_literals
import zipfile
import os.path
import sys
import xbmc
import xbmcvfs
import xbmcgui
from dropbox import dropbox
from . import utils as utils
from dropbox.files import WriteMode, CommitInfo, UploadSessionCursor
from . authorizers import DropboxAuthorizer
class Vfs:
root_path ... |
from PyQt5 import QtCore, QtWidgets, QtGui
from pygments import highlight
from pygments.lexers import *
from pygments.formatter import Formatter
import json
def hex2QColor(c):
r=int(c[0:2],16)
g=int(c[2:4],16)
b=int(c[4:6],16)
return QtGui.QColor(r,g,b)
class QFormatter(Formatter):
def ... |
# Copyright 2011, 2012 SRI International
# See LICENSE for other credits and copying information
# Integration tests for stegotorus - library routines.
import difflib
import errno
import os
import re
import shlex
import socket
import subprocess
import threading
import time
TIMEOUT_LEN = 15 # seconds
# Helper: stick... |
import json
import logging
import os
import sys
import inspect
import traceback
import datetime
import dataclasses
from typing import Optional
from typing import Tuple
from typing import Callable
@dataclasses.dataclass(frozen=True)
class LoggerContext:
trace: Optional[str] = None
span_id: Optional[str] = None... |
import argparse
import numpy as np
import sys
import os
import cntk as C
from cntk.train import Trainer, minibatch_size_schedule
from cntk.io import MinibatchSource, CTFDeserializer, StreamDef, StreamDefs, INFINITELY_REPEAT
from cntk.device import cpu, try_set_default_device
from cntk.learners import adagrad, learning... |
# internal use only for CI
# some CI related util functions
#
# Copyright 2020 Espressif Systems (Shanghai) PTE 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.o... |
from ctypes import (POINTER, WINFUNCTYPE, byref, c_byte, c_int64, c_longlong,
c_size_t, c_ubyte, c_uint, c_uint32, c_ulong, c_void_p,
c_wchar)
from typing import List, Union
from xlib.api.win32.wintypes.wintypes import BOOL
from ..wintypes import (ERROR, GUID, HRESULT, REFGUID, ... |
import base64
import json
import math
from typing import Tuple
import requests
import uvicorn
from electionguard import group
from electionguard.ballot import CiphertextBallot, BallotBoxState, from_ciphertext_ballot
from electionguard.decrypt_with_shares import decrypt_tally
from electionguard.decryption_share import... |
from util import is_int
class PowerScriptError(RuntimeError):
pass
ERR_TYPES = [
"CallError",
"MathError",
"CompareError",
"CastError",
]
for type_name in ERR_TYPES:
globals()[type_name] = type(type_name, (PowerScriptError,), {})
# Object instance = object
def make_spec_meth(name, var_name=None):
if n... |
from datetime import datetime
from flask import Blueprint, request, abort, current_app, jsonify
from sqlalchemy.orm.exc import NoResultFound
from commandment.models import db, Device
from commandment.pki.models import RSAPrivateKey, CertificateSigningRequest, CACertificate, \
EncryptionCertificate
from commandmen... |
# Copyright 2021 Huawei Technologies Co., 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 agreed to... |
# multicast e http -
# simulação de um hardware para o alexa
# simula um produto da wemo (no caso tomada liga e desliga.)
import struct
import socket
import sys
import _thread
import xml.etree.ElementTree as ET
import firebase_admin
from firebase_admin import credentials
from firebase_admin import auth
from firebase_... |
import numpy
import pytest
import chainerx
import chainerx.testing
from chainerx_tests import array_utils
# TODO(niboshi): Remove strides_check=False
@chainerx.testing.numpy_chainerx_array_equal(strides_check=False)
@pytest.mark.parametrize("shape,indices", [
# empty indexing
((), ()),
((3,), ()),
(... |
"""
Utils is intended to be a swiss-army-knife toolbox that houses boilerplate codes
for many apps or scripts. A generic API to access:
* config files,
* logs,
* email servers for notifications,
* [and maybe simple encryption, etc...]
"""
__authors__ = ['randollrr', 'msmith8']
__version__ = '1.13'
import json
import ... |
import sys
import argparse
import collections
import math
import tensorflow as tf
import numpy as np
import reader
parser = argparse.ArgumentParser(
description="Prepare data for the TensorFlow LSTM RNN")
parser.add_argument('infile')
parser.add_argument('-o', '--out_dir', nargs='?', default='./')
parser.add_argu... |
# This class takes advantage of the fact that all formats v0, v1 and v2 of
# messages storage has the same byte offsets for Length and Magic fields.
# Lets look closely at what leading bytes all versions have:
#
# V0 and V1 (Offset is MessageSet part, other bytes are Message ones):
# Offset => Int64
# BytesLength => ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
import socketserver
import struct
import logging
import sqlparse
from sqlparse.sql import Identifier, IdentifierList, Where, Parenthesis
from importlib import import_module
logging.basicConfig(level=logging.INFO)
class Handler(socketserver.BaseRequestHandler):
def handle(self):
self.environment = {}
... |
import datetime
import logging
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
from cloud_cache import CloudCache
from my_mqtt_cache import MqttCache
from salt.returners import get_returner_options
from salt.utils import jid
log = logging.getLogger(__name__)
__... |
from multiprocessing import Pool, cpu_count, freeze_support
import numpy as np
import pandas as pd
import pyam
import silicone.multiple_infillers as mi
from silicone.utils import return_cases_which_consistently_split
"""
This script measures how accurate the different ways of using multiple infillers are at
recreat... |
# Copyright (c) 2021 PPViT 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 applicable ... |
import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from dataset.range_transform import inv_im_trans
from collections import defaultdict
def tensor_to_numpy(image):
image_np = (image.numpy() * 255).astype('uint8')
return image_np
def tensor_to_np_float(image):
image_np ... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utility classes for io operations.
"""
import codecs
import errno
import os
import re
import tempfile
from monty.io import zopen
__author__ = (
"<NAME>, <NAME>, <NAME>, <NAME>, ... |
#!/usr/bin/env python3
# encoding: utf-8
# This file is part of CycloneDX Conan
#
# 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 ... |
"""Sans-I/O backend connection loss handling protocol."""
import enum
from typing import Optional, Tuple
import logging
import attr
from ventserver.protocols import events
from ventserver.protocols.application import connections
from ventserver.sansio import protocols
# Events
@enum.unique
class Update(enum.Enum... |
import time
import os
import numpy as np
# from scipy.misc import imread
import imageio as iio
from .text import load_formulas
from .image import build_images, greyscale
from .general import init_dir
class DataGeneratorFile(object):
"""Simple Generator of tuples (img_path, formula_id)"""
def __init__(self, ... |
import random
import warnings
from time import time
from collections import deque
from twisted.internet import reactor, defer, task
from ants.utils.defer import mustbe_deferred
from ants.utils.httpobj import urlparse_cached
from ants.resolver import dnscache
from ants.utils.exceptions import ScrapyDeprecationWarning
... |
import torch
import numpy as np
from tqdm import tqdm
from torch.autograd import Variable
import surprise
import copy
import time
from utils import *
import h5py
import gc
import os
class DataLoader():
def __init__(self, hyper_params, file_name):
self.hyper_params = hyper_params
self.bsz = int(hyp... |
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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/... |
from scipy.sparse import load_npz
import numpy as np
import csv
import os
def _load_csv(path):
# A helper function to load the csv file.
if not os.path.exists(path):
raise Exception("The specified path {} does not exist.".format(path))
# Initialize the data.
data = {
"user_id": [],
... |
# Base on the code: https://github.com/facebookresearch/Adversarial-Continual-Learning
from __future__ import print_function
from PIL import Image
import os
import os.path
import sys
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
import torch.utils.data as data
from torchvision.dat... |
from flask import Blueprint, request, jsonify, json
from sqlalchemy import text as sql
from typing import List
from web import util
from web.api import trigger
from web.cache import Cache, TriggerScheduler
bp = Blueprint('timeseries', __name__)
ENGINE = util.get_engine('metadata')
CACHE = Cache()
SCHEDULER = TriggerS... |
"""
Courses Forms
Django forms are a tool which allow us to write Python code and export HTML forms in the contexts of our view. Feel
free to use these to help update the database.
https://docs.djangoproject.com/en/1.11/ref/forms/
"""
import zipfile
from django import forms
from django.forms import ModelForm
from co... |
#!/usr/bin/env python3
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
sbz poudriere runner
"""
import argparse
import configparser
import os
import shlex
import subprocess
import sys
from typing import Dict
import colored
from colored import stylize
LOCALBASE = "/usr/local"
PORTSDIR = "/usr/ports" or o... |
"""
MicroGridsPy - Multi-year capacity-expansion (MYCE)
Linear Programming framework for microgrids least-cost sizing,
able to account for time-variable load demand evolution and capacity expansion.
Authors:
<NAME> - Department of Energy, Politecnico di Milano
<NAME> - Department of Energy, Politecnico... |
import sys
import os
import pandas as pd
import numpy as np
import sqlite3
import argparse
def refresh_drug(curie, synonymizer):
if curie is not None:
res = synonymizer.get_canonical_curies(curie)
if res[curie] is not None and res[curie]['preferred_category'] in ['biolink:Drug','biolink:ChemicalSu... |
from django import forms
from core.models import Grade, TermModel, Subject
class DateInput(forms.DateInput):
input_type = "date"
class AddStudentForm(forms.Form):
reg_number = forms.CharField(label="Reg Number", max_length=50, widget=forms.TextInput(attrs={"class": "form-control"}))
first_name = forms.... |
from compas.geometry import Frame
from compas.geometry import Rotation
from compas.geometry import Scale
from compas.geometry import Transformation
from compas.geometry import Translation
from compas.geometry import Vector
from compas.geometry import allclose
def test_transformation():
assert Transformation().mat... |
import random
import functools
import torch
from contextPred.chem.util import MaskAtom
# import inspect
class AtomFeaturesOneHotTransformer:
def __init__(
self,
num_atom_types=23,
num_degree=6,
num_formal_charge=5,
num_hybridization=8,
num_aromatic=2,
num_... |
# from pynndescent import NNDescent
# from utils import lovasz_losses as L
from utils import utils
import torch
from torch import nn
from torch import optim
import numpy as np
import networkx as nx
from sklearn.neighbors import NearestNeighbors
import random
import criteria as C
def stress(pos, D, W, sampleSize=No... |
from random import randint
from queue import SQueue
from error import PrioQueueError
class PrioQueue:
def __init__(self, elist=[]):
self._elems = list(elist)
if elist:
self.buildheap()
def is_empty(self):
return not self._elems
... |
import copy
from collections import OrderedDict
import psutil
import ray
try:
import GPUtil
except ImportError:
raise ImportError(" ray is not installed. " "In order to use auto_train please run " "pip install ludwig[ray]")
from ludwig.api import LudwigModel
from ludwig.automl.utils import get_available_reso... |
from collections import defaultdict
import numpy as np
from sklearn import svm
def makefeatx(fx, fy, bx, by, img):
tmpx = np.hstack((fx, bx))
tmpy = np.hstack((fy, by))
featx = np.zeros((len(tmpx), 15))
for i in range(len(tmpx)):
r = tmpy[i]
c = tmpx[i]
featx[i] = np.array([
... |
import re
import os
import subprocess
def is_travis():
return os.getenv("TRAVIS", False)
def is_appveyor():
return os.getenv("APPVEYOR", False)
def is_bamboo():
return os.getenv("bamboo_buildNumber", False)
def is_jenkins():
return os.getenv("JENKINS_URL", False)
def is_gitlab():
return os... |
import os
import pandas as pd
from analysis.choice_task.test_clusters import add_transition_clusters
from data_prep.add_variables.both_tasks.subject import add_fps_subject_level, \
add_max_trials, \
add_glasses_binary, add_recorded_date, add_window
from data_prep.add_variables.both_tasks.trial import add_fps_... |
from tkinter import *
import tkinter.filedialog
from tkinter.messagebox import *
from crypt_decrypt_fichier import *
def Ouverture_fichier_cle():
try:
filename = tkinter.filedialog.askopenfilename(title="Ouvrir fichier clé",filetypes=[('text files','.txt'),('all files','.*')])
path_key.set(filename... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.