text stringlengths 3.07k 22.1k |
|---|
from mpmath import *
from domain import Domain
from lazutkin_coordinates import *
from scipy.optimize import minimize_scalar
def bounce_compare(domain, path_vector, incident_point, t_0):
""" A helper for bounce which checks the validity of a bounce point
candidate. Return True if halving t_0 brings one clo... |
import requests
from typing import Union
from ScraGet.Exceptions import UserNotFound
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36"}
#"https://scratch.mit.edu/discuss/topic/96414/?page=11#post-1624859"
#"https://scratchdb.le... |
import os
import time
import tensorflow as tf
from copy import deepcopy
from tensorboard.plugins.hparams import api as hp
from tensorflow.python.eager import context
from tensorflow.python.keras import backend as K
from tensorflow.python.ops import summary_ops_v2
from tensorflow.python.summary import summary as tf_summ... |
"""
3D morphable model management.
This code is based on <NAME>'s code (https://github.com/YadiraF/face3d).
"""
import numpy as np
import scipy.io as sio
import face_alignment as fa
class MorphabelModel(object):
"""
nver: number of vertices.
ntri: number of triangles. *: must have. ~: can generate ones a... |
# coding: utf-8
###
# @file datasets.py
# @author <NAME> <<EMAIL>>
#
# @section LICENSE
#
# Copyright (c) 2019-2020 <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 with... |
#!/usr/bin/env python
"""
Description: Geometric median function implementation
Date Created: 15-MAY-2020
Last Modified: 17-MAY-2020
"""
from math import log
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import multivariate_normal
from scipy.optimize import minimize
from sklearn.preproce... |
import copy
import math
import typing
import jax
import jax._src.util as util
from jax import lax, numpy as jnp
from src.backend import get_param, shard, dims_to_shape, INT_OR_TUPLE, dot, matmul, transpose
from src.context import Context
REVERSIBLE_CTX = typing.Tuple[typing.Dict[str, jnp.ndarray], jnp.ndarray, jnp.n... |
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from numpy import floor
from networks import dmnet_2d_init2 as net_init
from networks.dmnet_2d_init2 import ResDBlock
from utils.learning_rate_scheduler import OneCycleSchedule, CyclicalSchedule, TriangularSchedule
from networks.layers import Mish
... |
import os
import sys
import inspect
import codecs
import re
import copy
import argparse
import warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict, Counter
def get_vocabulary(fobj, is_dict=False):
"""Read text and return dictionary that encodes vocab... |
import random
import math
import tensorflow as tf
from tensorflow.keras import layers
# applies additive normal-distributed pixel noise to the image
class RandomGaussianNoise(layers.Layer):
def __init__(self, stddev=0.02, **kwargs):
super().__init__(**kwargs)
self.stddev = stddev
def call(se... |
import torch
from torchvision.utils import save_image
from modules import model as M
from modules.dataset import MidiDataset
import os
import nonechucks as nc
from utils.torch_logger import TorchLogger
import numpy as np
from glob import glob
from tensorboardX import SummaryWriter
DATASET_PATH = "data/ginko_npy/**/*.n... |
from asyncio import AbstractEventLoop
from redbean.logs import setup_log_config
import contextlib
import os
import asyncio
from pathlib import Path
import inspect
import signal
import sys
import multiprocessing
import aiohttp.web
from watchgod import awatch
from importlib import import_module
import logging
logger = ... |
import wx
import wx.lib.buttons as buttons
import _icons as ico
DEFAULT_ITEM_WIDTH = 100
def chop_text(dc, text, max_size):
"""
Chops the input `text` if its size does not fit in `max_size`, by cutting the
text and adding ellipsis at the end.
:param `dc`: a `wx.DC` device context;
... |
import abc
import time
import boto
from boto.emr.connection import EmrConnection
from boto.regioninfo import RegionInfo
from boto.emr.step import PigStep
import luigi
from luigi.s3 import S3Target, S3PathTask
from luigi.contrib.pig import PigJobTask
from amazon_web_service.luigi import target_factory
import log... |
import mock
from bson.errors import InvalidStringData
class TestDatabaseInterface(object):
def test_get_all_exploits(self, db_instance):
exploits = db_instance.get_all_exploits()
assert len(exploits) == 2
assert exploits[0]['id'] == 1
assert exploits[0]['file'] == 'file1.c'
... |
#######################################################################
#Author: <NAME> #
#PI : <NAME> (<EMAIL>) #
#Email : <EMAIL> / <EMAIL> / <EMAIL> #
#######################################################################
impo... |
import os
import os.path
import re
import time
import hashlib
import logging
import multiprocessing
from piecrust.chefutil import format_timed, format_timed_scope
from piecrust.environment import ExecutionStats
from piecrust.processing.base import PipelineContext
from piecrust.processing.records import (
Proces... |
#!/usr/bin/env python
#Copyright (C) 2013 by <NAME>
#
#Released under the MIT license, see LICENSE.txt
'''
Testing aimseqtk.src.overlap
'''
import os
import sys
import unittest2 as unittest
import aimseqtk.src.overlap.overlap as overlap
import aimseqtk.src.overlap.trackclone as trackclone
import aimseqtk.lib.sample... |
import cv2
import numpy as np
def plothand(img, kp, bones=None):
"""
plothand is a function that plot single hand on the image
Image is desired to read by opencv. The outputs of other form of inputs are not guaranteed
Args:
:param img : image in matrix representation
:param kp : joi... |
"""Unit tests for :func:`esmvalcore._data_finder.regrid._stock_cube`"""
import iris
import pytest
from esmvalcore._data_finder import (
_get_timerange_from_years,
get_start_end_date,
get_start_end_year,
)
FILENAME_CASES = [
['var_whatever_1980-1981', 1980, 1981],
['var_whatever_1980.nc', 1980, 19... |
from stuff import *
from math import exp,log,sqrt
from scipy.optimize import minimize
import numpy as np
from random import random, seed
cases=loadcsv('SAcasecounts.csv')
cases['South Africa']=cases['Total']
del cases['Total']
mindate='2021-09-01'
maxdate='2021-12-04'
minday=datetoday(mindate)
maxday=datetoday(maxdat... |
import copy
import itertools
import json
import pytest
from sspace.orion.transformer import build_required_space
from sspace import Space, both, contains, either, eq, gt, lt, ne
from sspace.convert import build_space, convert_space
backends = ['ConfigSpace', 'Orion']
conditions = [eq, ne, lt, gt]
orion_space = {
... |
###############################################################################
# For more info, see https://hoseinkh.github.io/
###############################################################################
# In this file we are going to solve the Cart-Pole problem ...
# ... learning state-action value functions, ref... |
import os.path
import warnings
from subprocess import Popen
from time import sleep
import docker
import pytest
from compose.cli.main import TopLevelCommand, project_from_options
from confluent_kafka import Producer
from confluent_kafka.admin import AdminClient
from streaming_data_types.fbschemas.forwarder_config_updat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------... |
# Import libraries
import RPi.GPIO as GPIO
import random
import ES2EEPROMUtils
import os
import operator
import time
# some global variables that need to change as we run the program
end_of_game = None # set if the user wins or ends the game
user_guess = 0
num_of_guesses= 0
# DEFINE THE PINS USED HERE
LED_value = [... |
"""
Train and evaluate a SpanModel for SemEval-2021-task6-subtask2
For data, see: https://github.com/di-dimitrov/SEMEVAL-2021-task6-corpus
"""
from span.span_model import SpanModel
from span.span_utils import (
Fragment,
filter_sentence_splitter,
split_sentences_multi,
count_fragments,
split_in_s... |
r"""@package motsfinder.metric.analytical.schwarzschildks
Schwarzschild slice in Kerr-Schild coordinates.
The class defined here can be used to produce the data for a slice of
Schwarzschild spacetime in Kerr-Schild form.
"""
import numpy as np
from scipy import linalg
from ..base import _ThreeMetric, trivial_dtlaps... |
"""
Provides some useful systems using ipywidgets and MultibodyPlant.
This is gui code; to test changes, please manually run
//bindings/pydrake/multibody/examples/jupyter_widgets_examples.ipynb.
"""
import numpy as np
from functools import partial
from ipywidgets import FloatSlider, Layout
from IPython.display impor... |
import json
import requests
from typing import Set, Dict
from time import sleep
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from s... |
#!/net/kodiak/volumes/lake/shared/users/marghoob/my_env/bin/python
from __future__ import print_function
import argparse
import os
import sys
import logging
import subprocess
import re
import hashlib
import uuid
from multiprocessing import Process
import random
from functools import partial
from itertools import compr... |
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from app.utils import form_logger
from app.rmbot.config import CITY_MAPPING
from app.exceptions import Incomp... |
from scipy import stats
import random
import numpy as np
import pandas as pd
import CleanData
import timeit
import PullDataPostgreSQL
# Conditional Parameter Aggregation (CPA) is one of the most important parts
# of the entire SDV paper. It is what allows the user to synthesize an entire
# database instead of a single... |
import numpy as np
from pandas import DataFrame, Series
def impute(Y, method='mice', m=5, delta=0.0001, niter=100):
"""
Docstring for function ecopy.impute
====================
Performs univariate missing data imputation using one of several methods described below
Use
----
impute(Y, metho... |
import torch
from tqdm import tqdm
from timeit import default_timer
import torch.nn.functional as F
from .utils import save_checkpoint
from .losses import LpLoss, PINO_loss3d, get_forcing
from .distributed import reduce_loss_dict
from .data_utils import sample_data
try:
import wandb
except ImportError:
wandb =... |
import asyncio
import os
import subprocess
import traceback
from io import StringIO
from multiprocessing import Manager, Process
from multiprocessing.managers import DictProxy
from re import Pattern
from typing import Optional, Tuple, Dict, List, Set, Callable, TypeVar, Collection
BAD_USER_ENV_VARS = {'LD_PRELOAD'}
T ... |
#!/usr/bin/python
import datetime, time
import subprocess, threading
import shlex
import shutil
import os
import os.path
import sys
import tinys3
import glob
import urllib.request
import boto
from boto.s3.key import Key
import requests
import json
import random
from time import sleep
import time
from datetime import da... |
"""
pyt_pima_diabetes.py: binary classification (of imbalanced data) of PIMA Diabates dataset
@author: <NAME>
My experiments with Python, Machine Learning & Deep Learning.
This code is meant for education purposes only & is not intended for commercial/production use!
Use at your own risk!! I am not responsible if your... |
""" MobileNet V3
A PyTorch impl of MobileNet-V3, compatible with TF weights from official impl.
Paper: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244
Hacked together by <NAME>
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .efficientnet_blocks import round_channels, resol... |
"""Defines socket interaction, accepting connections and handling a basic
command/response flow.
"""
import asyncio
import binascii
import re
import sys
from asyncio import shield, IncompleteReadError, StreamReader, StreamWriter, \
CancelledError
from base64 import b64encode, b64decode
from ssl import SSLContext
... |
# # Calibration and Correction of State Preparation and Measurement (SPAM)
# Quantum Computers available in the NISQ-era are limited by significant sources of device noise which cause errors in computation. One such noise source is errors in the preparation and measurement of quantum states, more commonly know as SPAM... |
"""Widget to start / stop 3D Ortho viewer."""
from typing import List
from typing import Optional
import napari
from napari_plugin_engine import napari_hook_implementation
import numpy as np
from magicgui.widgets import Checkbox
from napari.layers import Image
from napari.layers import Labels
from qtpy.QtWidgets impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################################################
## POKeMON SwowS! ##
## ##
## Copyright (C) 2... |
import matplotlib
matplotlib.use('agg')
import matplotlib.gridspec as gridspec
from matplotlib.patches import Rectangle
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np
import os
from pandas import read_csv
from degnorm.utils import flatten_2d
plt.rcParams.update({'figure.max_open_warning': 0})
... |
import pandas as pd
import numpy as np
from gluonts_forecasts.model_config_registry import ModelConfigRegistry
from gluonts_forecasts.gluon_dataset import remove_unused_external_features
from gluonts_forecasts.utils import (
concat_timeseries_per_identifiers,
concat_all_timeseries,
add_row_origin,
quant... |
"""ユリウス通日."""
import math
import typing as t
# __pragma__("skip")
def julian_day_to_julian_year(juld) -> float:
"""ユリウス通日をユリウス年表示に變換する."""
julian_day_to_julian_year_intercept = 1721117.5
tweaked_julian_day = juld.julian_day - julian_day_to_julian_year_intercept
# ユリウス曆0年3月1日正子を0とする通算日數を計算。
quadren... |
# Copyright 2012 <NAME>
#
# 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 ... |
import numpy as np
import matplotlib
matplotlib.use('agg')
from . import flags
import torch
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = "cpu"
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
def merge_coresets(x_coresets, y_coresets):
merged_x, merged_y = ... |
from Utils import *
import cv2
from findcontours import *
def loadPlayerStrels():
strels = []
two = cv2.imread('PlayerSE/2.PNG', cv2.IMREAD_GRAYSCALE)
two = binarizeAndErode(two, 2, 1, 210, False)
strels.append(two)
three = cv2.imread('PlayerSE/3.PNG', cv2.IMREAD_GRAYSCALE)
three = binarizeAn... |
from __future__ import absolute_import, unicode_literals
import mock
from oauthlib.oauth2.rfc6749.tokens import *
from ...unittest import TestCase
class TokenTest(TestCase):
# MAC without body/payload or extension
mac_plain = {
'token': '<PASSWORD>',
'uri': 'http://example.com/resource/1?b... |
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import shutil
import chainer
import math
import argparse
from chainer import cuda
from chainer import optimizers
from chainer import serializers
from chainer import Variable
from chainer import functions as F
from mylib.chainer import dataset
from mylib.cv2_tools ... |
# lee: get k
import os
import json
import pandas as pd
import argparse
import spacy
import re
import pickle
import torch
from collections import defaultdict, OrderedDict, Counter
from transformers import AutoModel, AutoTokenizer, GPT2LMHeadModel, GPT2Tokenizer, AutoConfig
def load_json(fname):
try:
f = ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import asyncio,unittest,time
from redys import Client,AClient,Server
def async_test(coro):
def wrapper(*a, **k):
loop = asyncio.new_event_loop()
return loop.run_until_complete(coro(*a, **k))
return wrapper
class Test(unittest.TestCase):
def test... |
import os
import argparse
from PIL import Image
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.models import vgg16, vgg19, resnet50, resnet101, densenet121, densenet169
from dataset import *
parser = argparse.ArgumentParser()
parser.add_argument('-mo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# Copyright (c) Ostap developpers.
# =============================================================================
## @file ostap/math/tests/test_math_dalitz.py
# Test module for the file ost... |
import keras
class ResNet:
# implementation taken from
# https://github.com/keras-team/keras/blob/master/examples/cifar10_resnet.py
def __init__(self, input_shape, num_classes=10):
self.input_shape = input_shape
self.num_classes = num_classes
self._num_filters = 16
self._... |
"""Train script.
Usage:
infer_celeba.py <hparams> <dataset_root> <z_dir>
"""
import os
import cv2
import random
import torch
import vision
import numpy as np
from docopt import docopt
from torchvision import transforms
from glow.builder import build
from glow.config import JsonConfig
import imageio
from PIL import... |
from __future__ import absolute_import
import logging
import click
import cachetools
try:
import cPickle as pickle
except ImportError:
import pickle
from copy import deepcopy
from pathlib import Path
from pandas import to_datetime
from datetime import datetime
import datacube
from datacube.api.core import Dat... |
import time
from pathlib import Path
from typing import Optional
import torch.nn.functional as F
import dgl
import torch
from dgl.nn.pytorch import GINConv, SAGEConv, GraphConv
from torch.nn import Linear, Sequential, ReLU
from utils import Results, to_json, export_fold, ResultList, Crossval
torch.set_default_tenso... |
# -*- coding: utf-8 -*-
import os
from functools import cached_property
import tablib
from sqlalchemy import MetaData
from sqlalchemy import Table as SaTable
from sqlalchemy import create_engine, text
from sqlalchemy.sql import select
class Row:
"""A row from a table of a database."""
def __init__(self, ke... |
#!/usr/bin/env python
# FormatCBFMultiTileHierarchy.py
#
# Reads a multi-tile CBF image, discovering it's detector geometery
# automatically, and builds a hierarchy if present
#
# $Id:
#
from __future__ import absolute_import, division, print_function
import pycbf
from dxtbx.format.FormatCBFMultiTile import FormatCBF... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Reject submissions that are invalid in internal queues
"""
import argparse
import time
from challengeutils.submission import (
WORKFLOW_LAST_UPDATED_KEY,
WORKFLOW_START_KEY,
TIME_REMAINING_KEY,
)
from challengeutils.annotations import update_submission_status
from challengeutils.utils import update_sin... |
import binascii
import re
from . import tags
def _make_literal_serializer(expected_value, literal):
def serializer(to):
assert to.instance is expected_value
return literal
return serializer
def _make_integer_serializer(lower_bound, upper_bound, suffix):
def _serializer(to):
asser... |
import random
import time
import requests
import asyncio
from fun.Instagram import Instagram
from fun import db
_USERNAME = None
_PASSWORD = None
_UNWANTED_USERS_WITH_WORD = []
_UNWANTED_USERS_WITH_WORD_DEFAULT = ['pink',
'second', 'stuff', 'art', 'project', 'love', 'life', 'food', 'blog',
'free', 'keren', 'ph... |
import sublime
from . import debug, settings
"""
sv = source view
svid = source view id
tv = target view
tvid = target view id
"""
_source_views_by_tvid = dict()
_target_views_by_svid = dict()
_svids_by_tvid = dict()
_command_for_source_view = dict()
def cancel_command_for_view_id(view_id, wait=False):
command ... |
""" Module for finding keyframes """
import tensorflow as tf
import numpy as np
import cv2
import math
from openem.models import ImageModel
from openem.models import Preprocessor
from openem.image import crop
KEYFRAME_OFFSET = 32
MIN_SPACING = 1
PEAK_THRESHOLD = 0.03
AREA_THRESHOLD = 0.10
def peak_sum(array, idx, wi... |
# coding=utf-8
# Copyright 2022 The Fiddle-Config 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... |
'''
Created on 2018年3月28日
@author: <NAME>
'''
import csv
import numpy as np
import re
import Util.RandomUtil as RandomUtil
from Lib import RFLib as RFLib
filePath = r"G:\研究生课件\数据挖掘\实验数据"
'''
==========================与随机森林及决策树有关的工具类==============================
'''
'''
为随机森林模型及决策树模型产生数据,函数接受一个csv文件的文件名,具体路径在filePat... |
import itertools as itt
import collections as coll
import pathlib as pl
import matplotlib.pyplot as plt
import numpy as np
from progressbar import ProgressBar
from src.data import LDA as cLDA, dPCA as cdPCA
from src.metrics import dprime as cDP
import nems.recording as recording
import nems_lbhb.baphy as nb
from src.... |
import os
import errno
import sqlite3
import filecmp
import shutil
import warnings
from typing import (
Union,
Optional,
List,
Tuple,
Dict,
Any,
Iterator,
Callable,
)
from pathlib import Path
from contextlib import contextmanager
from tempfile import TemporaryDirectory
from .log import... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
import re
import scipy.io as sio
from .timeseries import *
def read_timeseries_PSAT(filename, timeseries_names=None, print_status=True):
var_names_mat = sio.loadmat(filename)['Varname']['uvars']
var_out_mat = sio.loadmat(filenam... |
import datetime
import os
from HTTPClient import NVPair
from java.lang import System
from java.net import ConnectException
from net.grinder.plugin.http import HTTPPluginControl
from net.grinder.plugin.http import HTTPRequest
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from org.sl... |
# -*- coding: utf-8 -*-
import io
import re
import sys
import threading
from collections import OrderedDict
from datetime import datetime, date
from itertools import chain
import six
__all__ = [
'unique', 'sorted_unique', 'AutoReprObject', 'object_to_dict',
'camel_to_underscore', 'import_string', 'ContextStac... |
"""
Discretization of continuous processes as markov chain
"""
import scipy as sp
import scipy.stats
import numpy as np
import math
# univariate tauchen code is taken from dpsolve ( https://bitbucket.org/stevejb/dpsolve )
def tauchen(N, mu, rho, sigma, m=2):
"""
Approximate an AR1 process by a finite marko... |
import sys, json, os, sys, hashlib, time, traceback
from pymongo import *
from urllib.parse import *
from uuid import uuid4
from random import randint, choice
from datetime import datetime
from core.set import *
from core.core import ct, get_post
from urllib.parse import *
import builtins as __builtin__
from set... |
#!/bin/env python3
import re
import argparse
import json
import numpy as np
from PIL import Image
from image_cropper import crop_image
from generate_sheet_music import generate_five_staff_sheet, generate_six_staff_sheet
def crop_staffs():
# Open file
with open('./Grand_Staff_Sections_Train.json', 'r') as fil... |
# -*- coding: utf-8 -*-
"""
@author: Eli
@data: 2021-08-18
@function pytest UI
"""
import time
from PySide6.QtWidgets import QApplication, QMainWindow, QListWidgetItem
from PySide6.QtUiTools import QUiLoader
from PySide6.QtGui import QFontDatabase
from PySide6.QtCore import QEnum, QFlag, QObject, Qt, Signal, Slot, QT... |
#!/usr/anaconda3/bin/python
#!/usr/bin/env python3
"""
Created on Mon Oct 22 23:50:11 2018
@author: <NAME> based on <NAME> and <NAME>
"""
import ete3, sys, argparse
from Bio import Entrez
# Parse arguments
parser=argparse.ArgumentParser(
description='''Takes a Newick tree with leaf names of either NCBI taxids o... |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
## NRPE Exporter Library Usage
The `NrpeExporterProvider` object may be used by charms to call
configured `nrpe` daemons and export the job results to Prometheus
metrics to facilitate migrating from Nagios+NRPE to
Prometheus+Ale... |
from __future__ import print_function, division, absolute_import
import os
os.environ['ODIN'] = 'gpu,float32'
from odin.utils import as_tuple_of_shape, ArgController, get_script_path, stdio, Progbar
args = ArgController(
).add('model', 'name of model'
).add('config', 'name of config in const.py'
).add('-ce', 'use cros... |
#!/usr/bin/env python3
"""Test pattoo configuration."""
import os
import unittest
import sys
from random import random
# Try to create a working PYTHONPATH
EXEC_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(
os.path.abspath(os.path.join(
os.path.abspath(os.path.... |
# Copyright <NAME> 2019. See LICENSE file.
from ..internal import GameObject, Box, Selection_Fill, Event
from .textBox import TextBox
from .textLine import TextLine
from typing import List, Tuple
class BaseSelectorObject(GameObject):
'''
Base Object for selector objects
'''
def __init... |
import base64
from collections import namedtuple
import io
import json
from os import listdir
from os.path import isfile, join, getsize, getmtime
import os
from traceback import print_tb
from xmlrpc.client import boolean
import zipfile
import psycopg2
import bcrypt
from core.consts import administrators_groups
from con... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from collections import defaultdict
import heapq
import pickle
import random
import time
import sys
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import pairwise_distances
impor... |
from pytest_bdd import scenario, given, when, then, parsers
import os
import subprocess
import sys
import docker
import pytest
import json
import tarfile
from deepdiff import DeepDiff
sys.path.append('./scripts/src/')
from report import report_info
import yaml
try:
from yaml import CLoader as Loader, CDumper as ... |
# Simple script to plot variables. Will grow with time.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import argparse
parser = argparse.ArgumentParser(description='reading strings for plotting')
parser.add_argument('strings', metavar='ID', nargs='+', help='string to plot')
args = parse... |
#!/usr/bin/env python3
###########################################################################
# This file is part of rsp2, and is licensed under EITHER the MIT license
# or the Apache 2.0 license, at your option.
#
# http://www.apache.org/licenses/LICENSE-2.0
# http://opensource.org/licenses/MIT
#
# ... |
# Acumos - Apache 2.0
from os.path import isfile
from os import makedirs, listdir, environ
from subprocess import PIPE, Popen
import importlib.util
import json
import requests
from acumos_proto_viewer import get_module_logger
from acumos_proto_viewer.exceptions import SchemaNotReachable
_logger = get_module_logger(_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from glob import glob
import importlib.util
from pathlib import Path
import sys
import threading
from typing import Dict, Callable
# For import parsers/*
sys.path.append('parsers')
from common import DIR_LOGS
def module_from_file(file_path: ... |
"""
Operations in time domain
"""
import keras
import numpy as np
import sklearn.linear_model as lm
import pyAudioAnalysis.audioFeatureExtraction as aF
import scipy as sp
import scipy.signal
from .stage_meta import ToDo, Neural, Analytic, DType
class GammaChirp(ToDo):
def __init__(self):
pass
class Ti... |
#!/usr/bin/env python3
import sys, os
import numpy as np
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from math_helpers import quaternions as quat
from math_helpers import matrices as mat
from math_helpers import vectors as vec
import matplotlib.pyplot as plt
"""Gemeral 3-axis at... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'
from os import listdir
import sys
import time
import tools.ops
import subprocess
import numpy as np
import tensorflow as tf
import scipy.misc as sm
from models.autoencoder_net import *
from tools.utilities import *
from tools.ops import *
from random import randint
... |
from __future__ import print_function
from __future__ import division
import numpy as np
import pandas as pd
import sys
from scipy.io import arff
from collections import Counter
# The following codes implement an ID3 tree with the assumptions:
# (i) the class attribute is binary
# (ii) the class attribute is named 'c... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import plotly.express as px
from .spatial_transformer_1d import SpatialTransformer1d
def plot_cost(cost, init_params, range_min, range_max, debug_dir):
"""Plot the cost image for the two parameters (weight and offset).
Parameters
... |
# A collection of quality of life functions that may be used in many places
import cv2
import numpy as np
import json
import matplotlib.pyplot as plt
from sklearn.metrics import precision_score, recall_score, roc_auc_score, roc_curve
# A silly function to set a default value if not in kwargs
def kwarget(key, default,... |
import solcx
from os.path import abspath
import subprocess
import re
from web3 import Web3
from eth_abi.exceptions import InsufficientDataBytes
from web3.exceptions import BadFunctionCallOutput
REVERT_MESSAGES = [
'VM Exception while processing transaction: revert',
'gas required exceeds allowance or always fa... |
import csv
import logging
import os
import re
import time
import traceback
import pandas as pd
import requests
import xlrd
import settings
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
class ExcelConverter(object):
"""
Conversion of multiple excel sheets to csv files
Adapted... |
'''
analyzer turns expression into a self-evaluating function
potentially save the effort to parse expression every time it executes
in fact, it might not be that useful, since we have already parsed list expression
but it's fun, so let's implement it
anyway, I feel deeply nested functions harder to debug than deeply ... |
from einops import rearrange
import paddle
import paddle.nn as nn
def conv_1x1_bn(inp, oup):
return nn.Sequential(
nn.Conv2D(inp, oup, 1, 1, 0, bias_attr=False),
nn.BatchNorm2D(oup),
nn.Silu()
)
def conv_nxn_bn(inp, oup, kernal_size=3, stride=1):
return nn.Sequential(
nn.C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.