text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
from torch.nn import functional as F
from detectron2.layers import (
CNNBlockBase,
Conv2d,
get_norm,
)
from detectron2.modeling import (
BACKBONE_REGISTRY,
ResNet,
)
from detectron2.modeling.backbone.resnet import (
BasicStem,
weight_init,
)
from ..modules.cbam impo... |
import mmcv
import numpy as np
import torch
import cv2
__all__ = ['MaskTransform_cornernet', 'ImageTransform', 'ImageTransform_cornernet', 'BboxTransform', 'BboxTransform_cornernet', 'MaskTransform', 'Numpy2Tensor']
class ImageTransform(object):
"""
Preprocess an image.
1. rescale the image to expe... |
import numpy as np
import sonnet as snt
import tensorflow as tf
from sonnet.python.modules import base
from tensorflow.python.training import moving_averages
from dataset import Dataset
class Encoder(snt.AbstractModule):
def __init__(self, latent_space_size, num_filters, kernel_size, strides, batch_norm, gen_ob... |
from typing import Dict, Text, Any, NoReturn
import demjson
import jmespath
import requests
from jmespath.exceptions import JMESPathError
from loguru import logger
from rrtv_httprunner import exceptions
from rrtv_httprunner.exceptions import ValidationFailure, ParamsError
from rrtv_httprunner.models import VariablesM... |
#!/usr/bin/env python
import hashlib
import json
import os
import pprint
import sys
import importlib
import argparse
import re
from pathlib import Path
import logging
import io
import pykube
import subprocess
from io import BytesIO
logger = logging.getLogger()
logger_handler = logging.StreamHandler(sys.stdout)
logger... |
"""@package ms_stack_transformer
Lark AST transformer to generate XLM_Objects from an AST generated by ms_xlm.bnf.
"""
from __future__ import print_function
import string
import os
import sys
import traceback
from lark import Lark
from lark import UnexpectedInput
from lark import Transformer
from XLM.stack_item imp... |
##
## Copyright <NAME> <<EMAIL>> April 2017
## All Rights Reserved
##
import logging
logger = logging.getLogger( __name__ )
##
#
# This file contains the Interpreter interface for actually
# computing and evaluating a parsed input
import parsing
import framework
import node_utilities
import defining
##============... |
"""Contains tests for the model abstractions and different models."""
import unittest
import numpy as np
import random
import shutil
from hbaselines.hiro.algorithm import as_scalar, TD3
from hbaselines.hiro.tf_util import get_trainable_vars
from hbaselines.hiro.policy import FeedForwardPolicy, GoalDirectedPolicy
cla... |
import logging
from abc import abstractmethod
from typing import Union
import dask.dataframe as dd
import pandas as pd
from Bio import SeqIO
import openomics
from openomics.utils.read_gtf import read_gtf
from .base import Database
# from gtfparse import read_gtf
class SequenceDatabase(Database):
"""Provides a... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""SDC workflows coordination."""
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from nipype import logging
from ...niworkflows.engine.workflows import LiterateWorkfl... |
#!/usr/bin/env python3
"""
Few quick shortcuts for ica
"""
from urllib.parse import urlparse
import re
from jwt import decode, InvalidTokenError
from datetime import datetime
import libica.openapi.libconsole
import os
from utils.logging import get_logger
from utils.globals import SCOPES_BY_ROLE, ICA_BASE_URL_ENV_VAR... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Main dialog of the loan calculator.
"""
__author__ = "Sofie & <NAME>"
__copyright__ = "Copyright (C) 2018 Sofie & <NAME>"
__license__ = "see LICENSE file"
import os
import pathlib
import yaml
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QHBoxLayout,... |
#!/usr/bin/python3
import argparse
import sys
import re
import codecs
import string
import collections
try:
from unidecode import unidecode
except:
sys.exit("Requires unidecode pip package to be installed. Run:\npip install unidecode\nor\npip3 install unidecode\ndepending on your installation and start the scri... |
#!/usr/bin/env python
from __future__ import print_function
import sys
try:
import configparser
from future import standard_library
import builtins
except ImportError:
sys.stderr.write("Updates to cosmosis mean that you now need to install some new packages.\n")
sys.stderr.write("Please install wi... |
#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
""" huetemperature.py reads temperature values from DS18B20 sensor
and writes the current temperature to a 4-digit 7-segment display.
It also adjusts the color of a Philips Hue lamp to indicate
the current temperature.
By default the colour becomes ... |
'''
hamil
=====
Base classes and functions for generating and interacting with Hamiltonian
matrices.
'''
# copyright (c) 2012 <NAME>.
# All rights reserved.
#
# Modified BSD License; see LICENSE for more details.
import numpy
#--- Construct Hamiltonian (base) ---
class Hamiltonian:
'''Base Hamiltonian class.
... |
import os
import io
import shutil
import psutil
import pathlib
import humanize
import dataclasses
from gooey import Gooey, GooeyParser
import sys
import slpname
in_terminal = False
try:
sys.stdout.write('\n')
sys.stdout.flush()
in_terminal = True
except AttributeError:
# dummy class to export a "do not... |
"""
AudioKinetic WWise SoundBank representation and reading.
References:
- http://wiki.xentax.com/index.php/Wwise_SoundBank_(*.bnk)
- https://github.com/rickvg/Wwise-BNKExtract
"""
from typing import BinaryIO, Iterable, Dict, Any
import struct
from chunk import Chunk
from . import exception
from . import s... |
import os
import pickle
import matplotlib.pyplot as plt
import os.path as osp
import numpy as np
from gym import Env
from gym import utils
from gym.spaces import Box
from mujoco_py import load_model_from_path, MjSim
import cv2
"""
Constants associated with the Maze env.
"""
HORIZON = 100
MAX_FORCE = 0.1
FAILURE_COST ... |
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""introduce jira models:
Revision ID: 1d125da81dbf
Revises: <PASSWORD>
Create Date... |
# -*- coding: utf-8 -*-
"""
Tests for reading data into objects from external data *not* following
the conventions of this package, e.g., missing Class and MimeType values.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# disable: accessing protected m... |
# cleaning
# Contains functions for cleaning images
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torch.nn.functional as F
import os
import shutil
import time
import re
import sys
import skimage.io as io
import random
from op... |
#!/usr/bin/env python
import feedparser # pip install feedparser
from pymongo import MongoClient
import json
import re
import datetime
import logging
import RAKE
from calendar import timegm
from datetime import datetime
import hashlib
from fuzzywuzzy import fuzz
from bs4 import BeautifulSoup
import time
start = time.t... |
import os
import os.path
import click
from tabulate import tabulate
import psycopg2
import psycopg2.extras
import graphviz
# Output configuration
import logging
format_ = '%(message)s'
logging.basicConfig(format=format_, level=logging.INFO)
logger = logging.getLogger(__name__)
STYLES = {
'BASE TABLE': {'style':'s... |
import itertools
import json
import logging
import math
import os
from collections import OrderedDict
import torch
from torch import nn, optim
from torch.nn.parallel.data_parallel import DataParallel
# from tqdm import tqdm
# from common import get_logger
# logger = get_logger('Augmentation')
# logger.setLevel(logg... |
"""
Command line interface to manage Julia's system images.
"""
import argparse
import subprocess
import sys
import textwrap
from pathlib import Path
from typing import TYPE_CHECKING
from . import __version__
from .application import Application
from .utils import ApplicationError
if TYPE_CHECKING:
from typing_e... |
import os
import sys
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import numpy as np
import codes.graph_utils as gu
from codes.simulator import ByzantineWorker
from codes.utils import filter_entries_from_json
from codes.attacks import get_attackers
from template import MNISTT... |
import unittest
from unittest.mock import patch
import numpy as np
import scipy.linalg
from pyscfit.pdf import (
W,
detW,
dWds,
asymptotic_r_vals,
chs_vectors,
R,
asymptotic_R,
exact_R,
exact_pdf_with_missed_events,
)
class WTestCase(unittest.TestCase):
def setUp(self):
... |
# built-in
import asyncio
import re
from pathlib import Path
from urllib.parse import urlparse
# external
import pytest
# project
from dephell.constants import DEFAULT_WAREHOUSE
from dephell.controllers import DependencyMaker
from dephell.models import Auth, RootDependency
from dephell.repositories import WarehouseSi... |
import re
import os
from subprocess import Popen, PIPE
import shlex
import sys
# Comments explaining each steps are coming from tassel bitbucket:
# https://bitbucket.org/tasseladmin/tassel-5-source/wiki/Tassel5GBSv2Pipeline/
# To add: log file to store errors and output
# Pipeline from GBS to SNPs discovery
def run... |
"""
661. Image Smoother
Easy
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not presen... |
"""
Unified alerting infrastructure
Push alerts to whatever services have been configured, including logging, email, zapier, and slack.
"""
import json
import datetime
from api import global_config, logger
from api.models import User, Address, Contact
from api.adapters.alert.alert_push_slack import AlertSlack
from ... |
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
# Input data files are available in the "../input/" directory.
# For example, ru... |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#
# Evaluate trained models
#
import warnings
warnings.simplefilter(action='ignore')
from keras import backend as K
from src.model1 import uResNet34
from src.train import get_train_test_split, get_norm_dict
from src.gen1 import SliceIterator, primary_transform
from src.const import (
model_dir, model_input_size,
... |
# Copyright (c) 2020 Huawei Technologies Co., Ltd.
# Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa... |
class Variable(object):
def __init__(self, var, inequality=None):
self.var = var
self.inequalityConstraint = inequality
# for webkb
self.domainSize = 0
def __eq__(self, other):
return self.var == other.var
def __hash__(self):
return hash(self.var)
def ... |
import sys
import numpy as np
from time import time
import pandas as pd
from PeakListParser import PeakListParser
import os
#import pyteomics.fasta as py_fasta
import SimpleFASTA
class CsvParseException(Exception):
pass
class MissingFileException(Exception):
pass
class AbstractCsvParser:
"""
"""
... |
import numpy as np
import math
import faiss
import torch
from tqdm.auto import tqdm
from beir.retrieval.evaluation import EvaluateRetrieval
def perform_eval(model, label_dataloader, label_ids, instance_dataloader, inst_num, test_ids, accelerator):
label_bert = model.label_encoder
inst_bert = model.instance_encoder
... |
"""
Functions for reading logs and events out of Kubernetes, as well
as (de)serialisation as JSON files.
"""
import datetime
import json
import re
import time
from datetime import timedelta, timezone
try:
import orjson
except:
orjson = json
import kubernetes
# Regular expressions
kube_time_re = re.compile(
... |
from server import db
import sqlalchemy as sa
import logging
from decimal import Decimal as D
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql import func
from .SimpleStrategy import SimpleStrategy
class OrderThread(object):
FLAG_NAME = 'is_finished'
logger = logging.getLogger(__name__)
... |
import os
import re
import itertools
from pathlib import Path
from typing import Any, Dict, Union, Optional
from src.core.utils import path_join, str_to_bool
from src.core.io import parse_config, load_dotenv
from .plugins.postgresql_plugin import (
TableObject, ViewObject, MaterializedViewObject, FunctionObject, Pr... |
from program_synthesis.naps.uast.uast_to_cpp.type_converter import to_cpp_type
from program_synthesis.naps.uast.uast_to_cpp.libs_to_include import CPPLibs
from program_synthesis.naps.uast import uast
def to_cpp_expr(expr, libs):
car = expr[0]
if car == 'assign':
return "%s = (%s)" % (to_cpp_expr(expr[... |
import amplpy
from copy import deepcopy
from ordered_set import OrderedSet
import os
from typing import List, Iterable, Optional, Tuple, Union
import warnings
import symro.src.mat as mat
from symro.src.prob.problem import BaseProblem, Problem
import symro.src.scripting.amplstatement as ampl_stm
import symro.src.handle... |
"""
WiP.
Soon.
"""
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
from time import sleep
from typing import TYPE_CHECKING
from pathlib import Path
from datetime import datetime, timedelta
from threading import Thread
# * Qt Imports -----... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from mutaprops import *
import logging
import sys
import time
import asyncio
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
@mutaprop_class("Test object")
class Neco(object):
_roof_types = {'Convertible': 5, 'PapaMobil': 20, 'Normal': 45}
def __ini... |
# add logo to a .mp4, logo is .png with alpha
# requires ffmpeg.exe
# created by <NAME> , https://www.linkedin.com/in/liviu-t-94975536/
import subprocess
import os
from tkinter import *
from tkinter import filedialog,messagebox
from subprocess import Popen, CREATE_NEW_CONSOLE
from PIL import Image as Img
def load_vid... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 1 23:58:42 2018
Snake Mini project Starter Code
Name:
Date:
"""
import turtle
import random #We'll need this later in the lab
moshiko = turtle.Turtle()
moshiko.pu()
moshiko.ht()
moshiko.goto(-200,300)
moshiko.write("SNAKE GAME!!!", font=("Arial" , 40, "no... |
import numpy as np
import os
import re
import SimpleITK as sitk
from typing import *
from disptools import *
try:
import vtk
except ImportError as e:
print("Warning: cannot import 'vtk' module. " +
"Some functionalities depending upon it may be unavailable.")
try:
import ply
import ply.lex a... |
"""
Cartesian to regular solid harmonics conversion code.
"""
import decimal
import os
import pickle
import platform
import numpy as np
from . import order
from . import utility
_MAX_AM = 17
_DECIMAL_PREC = 60
_saved_rsh_coefs = {}
_saved_factorials = {}
def _factorial(n):
decimal.getcontext().prec = _DECIMAL... |
import warnings
import numpy as np
from . import c_wrapper as cwrap
def bl_from_x(x, y, antenna_diameter=4.0, exception=True, ignore_redundant=True):
res = cwrap.get_baselines(x, y, antenna_diameter)
if np.isscalar(res):
# didn't work.
if exception:
raise RuntimeError("Some of t... |
#!/usr/bin/env python
""" Make plots of the ROC curves we found in ``calc_roc_curves.py``
Also makes violin plots of the distributions to compare the original and
optimized score matrices.
"""
# Imports
import argparse
import pathlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2015, 2016, 2017, 2018
# <NAME>, <NAME>, <NAME>
# 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 withou... |
import search.utilities as util
import search.query as qu
import webbrowser
# Class including functions for OSINT collection using search engines.
class SearchEngines(qu.Query):
def __init__(self, query):
qu.Query.__init__(self, query)
# Top level domain search
__TLD__ = "com"
# Number of re... |
from collections import OrderedDict
import hcl_mlir
from hcl_mlir.ir import *
from .. import config, types
from ..types import Int, Type, UInt, dtype_to_hcl
from .context import UniqueName
from .dsl import for_
from .schedule import Schedule, Stage
from .tensor import Array, Tensor
from .utils import get_dtype_str, h... |
import tensorflow as tf
import numpy as np
import sys
from src.convolutional import set_convolutional
from src.crops_sr import extract_crops_z_sr, extract_crops_x_sr, pad_frame_sr, resize_images
import src.ConvNetValue_Class as cnvc
sys.path.append('../')
# the follow parameters *have to* reflect the desig... |
from OpenGL.GL import *
from OpenGL.GLU import *
from helpers import *
class Link(object):
def __init__(self, lower,upper):
self.lower = lower
self.upper = upper
def other(self, obj):
if self.lower==obj: return self.upper
return self.lower
class Cell(object):
... |
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication
import sys
from PyQt5.Qt import QPainter, QPoint, QPen
from PyQt5.QtCore import Qt
from PyQt5.Qt import QWidget, QColor, QPixmap, QIcon, QSize, QCheckBox
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QPushButton, QSplitter,\
QComboBox... |
from typing import Callable, Dict, List, Optional, Tuple, Union
import symro.src.mat as mat
# TODO: remove this module
# Fundamental Blocks
# ------------------------------------------------------------------------------------------------------------------
def generate_entity_instance(meta_entity: mat.MetaEntity,
... |
from PIL import Image
import os
from os.path import join
import scipy.io as sio
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from Network import Network
from utils import plot_images , sigmoid , dsigmoid_to_dval , make_results_reproducible , make_results_random
make_results_reproducibl... |
import math
import json
from collections import OrderedDict
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from django.db.models import Count
from django.db.models.query import QuerySet
from django.contrib.auth import authenticate, login, logout
from django.... |
# -*- mode: python; coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*-
#
# LIBTBX_SET_DISPATCHER_NAME xpp.progress_bar
#
'''
This is a wxpython GUI application for reading a database and
displaying a plot showing multiplicity by trial.
Currently it features:
* contains the matplotlib navigation toolbar
* allows... |
"""
This module helps in setting up the displays for game events (game over, victory, introduction, pause screen).
"""
import sys
import pygame
import constants as constants
# source: http://programarcadegames.com/python_examples/f.php?file=instruction_screen.py
def display_intro_screen():
""" ... |
# coding: utf-8
import os
import sys
from python_scale_ezxr.charuco_detection import *
from python_scale_ezxr.charuco_match import *
from python_scale_ezxr.scale_restoration import *
from colmap_script.colmap_proj import ColmapProj
from colmap_process.colmap_model_modify import modify_image_model_binary
def mkdir_cha... |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F
import torchvision.datasets as datasets
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import math
import os
import time
import numpy as n... |
# -*- coding: utf-8 -*-
import errno
import json
import logging
import logging.handlers
import os
import time
from configparser import ConfigParser, ExtendedInterpolation
import requests
import websocket
symbol1LastCallTime = 0.0
symbol2LastCallTime = 0.0
symbol3LastCallTime = 0.0
symbol4LastCall... |
import torch
import time
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from torch.utils.data import Dataset
import torch.autograd.functional as AGF
from pytorch_lightning.callbacks import EarlyStopping
import torch.linalg as linalg
from ... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
import tensorflow as tf
import numpy as np
import librosa
from librosa import display
import matplotlib.pyplot as plt
import pickle
import os
import io
import glob
import datetime
from hyperparameter import Hyperparameter as hp
from preprocess import world_decompose, pitch_conversion, world_encode_spectral_envelop, wor... |
"""
File description.
This file is the main program to run the project, just run it directly
encoding: utf-8
@author: <NAME>
@contact: <EMAIL>
@software: Pycharm
@time: 2022/1/14
@gituhb: sanxiadaba/pythonBlog
"""
import os
import time
import traceback
from collections import defaultdict
import pymysql
from flask i... |
import argparse
import logging
import time
from collections import Counter
from pathlib import Path
import PIL
import cv2
import numpy as np
import torch
from utils.datasets import LoadImages
from constants import DEFAULT_IOU_THRESHOLD, DEFAULT_CONF_THRESHOLD, DEFAULT_DETECTED_IMAGE_DIR, \
DEFAULT_INPUT_RESOLUTIO... |
import threading
from typing import ( # noqa: F401 pylint: disable=unused-import
Optional, Any, Callable, List, TypeVar, Dict, Coroutine, Set,
TYPE_CHECKING, Awaitable, Iterator)
import asyncio
from async_timeout import timeout
from types import MappingProxyType
import voluptuous as vol
import merceedge.util a... |
import numpy as np
import itertools as iter
class Clustering(dict):
def __init__(self, clustering_dict):
if not isinstance(clustering_dict, dict):
clustering_dict = dict(zip(range(len(clustering_dict)),clustering_dict))
super().__init__(clustering_dict)
self.clusters = {}
... |
"""
=====
Distributed by: <NAME> SCAI Lab (MIT Liscense)
- Associated publication:
url: https://arxiv.org/abs/2010.03957
doi:
github: https://github.com/zabaras/transformer-physx
=====
"""
import os
import matplotlib
import torch
import numpy as np
from typing import Optional
import matplotlib as mpl
mpl.use('agg')
i... |
#!/usr/bin/env python
import rospy
import rosparam
import actionlib
from copy import deepcopy
from waypoint import Waypoint
from interactive_markers.interactive_marker_server import InteractiveMarkerServer
from interactive_markers.menu_handler import MenuHandler
from geometry_msgs.msg import PoseWithCovarianceStamped, ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
# -----------------------------------------------------------------------------------------------------
# CONDOR
# Simulator for diffractive single-particle imaging experiments with X-ray lasers
# http://xfel.icm.uu.se/condor/
# -------------------------------------------------------------------------------------------... |
"""Various Player classes which are used in cmd play and inherit from Player"""
import move, board
import random, math
class Player:
"""Parent class to be inherited for Players. Defines two needed functions: play and __init__"""
def __init__(self, name = "Unspecified"):
self.name = name
self.w... |
from __future__ import absolute_import, division, unicode_literals
import datetime
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec, rsa, padding
import requests
# TOD... |
'''
Dataset record processing.
'''
# standard
import os
import logging
from posixpath import join
import shutil
import re
from numpy import number, string_
# third party
import pandas
# local
from libs import utils
from libs import constants as EC
from ht_etl import nlp_growth_conditions, gene_exp_datasets
def open... |
import requests
import string
import json
import time
markets = ['bitbay.net','bittrex.com','bitstamp.net','cex.io']
currency_pairs = [("ETH","USD"),("LTC","BTC"),("ETH","EUR"),("ETH","BTC")]
def orderbook_url(market, currency_pair):
source_currency = currency_pair[0]
target_currency = currency_pair[1]
i... |
import numpy as np
import datetime
import dateutil.parser
import cdflib
import matplotlib.pyplot as plt
import matplotlib as mpl
import string
#---Time conversion. All times are in UTC.
# internally save time as (whole ut sec, fractional ut sec up to pica sec accuracy).
# t_epoch, accurate to 1 milli second, in milli... |
# Copyright (c) Facebook, Inc. and its affiliates.
import random
from contextlib import contextmanager
import numpy as np
import timeit
import torch
import operator
from functools import reduce
prod = lambda l: reduce(operator.mul, l, 1)
torch.set_default_tensor_type(torch.DoubleTensor)
def cross_product(vec3a, ve... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import
import numpy as np
from .extras import dist, f
from .library import atleast_2d
from .eos80 import dens, dpth, g, pden
from .constants import db2Pascal, gdef
__all__ = ['bfrq',
'svan',
'gpan',
'gvel']
def bfr... |
# -*- coding: utf-8 -*-
"""
PlexAPI Media
"""
from plexapi.utils import cast
class Media(object):
TYPE = 'Media'
def __init__(self, server, data, initpath, video):
self.server = server
self.initpath = initpath
self.video = video
self.aspectRatio = cast(float, data.attrib.get('... |
import numpy as np
class AutoDiff():
"""Class which performs forward automatic differentiation
ATTRIBUTES
==========
val: the value of the object, can be scalar of vector
der: the derivative of the object, can be a scalar, vector or array
Optional
variables: number of variables used in... |
# Copyright 2016 ZTE 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 ... |
#!/usr/bin/env python
# coding=utf-8
# encoding=utf8
"""
Creates an excel spreadsheet formatted for Bridge input from a spreadsheet of
lemmatized forms in the format used by autoLemma.py.
Usage:
python3 convert_lemmata_format.py (greek | latin) import
EQUIVALENCETABLE.xlsx
python3 convert_lemmata_for... |
from ald.abp.abpkernels import AbstractABPKernel
from jinja2 import Template
from ald.core.config import AbstractConfig
import pycuda.gpuarray as gpuarray
import numpy as np
from ald.core.particle import ABP
from ald.core.boundary import Box
import h5py
class RheologyParams:
"""Compute simulation parameters from ... |
import os
import logging
import json
import asyncio
import zlib
import base64
from collections import OrderedDict
from typing import Tuple, Dict, List, Union
from aioupnp.fault import UPnPError
from aioupnp.gateway import Gateway
from aioupnp.util import get_gateway_and_lan_addresses
from aioupnp.protocols.ssdp import ... |
"""Optimize the quantum yield of a retinal model (Hahn, Susanne, and <NAME>.
"Quantum-mechanical modeling of the femtosecond isomerization in rhodopsin."
The Journal of Physical Chemistry B 104.6 (2000): 1146-1149.)"""
import torch
import numpy as np
import os
import torch
import random
import pdb
from math import pi... |
from . import app, view, auth
from .model import *
from .constants import *
from .utils import validate_user_id, validate_user_name, validate_jpeg_file, need_params
from flask import request, abort, send_file, g
@app.errorhandler(HTTP_400_BAD_REQUEST)
@app.errorhandler(HTTP_404_NOT_FOUND)
@app.errorhandler(HTTP_405_ME... |
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import pyautogui
import smtplib
from email.message import EmailMessage
import webbrowser
from time import sleep
import os
gmail = os.environ.get("ine")
password = os.environ.get("password")
listener = sr.Re... |
import logging
import os
import pickle
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from srl.base.define import (
EnvAction,
EnvObservation,
EnvObservationType,
Info,
RLAction,
RLActionType,
RLInvalidAction,
RLObservation,
... |
# -*- coding: utf-8 -*-
"""
modules for misc crawler without unfied API
"""
import re
import pandas as pd
import datetime as dt
import logging
import numpy as np
from bs4 import BeautifulSoup
from functools import lru_cache
import time
from requests_toolbelt import (
MultipartEncoder,
) # 'requests_toolbelt' has ... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import os
import time
class BRNN(nn.RNN):
def __init__(self, input_size, hidden_size... |
import os
import logging
import sys
import requests as req
from collections import OrderedDict
from datetime import datetime, timedelta
import cartosql
from functools import reduce
# Constants
LOG_LEVEL = logging.INFO
ALPS_URL = 'http://dataviz.vam.wfp.org/api/GetAlps?ac={country_code}'
MARKETS_URL = 'http://dataviz.... |
import numpy as np
import matplotlib.pyplot as plt
import os
from src.utils import dsp_utils
from scipy import signal
from scipy import interpolate
'''
Code for studying the wandering baseline of the ECGs.
This corresponds to the cardio-pulmonary response of each patient (i.e. the Sinus Respiratory Arrythmia)
'''
def... |
import numpy as np
from scipy.integrate import solve_ivp
from geomstats.geometry.special_orthogonal import SpecialOrthogonal
from geomstats.geometry.riemannian_metric import RiemannianMetric
import time
import multiprocessing
import functools
np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
... |
import logging
import os
from abc import ABC
from algorithm.policies import Policy
from algorithm.tools.podium import Podium
from algorithm.tools.utils import check_if_filepath_exists, Config, log
class Iteration(ABC):
"""
Abstract helper class for bookkeeping stuff of an iteration
"""
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.