text string |
|---|
import argparse
import logging
import os
import subprocess
import sys
import scipy.io as sio
import torch
from utils.eval_cmc import eval_feature
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("gpu", type=int)
parser.add_argument("model_path", type=str)
parser.add_a... |
<filename>vermouth/utils.py
# -*- coding: utf-8 -*-
# Copyright 2018 University of Groningen
#
# 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
... |
<reponame>ktodorov/uva-mas-18
import numpy as np
from scipy.stats import truncnorm
import scipy.stats as st
class my_pdf(st.rv_continuous):
def _pdf(self,x):
return (1+np.cos(x*np.pi))/2 # Normalized over its range, in this case [-1,1]
"MC for baseline comparision"
X_distribution = my_pdf(a=-1, b=1, nam... |
<filename>files_floor_area/files_commercial/weighted_regression_ExpDec.py
# according to https://stackoverflow.com/questions/44878372/how-can-i-apply-weights-in-this-scipy-least-squares-optimization-routine
import numpy as np
from scipy import optimize
import math
## same xdata and ydata as stated in question
gu... |
<filename>utils/features.py
import os
import sys
import numpy
import argparse
import sys
import soundfile
import numpy as np
import librosa
import h5py
import time
import pandas as pd
from scipy import signal
import matplotlib.pyplot as plt
import logging
import config
from utilities import calculate_scalar, create_fo... |
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import time
import os
from selenium.webdriver.common.by import By
import re
import time
from sklearn.linear_model import LinearRegression
from sklearn.model... |
#!/usr/bin/env python
# TODO:
# 2. impedance controlled shape of the formation: area(velocity)
# 3. postprocessing: trajectories smoothness, etc. compare imp modeles:
# - oscillation, underdamped, critically damped, overdamped
# - velocity plot for all drones, acc, jerk ?
# 4. another drones are obstacles for ... |
<filename>src/predict_bad_conver_helpers.py
# Lint as: python3
"""Helper functions for predicting conversation faillure
"""
from src import download_data
download_data.download_data()
import numpy as np
import pandas as pd
from scipy import stats
import logging
import os
import matplotlib.pyplot as plt
from sklearn.m... |
# -*- coding: utf-8 -*-
import scipy.io as sio
import numpy as np
import gmsh
import copy
from Gmsh_Functions_Submission import*
#Initialize the Gmsh kernel
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 0)
#Setting the parallel option for boolean operators on
gmsh.option.setNumber("Geometr... |
<gh_stars>1-10
import numpy as np
from scipy.interpolate import griddata
FanData = np.array(((33630, 0), (29845, 80), (25915, 150), (20280, 220), (29025, 0), (25820, 61), (22440, 112),
(17560, 165), (23900, 0), (21260, 41), (184804, 76), (14460, 112), (18780, 0), (16075, 26),
(1... |
<reponame>ScalarPy/scalarpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os.path
import math
from IPython.display import display,clear_output
import random
import scipy.stats as st
from sklearn.preprocessing import LabelEncoder
import sklearn.preprocess... |
<filename>test/plotTest.py
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy import stats
from mayavi import mlab
data = pd.read_csv(r'/afs/inf.ed.ac.uk/user/s18/s1854010/Downloads/DONEresultszz2.csv')
# data.head()
xx = data[data['x'] < 9000... |
from PIL import Image
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import griddata
import numpy as np
img_filename = "image.jpg"
im = Image.open(img_filename).convert('LA')
nim = Image.new('LA', im.size)
pixels = nim.load()
bitlist = []
pixelvalueslist = []
pixelplot ... |
"""
Background subtract, resample, and coadd 2d spectra.
"""
from mostools import spectools,correct_telluric,skysub
from special_functions import genfunc
import scipy
from scipy import optimize,interpolate,ndimage,signal,stats
from astropy.io import fits as pyfits
RESAMPLE = 0 # 1 to only resample
magicnum = -2**15... |
import matplotlib as mpl
from matplotlib import cm, colors
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import argparse
import csv
import sys
from scipy.sparse import csc_matrix, dia_matrix, linalg as sla
from scipy.stats import norm
from smoothfdr.smoothed_... |
<filename>faster-rcnn-base-model/code/Debug_20180301.py
#Bayesian Loop
import numpy as np
import glob
import os
import pandas as pd
import scipy
import matplotlib.pyplot as plt
from sklearn import datasets, linear_model
from scipy.stats import norm
from sklearn.neighbors import KernelDensity
from scipy.stats import poi... |
"""Convolutional dictionary learning"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import time
import numpy as np
from scipy import linalg
from scipy import optimize, signal
from joblib import Parallel, delayed
from .utils.convolution import _choos... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 17 10:20:15 2018
@author: SENSETIME\yuxian
"""
import logging
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import os, sys, shutil, argparse
import openslide
import json
from scipy import ndimage as nd... |
import itertools
import logging
import os
import time
from collections import OrderedDict
import matplotlib.pyplot as plt
import numpy as np
plt.style.use(os.path.join(os.path.dirname(__file__), 'mpl_style')) # noqa
from scipy import spatial
from sklearn.decomposition import PCA
from sklearn.preprocessing import Sta... |
from __future__ import division
from __future__ import print_function
import numpy as np
import scipy.sparse as sp
import pickle as pkl
import os
import h5py
import pandas as pd
import pdb
from data_utils import load_data, map_data, download_dataset
def normalize_features(feat):
sum= feat.sum(1)
... |
<gh_stars>0
from scipy import stats
import numpy as np
from matplotlib import pyplot as plt
data = stats.norm.rvs(size=500)
pv = stats.kstest(data, "norm")[1]
print('p-value:' + str(pv))
mu = 5
sigma2 = 3
data = stats.norm.rvs(size=500) * sigma2 + mu
pv = stats.kstest(data, stats.norm(loc=mu, scale=sigma2).cdf)[1]
pr... |
<reponame>carlosayam/PyWDE<filename>pywde/common.py
import pywt
import math
import numpy as np
import itertools as itt
from sklearn.neighbors import BallTree
from scipy.interpolate import interp1d
from scipy.special import gamma
from functools import partial
def np_mult(cols):
if len(cols) == 1:
return col... |
<reponame>Candida18/Job-Portal-with-Automated-Resume-Screening
#!/usr/bin/env python
# encoding: utf-8
from collections import namedtuple
import unittest
import logging
import numpy as np
from scipy.spatial.distance import cosine
from gensim.models.doc2vec import Doc2Vec
from gensim import utils
from gensim.models im... |
#!/usr/bin/env python
'''
Test script to compare the performances of
the generalized poisson llh with the other
miminization metrics available in pisa
'''
from __future__ import absolute_import, print_function, division
__author__ = "<NAME> (<EMAIL>)"
#
# Standard python imports
#
import os
import pickle
from coll... |
<filename>code_mod1.py
# Model I
# Version 23th July 2015
# The python code solves Model I for the optimization of a transit line
# and for the strategic assessment of mode choice, see:
# <NAME>, and <NAME>, 'Improved models for technology choice in a transit corridor with fixed demand', 2015
# For comments, please w... |
# -*- coding: utf-8 -*-
"""
Es 3
"""
import matplotlib.pyplot as plt
import numpy as np
import sympy as sym
import allM as fz
import math
import Funzioni_Integrazione as fzz
scelta = input("Seleziona integrale ")
x = sym.Symbol("x")
alpha = np.array([13./2., 5./2., 1./2.])
integrali = {
"1" : [sym... |
import numpy as np
from scipy import sparse
def adj_from_nii(maskfile,num_time_points,numt=0,numx=1,numy=1,numz=1,regions=None):
from nipy.io.api import load_image
from nipy.core.api import Image
mask = load_image(maskfile)._data
return adj_from_3dmask(mask=mask,num_time_points=num_time_points,numt=nu... |
<reponame>johankaito/fufuka
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright (C) 2006-2015 <NAME> <<EMAIL>>
#
# This program 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 version 3 of th... |
<filename>code/isa/tests/gsm_test.py
import sys
import unittest
sys.path.append('./code')
from isa import GSM
from numpy import asarray, isnan, any, sqrt, sum, square, std, mean
from numpy.random import randn, rand
from scipy.stats import kstest, norm, laplace, cauchy
from scipy.optimize import check_grad
from pickle... |
<gh_stars>0
import os
import shutil
import glob
import re
import scipy
import astropy.io.fits as pyfits
from matplotlib import pyplot
from scaling_functions import *
# ========================
# === Class CalDB ===
# ========================
class CalDB:
"""
A class to scale the standard CTA IRFs, store... |
from sys import getdefaultencoding
import setdefaultencoding
from gensim.models import Word2Vec
from bltk.langtools import PosTagger
import nltk
import bltk
import numpy as np
from bltk.langtools import Tokenizer
from sklearn.cluster import KMeans
from sklearn import cluster
from sklearn import metrics
fr... |
"""
Audio feature extraction.
Many functions have been inspired by https://github.com/librosa and https://github.com/kaldi-asr/kaldi.
"""
import os
import wave
import miniaudio
import numpy as np
import tensorflow as tf
import webrtcvad
import scipy.signal
from . import mel_ops
@tf.function(input_signature=[tf.Tens... |
<filename>encrypt.py
import os
import random
import math
import sys
from Crypto.PublicKey import RSA
from sympy import *
sys.setrecursionlimit(2000)
####Prime Functions####
def millerRabin(m, k):
"""
Miller Rabin pseudo-prime test
return True means likely a prime, (how sure about that, depend... |
import numpy as np
import os
import glob
import json
import argparse
import tensorflow as tf
# For headless environments
import matplotlib as mpl
mpl.use('Agg') # NOQA
import matplotlib.pyplot as plt
from PIL import Image
from scipy.misc import imsave
from object_detection.utils import label_map_util
from object_dete... |
#! /usr/bin/env python3
import itertools
import math
from fractions import Fraction
description = '''
Diophantine equation
Problem 66
Consider quadratic Diophantine equations of the form:
x2 – Dy2 = 1
For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
It can be assumed that there are no solut... |
#!/usr/bin/env python
# coding: utf-8
# <div class="alert alert-block alert-info">
# <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b>
# </div>
#
# Copyright © 2021 <NAME> and <NAME>
#
# Last GitHub Commit Date:
#
# # 30: Regression using Exponential, Logarithmic, and Power-Law Models
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Dynamic Model of Quadrotor ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 13:37:37 2019
@author: mlampert
"""
#Core imports
import os
import copy
#Importing and setting up the FLAP environment
import flap
import flap_nstx
flap_nstx.register()
thisdir = os.path.dirname(os.path.realpath(__file__))
fn = os.path.join(this... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import torch
import torch.nn as nn
import torch.optim as optim
from kaldi_fft_dataset_adjusted import FftDataloader, FrameDataset
#from speech_utils import print_with_time
import hashlib
import numpy as np
from tensorboardX import SummaryWriter
import torchvision.util... |
<gh_stars>1-10
import pandas as pd
import os
import datetime
import numpy as np
import statsmodels.formula.api as sml
import QUANTAXIS as QA
import datetime
import numpy as np
import statsmodels.formula.api as sml
from QAStrategy.qastockbase import QAStrategyStockBase
import matplotlib.pyplot as plt
import scipy.stat... |
from typing import Optional, Union
import numpy as np
import tensorflow as tf
from patsy import dmatrix
from scipy.sparse import coo_matrix
from ncem.estimators import Estimator
from ncem.models import ModelLinear
class EstimatorLinear(Estimator):
"""Estimator class for linear models. Subclass of Estimator."""
... |
<gh_stars>1-10
import numpy
from scipy import ndimage
def sample_image_rect(image, size, center, rotation=0, order=3, **kwargs):
"""Return an image "swath" of a given (w, h) size, centered at a given (x, y)
position and rotated by the specified degrees.
Parameters:
image: the image to sample from.
... |
<gh_stars>10-100
import numpy as np
from tqdm import tqdm
from scipy.linalg import expm
from scipy.interpolate import interp1d
from scipy.signal import tf2ss
from msdsl import MixedSignalModel, RangeOf
from msdsl.interp.interp import calc_interp_w
from msdsl.interp.lds import SplineLDS
from msdsl.interp.ctle import ca... |
import numpy as np
from collections import OrderedDict
from scipy.sparse import hstack, csr_matrix
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import OneHotEncoder
from autogluon.core.constants import BINARY, MULTICLASS, REGRESSION, SOFTCLASS
from ..tabular_nn.categorical_encode... |
"""
产品组件:GDM (数据建模工作台)
工作空间:b
文件:机器学习模型1.gdmm
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io.matlab.tests.test_mio import a
from sklearn.metrics import mean_squared_error
from gdmBHTR.transformed_histogram import TransformedHistogramRegressor
from gdmBHTR.transformed_boost i... |
"""Glacier thickness.
Note for later: the current code is oriented towards a consistent framework
for flowline modelling. The major direction shift happens at the
flowlines.width_correction step where the widths are computed to follow the
altitude area distribution. This must not and should not be the case when
the a... |
<gh_stars>10-100
import os
import pdb
import random
from collections import namedtuple
import numpy as np
import scipy.sparse as sparse
import torch
from cnf import CNF
from util import DataSample, adj, adj_batch, init_edge_attr, to_sparse_tensor
Batch = namedtuple('Batch', ['x', 'adj', 'y', 'idx', 'sizes'])
def l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test suite for the response handling.
:copyright:
<NAME> (<EMAIL>), 2013
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print_function,
... |
<reponame>usuaero/PyProp
#Code written by <NAME>.
#Altered by <NAME> to handle "NaN" values.
#Altered by <NAME> to allow the user to specify if some power coefficients
#should be set to zero.
import numpy as np
from scipy.optimize import least_squares
def poly_fit(n,xx,yy,forcezero=None):
good = np.where(~(... |
<gh_stars>1-10
#!/usr/bin/env python3
import argparse
import arviz as az
import copy
import csv
import engineering_notation
import hashlib
import numpy as np
import os
import pandas as pd
import platform
import pymc3 as pm
import shutil
import scipy.stats
import statistics
import subprocess
import sys
import time
impo... |
<filename>explanation/lime.py
import numpy
import scipy.sparse
import sklearn.metrics.pairwise
import math
from sklearn.linear_model import Lasso, Ridge, RidgeClassifier
from explanation.base_explanation import BaseExplanator, BaseExplanation
def gaussian(d, w):
return math.exp((-1 * d * d) / (w * w))
... |
# Copyright 2019 <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
import numpy as np
from scipy.optimize import curve_fit
from auspex.... |
"""
#ex1
print("hello world")
#ex2
for i in range(2000,2041):
print(i)
#ex3
for i in range(1,31):
print(f" 8 * {i}={8*i}")
#ex4
for x in range(1,8):
print("*" * x)
#ex5
y=int(input("votre nombre?\n"))
print("double du cube = ",(y**3)*2)
#ex6
y=int(input("votre nombre?"))
if y%2==0:
print("nombre paire")
else:
pri... |
import multiprocessing as mp
import os
import tempfile
import shutil
import dask.dataframe as dd
import dask.diagnostics
import genomepy
from gimmemotifs.scanner import scan_regionfile_to_table
from gimmemotifs.utils import pfmfile_location
from loguru import logger
import numpy as np
import pandas as pd
import pickle... |
import time
import numpy as np
import scipy.ndimage
from desiutil.log import get_logger
from desispec.qproc.qframe import QFrame
def qproc_sky_subtraction(qframe,return_skymodel=False) :
log=get_logger()
t0=time.time()
log.info("Starting...")
twave=np.linspace(np.min(qframe.wave),np.max(qframe.wa... |
<filename>recsys/models/vector_model.py
import numpy as np
import tensorflow as tf
import random
import utils.serialize_iterable
import utils.load_info_for_model
import implicit
import re
from scipy import sparse
def normalize_name(name):
name = name.lower()
name = re.sub(r"[.,\/#!$%\^\*;:{}=\_`~()@]", ' ', n... |
<filename>myresources/crocodile/core.py
"""
A collection of classes extending the functionality of Python's builtins.
email <EMAIL>
"""
# Typing
# Path
import os
import sys
from pathlib import Path
import string
import random
# Numerical
import numpy as np
# import pandas as pd # heavy weight, avoid unless necessary... |
<reponame>adrimos/COVID19TreeMapUSpop
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# Setting up the environment.
import numpy as np
import pandas as pd
from scipy import stats
import plotly as pl
# %%
# Load the data from the John Hopkins github repo
df = pd.read_csv('htt... |
<filename>analysis_minimum_features.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 10 15:24:20 2021
Assess how many features are really necessary
@author: kaandorp
"""
import numpy as np
import pandas as pd
import xarray as xr
import os
from datetime import datetime,timedelta
impor... |
<filename>cluster/find_subclusters.py
import sys
import pickle
import scipy.sparse as sp
import numpy as np
import time
import ed_spins as tvi
import ed_fermions as hubb
import ed_nlce
def find_subclusters(cluster_index, cluster_data_out_fname, cluster_data_in_fname):
with open(cluster_data_in_fname, '... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017 2018 <NAME> <<EMAIL>>
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 Softwa... |
import sys
import os
from unet.SegmentationNetwork import UNET
import tensorflow.contrib.slim as slim
import tensorflow as tf
import numpy as np
import pandas as pd
from losses import *
from skimage.transform import resize
import pdb
import yaml
import time
import scipy.io as sio
from datetime import datetime
import r... |
#!/usr/bin/env python
import pylab as plt
import scipy
import numpy as np
from mpl_toolkits.basemap import Basemap
import sys
import argparse
import scipy.ndimage
import pyfits
import os
import myutils
import mgc3_lib
import gzip
import bovy_coords as bc
#----------------------------------------------
__version__ = '1... |
# --------------------------------------------------------------------------------------
# Copyright 2016, <NAME>, <NAME>, <NAME>, <NAME>
# Hummingbird is distributed under the terms of the Simplified BSD License.
# -------------------------------------------------------------------------
from __future__ import print_f... |
import mygene
import pandas as pd
import scipy
import scipy.stats as ss
from tqdm import tqdm
def compute_bulk_correlations(
ad,
bulk_expr_path,
mapping_file_path,
imputed_obsm_key=None,
rpkm_prefix="900",
tf_list=None,
):
ad.var_names_make_unique()
# Read the mapping file which maps... |
# Code to prepare the NUS dataset, go through all the files, process each file and save the data
import os,re
import collections
import numpy as np
from scipy.stats import norm
import pyworld as pw
import matplotlib.pyplot as plt
import sys
import h5py
from synth.utils import sig_process, segment, vamp_notes, audio_p... |
#!/usr/bin/env python3
"""
Phonon
Only harmonic Phonon subroutines implemented
All numerically heavy computations are in f90 (f_phonon.f90)
"""
#import os
#from itertools import islice, product
from ..util.tool import my_flatten
#from ..util.string_utils import fn_available
from ..symm_kpts import HighSymmKpath
from... |
<reponame>leemengwei/my_mmdetection
from argparse import ArgumentParser
from mmdet.core import post_processing
import sys, os
from IPython import embed
from mmdet.apis import inference_detector, init_detector, show_result_pyplot
import tqdm
import re
import pickle
import seaborn as sns
from scipy import stats
import nu... |
<reponame>peterezzo/vmscripts
#!/usr/bin/env python3
# coding=utf-8
from subprocess import PIPE, run
from statistics import mean
HOSTS = [
'www.bing.com',
'www.google.com',
'mail.google.com',
'www.youtube.com',
'www.amazon.com',
'www.amazonvideo.com',
'd2lkq7nlcrdi7q.cloudfront.net',
'... |
"""
Copyright 2017 <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 agreed to in writing, software
distrib... |
# Copyright 2021 <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 agreed to in writing, softw... |
<reponame>a68b57/rl_for_set_down<filename>RNN/toolkit.py<gh_stars>0
from keras.models import model_from_json
from matplotlib import pyplot as plt
from scipy.io import loadmat, savemat
import numpy as np
from sklearn import model_selection
import glob
import time, os
import matplotlib.gridspec as gridspec
import tensorf... |
<filename>job.py
# Import all packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
# Import dataset from url
from urllib.request import urlretrieve
url = 'https://assets.datacamp.com/production/course_2023/datasets/dob_job_application_filings_subset.csv'
# urlretrieve(url,... |
<filename>general-models/MFGrid/mfgrid/array_sample.py<gh_stars>1-10
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from math import cos, sin
def modflow_global_coords(nrow, ncol, delr, delc, xoffset, yoffset, the... |
###############################################################################
# TriaxialGaussianPotential.py: Potential of a triaxial Gaussian stratified
# on similar ellipsoids
#
# \rho(x,y,z) ~ exp(-m^2/[2\sigma^2])
#
# ... |
<reponame>nrjl/GPN
import numpy as np
from scipy.special import ndtr as std_norm_cdf
class NormCDF(object):
def logpyf(self,y,f):
return np.log(std_norm_cdf(y*f))
def dlogpyf_df(self,y,f):
std_norm_cdf
y*
def logistic_function(z):
return 1.0/(1 + np.exp(-z))
def ClassifierLikeli... |
import numpy as np
import pandas as pd
import scipy.stats
import scipy.optimize
import edhec_risk_kit
def drawdown(return_series: pd.Series):
"""
Takes a time series of asset returns
Computes and returns a DataFrame that contains:
- Wealth index
- Previous peaks
- Percent drawdown... |
import os
import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.io as scio
from tqdm import tqdm
from dataloaders import make_data_loader
from dataloaders.custom_transforms import denormalizeimage
from modeling.sync_batchnorm.replicate import DataParallelWithCallback, patch_replication_callback
fr... |
# Copyright (c) 2017, Lehrstuhl fuer Angewandte Mechanik, Technische Universitaet Muenchen.
#
# Distributed under BSD-3-Clause License. See LICENSE-File for more information.
#
"""
Example: Comparison of AMfe's pinciple angles and SciPy.linalg's subspace angles.
"""
import amfe
import numpy as np
import scipy as sp
i... |
#!/usr/bin/env python3
import fileinput
import re
import statistics
BENCH_NAME = re.compile(r'(\w+)')
EST_CYCLES = re.compile(r' +Estimated Cycles: +(\d+) +\((.*)\)')
name = ''
printed_headers = False
ratios = []
for line in fileinput.input():
if match := BENCH_NAME.match(line):
name = match[1]
if m... |
from __future__ import print_function
import cv2
from scipy.ndimage.filters import gaussian_filter
import numpy as np
# cv2.createBackgroundSubtractorKNN( [, history[, dist2Threshold[, detectShadows]]] )
# cv2.createBackgroundSubtractorKNN(50, 400.0, True)
#backSub = cv2.createBackgroundSubtractorKNN(50, 300.0, False)... |
"""
Authors: <NAME>, <NAME>
utility function for reading and preapering the data for IEI and IEIO.
"""
import os
import numpy as np
import pandas as pd
from scipy.io import arff
from scipy.io import loadmat
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
def preprocessing(data_path):
np.rando... |
<gh_stars>1-10
"""
Some tests with CUDA
"""
import numpy as np
def deviceInfo():
import pycuda.driver as drv
drv.init()
print "%d device(s) found." % drv.Device.count()
for ordinal in range(drv.Device.count()):
dev = drv.Device(ordinal)
print "Device #%d: %s" % (ordinal, dev.name())
... |
<filename>euler-381.py
import sympy
from Primer import mod_inv
from Progress import Progress
progress = Progress()
max_p = 10**8
ans = 0
for p in sympy.primerange(5, 10**8):
# p1 = p - 1
# p2 = 1
# p3 = p // 2
# p4 = pow(6, p - 2, p)
# p5 = pow(p - 24, p - 2, p)
p1 = mod_inv(-1, ... |
from sklearn.base import TransformerMixin, BaseEstimator
import numpy as np
import scipy as sp
from scipy.misc import comb
from scipy.sparse import csr_matrix, coo_matrix
from code import interact
#TODO add include_bias support
class SparsePolynomialFeatures(TransformerMixin, BaseEstimator):
def __init__(self, de... |
"""
A quick start for aTEAM/optim
More test example can be found in aTEAM/test/optim*.py.
"""
from numpy import *
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from aTEAM.optim import NumpyFunctionInterface,ParamGroupsManager
"""
Example 1
Let us start with an example.
At f... |
<gh_stars>0
from scipy.optimize import linear_sum_assignment
import rltk.utils as utils
from rltk.similarity.jaro import jaro_winkler_similarity
MIN_FLOAT = float('-inf')
def hybrid_jaccard_similarity(set1, set2, threshold=0.5, function=jaro_winkler_similarity, parameters=None):
"""
Generalized Jaccard Measu... |
# coding:utf-8
import os
import cv2
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from scipy.stats import kurtosis
from MaskLoader import MaskLoader
# from CityscapesMaskLoader import CityscalesMaskLoader
from utils import (
IOUMetric,
fast_ista,
prepare_distance_t... |
<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize
from scipy.signal import find_peaks
import csv, similaritymeasures
import os, math
from datetime import date, timedelta
from pymongo import MongoClient, ASCENDING
from scipy.optimize import leastsq
from scipy.interpolate import interp1... |
### ------------------------------------------------------------------------- ###
# DEFINITELY NEED THIS SCRIPT!
### Create CSV files with average luminance per frame of stimulus vids
### use world camera vids for timing, stretch and interpolate raw stim vid lum values
### output as data files categorized by calibratio... |
from scipy import signal
import numpy as np
from datetime import datetime
from .date_time import datetime64_to_milliseconds, datetime_to_milliseconds
from scipy.interpolate import interp1d
def as_2d_array(func):
def wrapper(X, *args, **kwargs):
if len(X.shape) == 1:
X_2d = np.reshape(X, (1, X.s... |
#------------------------------------------------------------------------------
# Copyright (C) 2007-2010 <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/... |
<filename>modelproject/test2.py<gh_stars>0
#%%
import numpy as np
import scipy as sp
from scipy import linalg
from scipy import optimize
from scipy import interpolate
import sympy as sm
import matplotlib.pyplot as plt
import math
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
#%%
def util(q1,q2,alpha... |
<reponame>saustinp/3D-CG<gh_stars>0
import numpy as np
from scipy.io import loadmat
import shelve
import sys
sys.path.insert(0, '../util')
from gmshcall import gmshcall
import pickle
def process_mesh(filename, ndim, nelem, nface=None):
"""
ndim: dimensionality of the mesh
nelem: element ID of the highest d... |
<filename>PySA_2.0.1_20180205.py
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
from PySide import QtCore, QtGui
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.ticker as tick
tick.MultipleLocator(base=25.0)
from ... |
# -*- coding: utf-8 -*-
#############################################################################
# SRW Brightness Calculation
#############################################################################
from scipy import special
import math
import numpy as np
import sirepo.resource
#General constants
_ElMass_kg... |
<filename>unit/processor.py
# coding=utf-8
import logging
from typing import Type, TextIO, Iterable
import numpy
from scipy import ndimage
from unit.detectors.hough_circle import HoughCircleDetector
from unit.exporters.base import BaseExporter
from unit.exporters.csv import CsvExporter
from unit.filters.edge_detectio... |
# Import modules
import os
import re
import sys
try:
get_ipython().system('pip install gym')
get_ipython().system('pip install tqdm')
get_ipython().system('pip install dropbox')
get_ipython().system('pip install gym[atari]')
get_ipython().system('apt-get install -y cmake libopenmpi-dev python3-dev z... |
<filename>evaluate.py
from __future__ import print_function
import torch
from model import roundNet
from utils import roundDataset, maskedMSETest, anchor_inverse, multi_pred, horiz_eval
from torch.utils.data import DataLoader
import numpy as np
import scipy.io as scp
## Network Arguments
from model_args import args
ar... |
############### IMPORT PACKAGES ##################
import numpy as np
from numpy.linalg import inv as inv #Used in kalman filter
#Used for naive bayes decoder
try:
import statsmodels.api as sm
except ImportError:
print("\nWARNING: statsmodels is not installed. You will be unable to use the Naive Bayes Decoder... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.