text string |
|---|
import csv
import numpy as np
lonMin = -74.1 # minimum longitude
lonMax = -73.7
lonStep = 0.0025 # defines cell size
latMin = 40.6 # minimum latitude
latMax = 41.0
latStep = 0.0025 # defines cell size
latLen = int((latMax - latMin) / latStep) + 1 # number of cells on the y-axis
lonLen = int((lonMax - lonMin) / ... |
#file reading portion of 190621_accel_combined only
import os
import glob
from datetime import datetime, timedelta
import time
import csv
import numpy as np
import statistics
import json
import geopy.distance
import urllib.request
from scipy import interpolate
from scipy import fft
from scipy import signal
import matp... |
<filename>4 - Prediction and Evaluation/Generate_Index_For_False_Positive_Patches.py
#! /usr/bin/env python3
from scipy.misc import imsave
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os.path as osp
import openslide
from pathlib import Path
from skimage.filters import threshol... |
<gh_stars>10-100
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Rank documents with TF-IDF scores"""
import argparse
import logging
import numpy as np
impo... |
<filename>gp_lib/kernels.py
import numpy as np
import scipy as sp
import scipy.spatial
from functools import reduce
class Kernel(object):
def __call__(self, x, y):
"""
Returns
-------
kernel: m x n array
"""
raise NotImplementedError
def trace_x_x(self, x):
... |
<gh_stars>0
"""
Call variant based on a list of SAMMPileUpRecord where list[i] is the record of i-th position
Most of the code follows Juliet's code at
https://github.com/PacificBiosciences/minorseq/blob/develop/src/AminoAcidCaller.cpp
"""
import os, sys
import scipy.stats as stats
from collections import Counter, n... |
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import os, nibabel
import sys, getopt
import PIL
from PIL import Image
import imageio
import scipy.misc
import numpy as np
import glob
from torch.utils import data
import torch
import random
from .augmentations import augment_spatial, ComposeTest,... |
<reponame>shashankballa/shredder-v2-self-supervised<filename>mutual_info_std20_self_lenet_nonsen.py
# Email <EMAIL> in case of any questions
import torch
import torch.nn as nn
import torch.nn.functional as F
from lenet import LeNet5
from torchvision.datasets.mnist import MNIST
import torchvision.transforms as transform... |
<filename>Solutions_Python/disorderly_escape.py
from math import factorial
from collections import Counter
from fractions import gcd #This does not work in Python 3 however Google's foobar uses Python 2
def cycle_count(c, n):
cc = factorial(n)
for a, b in Counter(c).items():
cc //= (a**b)*factorial(b)... |
from wobbles.workflow.compute_distribution_function import compute_df
from wobbles.workflow.integrate_single_orbit import integrate_orbit
from wobbles.workflow.subhalos_and_dwarfs import *
from galpy.potential.mwpotentials import PowerSphericalPotentialwCutoff, MiyamotoNagaiPotential
from wobbles.disc import Disc
from ... |
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
# Plot Forward Model Results
n_plots = 3 # number of examples to plot
samp_index = [0,1,2,3]
# Load the test results for the multi-fidelity forward model
results = sio.loadmat('results/holographic_forward_model_examples.mat')
x_exp_... |
<gh_stars>1-10
"""
legacyhalos.misc
================
Miscellaneous utility code used by various scripts.
"""
import os, sys
import numpy as np
def viewer_inspect(cat, galaxycolname='GALAXY'):
"""Write a little catalog that can be uploaded to the viewer.
"""
out = cat[galaxycolname, 'RA', 'DEC']
out.... |
#!/usr/bin/env python
#
# Created by: <NAME>, September 2002
#
from numpy.testing import TestCase, run_module_suite, assert_equal, \
assert_array_almost_equal, assert_
from numpy import ones
from scipy.linalg import flapack, clapack
class TestFlapackSimple(TestCase):
def test_gebal(self):
a = [[1,2... |
<reponame>RICE-EIC/GCoD
from torch_geometric.datasets import Planetoid, TUDataset, Flickr, Coauthor, CitationFull
import argparse
import os
import torch_geometric.transforms as T
import dgl
import torch
from dgl.distributed import partition_graph
from torch_geometric.data import Data
from torch_sparse import SparseTens... |
# for more information read "19-Intro2ML-HodaDataset.ipynb"
import cv2
import numpy as np
from scipy import io
def load_hoda(training_sample_size=1000, test_sample_size=200, size=5):
#load dataset
trs = training_sample_size
tes = test_sample_size
dataset = io.loadmat('./dataset/Data_hoda_full.mat')
... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import zip
from builtins import range
from past.builtins import basestring
from past.utils import old_div
from builtins import object
import os
import time
from collections... |
"""
==================================
Exploratory analysis of cue epochs
==================================
Compute descriptive statistics and exploratory analysis plots
for cue locked ERPs.
Authors: <NAME> <<EMAIL>>
License: BSD (3-clause)
"""
import numpy as np
from scipy.stats import ttest_rel
import matplotli... |
#!/usr/bin/env python
# coding=utf-8
# Author : <NAME>
# Created : 2017.1.22
# Modified : 2017.1.22
# Version : 1.0
import random
import numpy as np
from scipy import stats
def do_probability_test(rate):
"""
指定概率必须是两位小数,即0.00~1.00
"""
result = random.randint(0, 100)
if result < rate*100... |
<gh_stars>0
import scipy.optimize as op
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.cm as cm
import itertools
import math
import sys
import io
import os
figpath="fig/"
title="star5to1"
cmap=cm.get_cmap("rainbow")
def replacefig(fig):
... |
<reponame>harmslab/likelihood
__description__ = \
"""
Fitter subclass for performing maximum likelihood fits.
"""
__author__ = "<NAME>"
__date__ = "2017-05-10"
from .base import Fitter
import numpy as np
import scipy.stats
import scipy.optimize as optimize
import warnings
class MLFitter(Fitter):
"""
Fit the... |
from __init__ import *
import sys
from fractions import Fraction
from polymage_common import set_ghosts
sys.path.insert(0, ROOT)
from compiler import *
from constructs import *
def interpolate(U_, correction, l, name, pipe_data):
if U_ == None:
return correction
z = pipe_data['z']
y = pipe_dat... |
<reponame>edfong/npl
"""
Load Genetics dataset and preprocess
"""
import numpy as np
import pandas as pd
import scipy as sp
from scipy import special
import random
import pickle
x_train = pd.DataFrame(np.random.randn(500,50))
#take first 500 points
x_train = x_train[0:500]
#take first 50 covariates
x_train = x_trai... |
__author__ = 'sibirrer'
# this file contains a class to compute the Navaro-Frenk-White profile
import numpy as np
import lenstronomy.Util.util as util
import scipy.interpolate as interp
from lenstronomy.LensModel.Profiles.base_profile import LensProfileBase
from lenstronomy.LensModel.Profiles.sersic_utils import Sers... |
"""Provide functions used to estimate coexistence points"""
import numpy as np
from scipy import optimize
def delta_f(f1new: float,f2new: float,f: np.ndarray) -> np.ndarray:
"""
Calculate the difference between next and current integration points
Parameters
----------
f1new : float
The nex... |
from src.model.multi_distance_models import multi_distance_models
from sklearn import preprocessing
import pickle as pk
import numpy as np
import scipy as sp
import argparse
import os
import sys
import random
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='evaluate the token based tf-idf v... |
<gh_stars>1-10
# coding: utf-8
from mpi4py import MPI
from sympy import lambdify
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from mpl_toolkits import mplot3d
from collections import OrderedDict
from psydac.linalg.utilities import array_to_stencil
from psydac.fem.basic ... |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# co... |
import networkx as nx
from matlab import engine
import scipy.io
import os
import time
import tnetwork as tn
import io
import scipy
def _runMatlabCode(matrix, matlab_session):
#matrix = scipy.sparse.coo_matrix(matrix)
dir = os.path.dirname(__file__)
visuAddress = os.path.join(dir, "GenLouvain-master")... |
"""`get_entropy` code comes from https://github.com/paulbrodersen/entropy_estimators/blob/master/entropy_estimators/continuous.py"""
import numpy as np
from scipy.spatial import KDTree
from scipy.special import gamma, digamma
def get_entropy(x, k=1, norm='max', min_dist=0., workers=1):
"""
Code source: htt... |
# This script is part of the supporting information to the manuscript entitled
# "Assessing the Calibration in Toxicological in Vitro Models with Conformal Prediction".
# The script was developed by <NAME> in the In Silico Toxicology and Structural Biology Group of
# Prof. Dr. <NAME> at the Charité Universitätsmedizin ... |
<reponame>mlazaric/PhotonSimulation
"""
Constants for the project, includes various starting conditions and other information.
"""
from sympy import Rational, Point
# Step used for ray tracing to find the circle which the src hits.
STEP = 0.1
# Radius of the circles.
RADIUS = Rational('1/3')
# Multiplication factor... |
from dask.distributed import Client, LocalCluster, performance_report
import dask.dataframe as dd
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.svm import SVC
from sklearn.metrics import f1_score, accuracy_score, recall_score, classification_report
import os, json, pickle, csv
import pandas as pd... |
<reponame>LiGhtime/CSCI4622
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import csv
import statistics as st
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.metrics... |
#!/usr/bin/python
import numpy as np
from ffthompy.general.base import Timer
from ffthompy.matvec import VecTri
def linear_solver(Afun=None, ATfun=None, B=None, x0=None, par=None,
solver=None, callback=None):
"""
Wraper for various linear solvers suited for FFT-based homogenization.
"""
... |
import pickle as pickle
import numpy as np
import pandas as pd
import os
import sys
from subprocess import call
import matplotlib
#matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator
import scipy
import json
from sklearn.decomposition import PCA as skPCA
from scipy.spati... |
'''
------------------------------------------------------------------------
Last updated 7/17/2015
Returns the wealth for all ages of a certain percentile.
This py-file calls the following other file(s):
data/wealth/scf2007to2013_wealth_age_all_percentiles.csv
utils.py
This py-file creates t... |
import re
import time
import pickle
import numpy as np
import tensorflow as tf
import scipy.sparse as sp
class GNN(): #2 layers
"""A class of graph neural network."""
def __init__(self, args):
self.args = dict(args._get_kwargs())
for key, value in self.args.items():
... |
import os
import unittest
import numpy as np
from scipy import signal
from mne import create_info, EpochsArray
import Offline.model as Model
import Offline.utils as util
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from config import merge_cfg_from_file
merge_cfg_from_file('./... |
from __future__ import annotations
from datetime import datetime
import numpy as np
import math
import xarray
import scipy.interpolate as interp
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from ..utils import git_meta
from ..read import get_lxs
from .constants import R_EARTH, REF_ALT
from .... |
<gh_stars>1-10
#!/usr/bin/env python2.7
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# Capriqorn --- CAlculation of P(R) and I(Q) Of macRomolcules in solutioN
#
# Copyright (c) <NAME>, <NAME>, and contributors.
# See... |
"""Automated Rectification of Image.
References
----------
1. Chaudhury, Krishnendu, <NAME>, and <NAME>.
"Auto-rectification of user photos." 2014 IEEE International Conference on
Image Processing (ICIP). IEEE, 2014.
2. Bazin, Jean-Charles, and <NAME>. "3-line RANSAC for orthogonal
vanishing point ... |
<filename>datastock/_class1_interpolate.py
# -*- coding: utf-8 -*-
# Builtin
import warnings
# Common
import numpy as np
import scipy.interpolate as scpinterp
# local
from . import _generic_check
# #############################################################################
# ##################################... |
import sys
import os
cwd=os.getcwd()
work_dir = os.path.join(cwd,'benchmarks')
# os.chdir(work_dir)
sys.path.append(work_dir)
import tensorflow as tf
import benchmark_cnn
from config import Options
from utils import *
from model_builder import Model_Builder
import numpy as np
import random
import math
import copy
... |
"""
Generic FPM solver developed by Kristina and David as a course project
<NAME> <EMAIL>
<NAME> <EMAIL>
May 10, 2017
"""
from abc import ABCMeta, abstractmethod
import sys
import os
import numpy as np
import numpy.linalg as la
import time
import labalg.iteralg as algorithms
import pyfftw
import glob
imp... |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import csv
import json
import os
import random
import unittest
import numpy as np
import scipy.constants as const
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
from pymatgen.util.tes... |
#!/usr/bin/env python
# coding: utf-8
import scipy.optimize
import json
import numpy as np
import re
import sys
import math
import argparse
from collections import defaultdict
from pprint import pprint
def float_list(s):
return [float(x) for x in s.split(",")] if s else []
parser = argparse.ArgumentParser()
pars... |
<reponame>eandklahn/molmag_ac_gui<gh_stars>0
#std packages
import os
from subprocess import Popen, PIPE
#third-party packages
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.constants as sc
from scipy.optimize import curve_fit
from lmfit import Parameters, minimi... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import sys
import pprint
import torch
import scanpy as sc
from collections import defaultdict
from sklearn.metrics import r2_score
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.decomposition import KernelP... |
import sys
import os
from warnings import warn
import re
import numpy as np
from matplotlib import pyplot as plt
import scipy.constants as co
from spacepy import pycdf
import h5py
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage[varg]{txfonts}')
plt.rc('axes', titlesize=54)
plt.rc('font', fami... |
#!/usr/bin/env python
'''
Code for isotope diffusion.
'''
import numpy as np
import json
import scipy.interpolate as interpolate
from constants import *
import os
import sys
class ModelOutputs:
'''
Class to handle making the model output files
'''
def __init__(self, config, MOd, TWlen, init_time, Glen... |
<filename>Python/random-number-generator.py
# https://www.hackerrank.com/challenges/random-number-generator/problem
from fractions import Fraction
test_cases = int(input())
for test_case in range(test_cases):
a, b, c = map(int, input().split())
p, q = max(a, b), min(a, b)
if a + b < c:
ans = Fra... |
#!/usr/bin/env python
#
# Copyright 2011,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your optio... |
<reponame>mlcb-thu/DeepRCI
from tqdm import tqdm
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import pickle as pkl
np.random.seed(1234)
df = {'interaction':[],'type':[],'chromosome':[]}
## 设定需要分析的染色体序号
chrs= 'chr1'
annotation = '../../ref/gencode.v38.chr_patch_hap... |
"""
FBM_single_functions.py
This script contains functions for activating and testing of Fractional Brownian Motion
single-trajectory networks trained to estimate the Hurst exponent.
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from keras.models import load_model
from utils import fbm_diff... |
"""
The ProblemManager contains all of the
different classes of problems that windse can solve
"""
import __main__
import os
### Get the name of program importing this package ###
if hasattr(__main__,"__file__"):
main_file = os.path.basename(__main__.__file__)
else:
main_file = "ipython"
### This checks... |
import os
import scipy.io
import scipy.ndimage
import numpy as np
from PIL import Image
def label2d_array_nn_scaling(label2d, new_h, new_w):
"""
implement nearest neighbor scaling for 2d array
:param label2d: [H, W]
:return: label_new: [new_h, new_w]
"""
scale_h = new_h / label2d.shape[0]
... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
# author: kuangdd
# date: 2020/4/13
"""
"""
from pathlib import Path
from functools import partial
from multiprocessing.pool import Pool
from matplotlib import pyplot as plt
from tqdm import tqdm
import collections as clt
import os
import re
import json
import numpy as np
im... |
<reponame>GSEL9/dgufs
# -*- coding: utf-8 -*_
#
# dgufs.py
#
# This module is part of dgufs
#
"""
The Dependence Guided Unsupervised Feature Selection algorithm by Jun Guo and
Wenwu Zhu (2018).
"""
__author__ = '<NAME>'
__email__ = '<EMAIL>'
import numpy as np
import pandas as pd
import utils
#from dgufs import u... |
<filename>qiskit_dynamics/solvers/solver_classes.py<gh_stars>0
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree ... |
<reponame>dmquinones/qiskit-terra
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/l... |
from sympy.parsing.mathematica import mathematica
from sympy import sympify
def test_mathematica():
d = {
'- 6x': '-6*x',
'Sin[x]^2': 'sin(x)**2',
'2(x-1)': '2*(x-1)',
'3y+8': '3*y+8',
'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
'x+y': 'x+y',
'355/113... |
<filename>shors/qiskit/interactive_shors_factoring/Shor_Sequential_QFT.py
"""
This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second
simplification introduced by the base paper used.
The circuit is general, so, in a good computer that can support s... |
from typing import *
import numpy as np
import loompy
import logging
import scipy.sparse as sparse
class LayerManager:
"""
Manage a set of layers with a backing HDF5 file store
"""
def __init__(self, ds: Any) -> None: # Note: can't give type for ds because it will be circular and mypy doesn't support it
"""
... |
<reponame>dafeda/HistoryMatching
"""Generate initial reservoir realisations with geostatistical methods."""
import numpy as np
import scipy.linalg as sla
from matplotlib import pyplot as plt
from mpl_tools.place import freshfig
from numpy.random import randn
def variogram_gauss(xx, r, n=0, a=1/3):
"""Compute the... |
<reponame>JelleAalbers/hypney
import hypney
import numpy as np
from scipy import stats
def test_cut():
m_base = hypney.models.norm()
m_cut = m_base.cut(0, None)
assert isinstance(m_cut.simulate(), np.ndarray)
assert m_cut._cut == ((0, float("inf")),)
assert m_cut.cut_efficiency() == 0.5
asser... |
#####################################################################################################
# Purpose: calculate artificial structure, i.e. fluctuations in galaxy counts, resulting from
# imperfect observing strategy (OS). Includes the functionality to account for dust extinction,
# photometric calibration er... |
<gh_stars>0
import re
import math
from Bio import SeqIO
from scipy.integrate import quad
from terminaltables import AsciiTable
pathToFile = "NC_001416.fasta" # Canlımızın sekanslarının bulunduğu dosya
fasta_sequences = SeqIO.parse(open(pathToFile), 'fasta') # Dosyamızdaki tüm fasta sekanslarını getiren Iterator
seque... |
<filename>code/ornaments/bessel-functions.py
# ----------------------------------------------------------------------------
# Title: Scientific Visualisation - Python & Matplotlib
# Author: <NAME>
# License: BSD
# ----------------------------------------------------------------------------
import numpy as np
from sc... |
from sklearn.cluster import MeanShift, estimate_bandwidth, MiniBatchKMeans, KMeans, Birch, DBSCAN
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.metrics import accuracy_score, classification_report
from sk... |
<gh_stars>1-10
from __future__ import absolute_import, division, print_function
import os
import glob
#os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import numpy as np
import fid
from scipy.misc import imread
import tensorflow as tf
import cv2
import argparse
import random
parser = argparse.ArgumentParser()
parser.add_argu... |
"""
my NN library
(based on Yoav's)
"""
import _dynet as dynet
import numpy as np
import array
from bilstm_aux.lib.constants import START_TAG, END_TAG
from scipy import linalg
def init_dynet(seed):
"""initialize DyNet"""
dyparams = dynet.DynetParams()
# Fetch the command line arguments (optional)
dypa... |
from Bio import SeqIO
from Bio.SeqUtils import GC
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
from sklearn.utils import resample
import scipy.sparse
import pandas as pd
import pickle
import argparse
import os
parser = argparse.ArgumentParser(description="Kmer Counter for RNA viruses")
parser.add_argument('-... |
<filename>mcos/optimizer.py
from __future__ import division
from abc import ABC, abstractmethod
from typing import Dict, List
import numpy as np
import pandas as pd
import scipy.cluster.hierarchy as sch
from numpy.linalg import inv, pinv
#Compute the (multiplicative) inverse of a matrix.
from pypfopt.efficient_fron... |
<gh_stars>1-10
# 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
# A adaptation of https://www.kaggle.com/jhoward/nb-svm-strong-linear-baseline
# which is then based on https://nlp.stanford.edu/pu... |
import pandas as pd
from scipy import misc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.pyplot as plt
import glob
from sklearn.manifold import Isomap
# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')
import os
os.chdir("Datasets")
samples = []
#
# Write a for-... |
<reponame>sgg10/arsp_solver_api<gh_stars>0
from app.utils.methods import BaseMethod
from numpy import *
from sympy import *
class SOR(BaseMethod):
def __init__(self, n, A, b, x0, omega, iterations, tolerance):
self.n = int(n)
self.A = A
self.b = b
self.x0 = x0
self.omega = ... |
<filename>preDeal/utils.py
import datetime
import scipy as sp
from keras import backend as K
def my_logloss(act, pred):
epsilon = 1e-15
pred = K.maximum(epsilon, pred)
pred = K.minimum(1 - epsilon, pred)
ll = K.sum(act * K.log(pred) + (1 - act) * K.log(1 - pred))
ll = ll * -1.0 / K.shape(act)[0]
... |
from python_speech_features import mfcc
import scipy.io.wavfile as wav
import matplotlib.pyplot as plt
from scipy import signal
(rate, sig) = wav.read("D:\\Kaggle_Speech_Recognition\\Datasets\\train\\audio\\bed\\00f0204f_nohash_0.wav")
mfcc_feat = mfcc(sig, rate)
print(mfcc_feat[1:3,:])
samples_rate, samples =... |
from scipy.ndimage import uniform_filter, gaussian_filter
from scipy import interpolate
import numpy as np
from numpy_groupies import aggregate_np as aggregate
import matplotlib.pyplot as plt
from matplotlib import patches
from mpl_toolkits.axes_grid1 import make_axes_locatable
from copy import deepcopy
from tqdm impo... |
"""
desispec.quicklook.qlresolution
===============================
Quicklook version of resolution object that can
calculate resolution efficiently from psf information
Author: <NAME>
"""
import numpy as np
import scipy.sparse
import scipy.special
class QuickResolution(scipy.sparse.dia_matrix):
"""
Quick... |
import sys
import typing
import numpy as np
import scipy.special
def solve(n: int, d: int, x: int, y: int) -> typing.NoReturn:
if x % d or y % d:
print(0)
return
x, y = abs(x) // d, abs(y) // d
if n < x + y or (n - x - y) & 1:
print(0)
return
k = n - x... |
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from gene_finding.models import load_model, EnsModel
from gene_finding.borda import rank_aggregate_Borda
import os
import argparse
import torch.nn.functional as F
parser = argparse.ArgumentParser()
par... |
from model.abstract_VAE import VAE
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from scipy.stats import norm
class StableBCELoss(nn.modules.Module):
def __init__(self):
super(StableBCELoss, self).__init__()
def forward(self, input, target):
neg_abs =... |
<reponame>maffei2443/metastream
# from IPython.core.display import display, HTML
# display(HTML("<style>.container { width:100% !important; }</style>"))
import numpy as np
import pandas as pd
import scipy.stats
from pathlib import Path
np.random.seed(42)
# Métricas e preprocessamento
from sklearn.metrics import zero_... |
import os
import scipy.interpolate as spi
dataLabel = ["one", "two", "three", "four"]
dataRoot = "../toneclassifier/train"
normalLen = 1000
for label in dataLabel:
subsetPath = dataRoot + "/" + label
dataset = set()
for filename in os.listdir(subsetPath):
if filename[0] == ".":
conti... |
<reponame>Freya-Antonia/Modelflow2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 2 17:01:49 2018
@author: hanseni
Functions placed here are included in the Pyfs business language
"""
from math import exp, log, sqrt
from numpy import transpose , array
from scipy.stats import norm,lognorm
from scipy.stats import ga... |
##################################################################################
# This work is an extension of LoDE code developed by <NAME>
# (Email: <EMAIL>)
# Author: <NAME>
# Email: <EMAIL>
# Date: 2020/09/03
# Centre for Intelligent Sensing, Queen Mary University of London, UK
#
#########... |
# This is a small chunk of code from the skimage package. It is reproduced
# here because all we need is a couple color conversion routines, and adding
# all of skimage as dependecy is really heavy.
# Copyright (C) 2019, the scikit-image team
# All rights reserved.
# Redistribution and use in source and binary form... |
<reponame>pcmagic/stokes_flow
# coding=utf-8
import sys
import petsc4py
petsc4py.init(sys.argv)
import numpy as np
from time import time
from scipy.io import savemat
# from src.stokes_flow import problem_dic, obj_dic
from petsc4py import PETSc
from src import stokes_flow as sf
from src.myio import *
from src.objComp... |
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram
def corr2_coeff(A, B):
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:, None]
B_mB = B - B.mean(1)[:, None]
# Sum of squares across rows
ssA = (A_mA**2).sum(1)
ssB = (B_mB*... |
# USAGE
# python detect.py --input pedestrians.mp4
# import the necessary packages
from config import config
from detect import detect_people
from scipy.spatial import distance as dist
import numpy as np
import argparse
import imutils
import cv2
import os
#constructing the argument parse to parse the required argume... |
<reponame>saumya-madhavan/ga-learner-dsmp-repo<filename>Banking-Inferences/code.py
# --------------
import pandas as pd
import scipy.stats as stats
import math
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#Sample_Size
sample_size=2000
#Z_Critical Score
z_critical = stats.norm.ppf(q ... |
<filename>t13_mode1.py
# Find mode of n numbers
import statistics
A = [19, 18, 46, 18, 18, 19]
print(statistics.mode(A))
# the above only works if there is only 1 mode
# what if there is more than 1 mode?
|
"""Convolutional dictionary learning"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import numpy as np
from scipy.stats import levy_stable
from .utils import check_random_state
def estimate_phi_mh(X, Xhat, alpha, Phi, n_iter_mcmc, n_burnin_mcmc,
... |
import unittest
import numpy as np
import scipy.sparse as sps
import scipy.sparse.linalg as spsla
import sadptprj_riclyap_adi.lin_alg_utils as lau
import sadptprj_riclyap_adi.proj_ric_utils as pru
# unittests for the helper functions
class TestProjLyap(unittest.TestCase):
def setUp(self):
self.NV = 500... |
<gh_stars>0
import settings
import glob
import datetime
import os
import sys
import numpy
import cv2
from collections import defaultdict
from skimage.segmentation import clear_border
from skimage.measure import label, regionprops
from skimage.morphology import disk, dilation, binary_erosion, binary_closing
f... |
from fractions import Fraction as frac
from itertools import combinations
import sys
def readint():
return int(sys.stdin.readline())
def readints():
return [int(x) for x in sys.stdin.readline().split()]
T = readint()
for t in range(1, T+1):
C = readint()
data = readints()
if data[0] == 0 o... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Copyright (c) 2019, Eurecat / UPF
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of... |
from sympy.liealgebras.cartan_type import CartanType
from sympy.matrices import Matrix
def test_type_G():
c = CartanType("G2")
m = Matrix(2, 2, [2, -1, -3, 2])
assert c.cartan_matrix() == m
assert c.simple_root(2) == [1, -2, 1]
assert c.basis() == 14
assert c.roots() == 12
assert c.dimensio... |
# WARNING: Importing more than the bare minimum with mpmath will result in errors on eval() below.
# This is because we need SymPy to evaluate that expression, not mpmath.
from mpmath import mp, mpf, sqrt, pi
from random import seed, random
from trusted_values_dict import trusted_values_dict
from sympy import cse
# T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.