sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
7faa5b4125ad3dc0c7689bc37a13953b42d2700b685ad09ed2614250802bab3f | Python | 345 | 19 | #! /usr/bin/env python
# usage: python filter_branch.py <tree_file>
from treeshrink.Tree_extend import MVR_Tree
from sys import argv
from os.path import splitext
tree_file = argv[1]
outfile = argv[2]
base_name,ext = splitext(tree_file)
a_tree = MVR_Tree(tree_file=tree_file)
a_tree.filter_branch()
a_tree.tree_as_n... |
d61bba519aeefe59e3a5f27700925d35e65006c246fb68c3774f485f53d7564c | Python | 345 | 6 | from .misc import mask2index, index2mask, torch_groupby
from .mic import dx_mic, dx_mic_ortho
from .edges import add_edges, mask_edges
from .angles import bond_angles, dihedral_angles
from .cluster import knn_graph, radius_graph, periodic_radius_graph, periodic_radius_graph_v2
from .scatter import graph_scatter, graph_... |
43cef00a49eeca84e8c52e2fb9383186dcb14a51fd3a69068df5213ece7ad625 | Python | 346 | 10 | """PyCaret 4.0 application-platform backend.
A FastAPI server that fronts the ``pycaret`` engine with a typed REST + WebSocket
API, a SQL-backed workspace/project/experiment/run/pipeline/deployment model, and
in-house pipeline serving. See ``docs/revamp/PLATFORM_PLAN.md`` for the design.
"""
__version__ = "0.1.0a0"
... |
f507934180ecfaf2a833bf7f6bb8646a74dd8a0fb01dfa93b9559e05617370f6 | Python | 346 | 12 | """
algos/ directory is intended for individual functions from core.algorithms
In many cases these algorithms are reachable in multiple ways:
algos.foo(x, y)
Series(x).foo(y)
Index(x).foo(y)
pd.array(x).foo(y)
In most cases we profile the Series variant directly, trusting the performance
of the others to ... |
1ce66b4d09c33f859cac7ea1e1027bf51e8848c7d13dc0345e172948c28f1d2e | Python | 347 | 13 | from PyPDF2 import PdfFileMerger
path = '/home/mkowalska/Marta/kCSD-python/figures/kCSD_properties/'
name = 'small_srcs_all_ele'
merger = PdfFileMerger()
for i in range(100):
pdf = path + name + '/' + str(i) + '.pdf'
merger.append(open(pdf, 'rb'))
with open(path + name + '/' + name + '_err.pdf', 'wb') as fo... |
1c28f0ad72e132871d07dceae81555fc57a4a35d672dd90594031ace6cda7def | Python | 349 | 16 |
import tube2
import cine
import glob
from pathlib import Path
from skimage import io as skio
cine_names = glob.glob("data2/*.cine")
for name in cine_names:
video = cine.Cine(name)
med = video.get_video_median()
p = Path(name)
newname = "medtubes/" + p.stem + ".png"
tube = tube2.tube_crop1(med)
... |
a64e5f395a0fffbbc3361d9c424f05b5963b158b32be0ab77af08ae0f23a3787 | Python | 349 | 7 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2026, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
16aeaef0c1d38b5d89df0397bd33ad47b7983558e0837955c8c97aff79bf0200 | Python | 351 | 12 | import pytest
import pandas as pd
def test_astype_invalid_nas_to_tdt64_raises():
# GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT
idx = pd.Index([pd.NaT.asm8] * 2, dtype=object)
msg = r"Invalid type for timedelta scalar: <class 'numpy.datetime64'>"
with pytest.raises(TypeError, match=msg)... |
75e6b83f66a167bbeab7420dc59b54bd451229b1e39a2695b27235bfa0bbd40f | Python | 351 | 12 | """Utils for handling GPU computation."""
from tensorflow.python.client import device_lib
def get_available_gpus():
"""
Get available GPUs.
From https://stackoverflow.com/a/38580201/10032558.
"""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_pr... |
cbc0063663ea419ee1dd46a07cec20df0cb773d319643296df8e4c278a50bcda | Python | 351 | 12 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .lmdb_dataset import (
LmdbDataset,
SinglePointLmdbDataset,
TrajectoryLmdbDataset,
data_list_collater,
)
from .oc22_lmdb_... |
13f84c6a49286523bf893da49f75251e6b16a90802335891b2bbce9b80aa401d | Python | 353 | 13 | import sys
'''
Prepend article delim !ARTICLE to linetoks to create delim.linetoks. Do nothing if !ARTICLE begins linetoks
'''
firstline = sys.stdin.readline()
if firstline != "!ARTICLE\n":
sys.stdout.write("!ARTICLE\n")
sys.stdout.write(firstline)
for line in sys.stdin.readlines():
sys.stdout.write("!ARTICL... |
4b485adb8ac8cf333ab1caa4cb9bebe2f47131c2e6cab37446831a2dc0c11025 | Python | 354 | 18 | from torch.autograd import Function
class ReverseLayerF(Function):
"""Gradient reversal layer for Pytorch."""
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
output = grad_output.neg() * ctx.a... |
3a7892cb77c76e5657533bf09e695959176fa6f9709ea2a77d7e7325d11ff1e1 | Python | 355 | 11 | import pandas as pd
import pandas._testing as tm
class TestTimedeltaIndexOps:
def test_infer_freq(self, freq_sample):
# GH#11018
idx = pd.timedelta_range("1", freq=freq_sample, periods=10)
result = pd.TimedeltaIndex(idx.asi8, freq="infer")
tm.assert_index_equal(idx, result)
... |
33db4cbf035f8fd01322718fa38e74823befaf39ca8827c9b578d3687d0289d3 | Python | 356 | 19 | from pandas.core.arrays.sparse.accessor import (
SparseAccessor,
SparseFrameAccessor,
)
from pandas.core.arrays.sparse.array import (
BlockIndex,
IntIndex,
SparseArray,
make_sparse_index,
)
__all__ = [
"BlockIndex",
"IntIndex",
"SparseAccessor",
"SparseArray",
"SparseFrameAc... |
a09fe4b3988dc9f130b0e1ec4b59f43d03319a4a417bdaf52ea26fcd6a4f6f5c | Python | 357 | 17 | """
Public API for Rolling Window Indexers.
"""
from pandas.core.indexers import check_array_indexer
from pandas.core.indexers.objects import (
BaseIndexer,
FixedForwardWindowIndexer,
VariableOffsetWindowIndexer,
)
__all__ = [
"BaseIndexer",
"FixedForwardWindowIndexer",
"VariableOffsetWindowIn... |
2ea02735319cde8cb77150e53ca242a147da5967a8902864468f6529ad77954a | Python | 360 | 15 | """Common meta-analytic workflows."""
from .ale import ale_sleuth_workflow
from .conperm import conperm_workflow
from .macm import macm_workflow
from .peaks2maps import peaks2maps_workflow
from .scale import scale_workflow
__all__ = [
"ale_sleuth_workflow",
"conperm_workflow",
"macm_workflow",
"peaks2... |
835bca17d7eb19239cb7105c00dff1e636c04d7dec74f44d8a97bf5c3d8872df | Python | 360 | 11 | import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
print("word syncat")
for line in sys.stdin:
if (line.strip() !='') and (line.strip()[0] != '%'):
T = tree.Tree()
T.read(line)
for word, cat in zip(T.words(), T.syncats(... |
a22588adf382e26fb9a416c962209baa477dd832a3b0693b02277fbaf1df69ff | Python | 361 | 12 | from pathlib import Path
import sys
try:
import msmfcode
except ModuleNotFoundError:
path_root = Path(__file__).parent.resolve().parent
if path_root not in sys.path:
sys.path.append(str(path_root))
else:
print(f'Can\'t import module msmfcode but its module path seems to be in the PYTHON... |
ac9b8a7d4fc8aeaab0ff18dcfdc94170d74db98417b93df5d588ab8672ad2518 | Python | 362 | 12 | from setuptools import setup, find_packages
setup(
name='windseer',
version='1.0.1',
description='Wind prediction around complex terrain using a neural network',
license='BSD 3-Clause',
packages=['windseer'],
author='Achermann Florian',
author_email='florian.achermann@mavt.ethz.ch',
url... |
aa3a185f77506e730f97f81d3cc3b9e4d3e8bf2e4b4e4626f4b016a427944eb5 | Python | 363 | 15 |
# this file exists for the sake of working around a
# bug that occurs with some videos regarding their length
# may have fixed it by addition of line in cine.py
import glob
import meniscus
vidnames = glob.glob("videos_surface_bug/*.cine")
for vidname in vidnames:
cine = meniscus.Cine(vidname)
meniscus.addi... |
aac61586d01a174dad99f04cf38eb17534aad5ce22031adbab4e677631473ab7 | Python | 363 | 13 | import anndata as an
import scanpy as sc
from scsims import SIMS
import torch
device = "cuda" if torch.cuda.is_available() else None
dataset = sc.datasets.pbmc3k_processed()
sims = SIMS(data=dataset, class_label="louvain")
sims.setup_trainer(devices=1, max_epochs=10, accelerator="gpu" if device else "cpu")
sims.tr... |
3a50a60d58129a03345b64ae93f9f2c199e9c609142236311ae6224b2ecbf17a | Python | 364 | 16 | import numpy as np
from scipy.io import savemat
from os.path import join
inputFilePath = 'D:\Documents\Data\MELD_database'
inputFileName = 'predictions_lh.npz'
data = np.load(join(inputFilePath, inputFileName))
lst = data.files
matData = {}
for item in lst:
matData[item] = data[item]
savemat(join(inputFile... |
bc2a5b10e9fe94612337688f9f3adc3de59f02c2295f9def3c7a78aa89305a2e | Python | 364 | 13 | import numpy as np
import pumpprobe as pp
def integral_c(A, delta=1., k=8):
if A.dtype==np.complex128:
I = pp.integral(A.real.copy(),delta,k)
I += 1.0j*pp.integral(A.imag.copy(),delta,k)
elif A.flags['C_CONTIGUOUS']==False:
I = pp.integral(A.copy(),delta,k)
else:
I = pp.in... |
6fab3cd26aa1593eda18a417f8958f4b36dcc29e779e87fb218e6cd46ece444f | Python | 365 | 13 | #python3 convert_latin-1.py
#Convert stdin encoded as latin-1 to ascii
import io
import sys
import codecs
#sys.stdout = codecs.getwriter( 'utf8' )( sys.stdout )
input_stream = io.TextIOWrapper( sys.stdin.buffer, encoding='CP437' ) #'latin-1' )
#input_stream = sys.stdin
for line in input_stream:
sys.stdout.write( l... |
ae86fe1db3c28d682ceb56ad353ccd9f128ee07465cb35e9586354e258ad4af3 | Python | 365 | 22 | import sys
import h5py
import hdf5plugin
import numpy as np
def printname(x):
print(x)
def main():
with h5py.File(sys.argv[1],'r') as f:
total_cas = 0
for protein in f[sys.argv[2]]:
total_cas += np.count_nonzero(protein['atom_names'] == b' CA ')
sys.exit(str(total_cas))... |
db3bd524d94572ecbccc58ad81496366a42f40c65eaca73902145aed0c046699 | Python | 366 | 10 | import pandas as pd
import pandas._testing as tm
class TestPickle:
def test_pickle_round_trip_closed(self, closed, temp_file):
# https://github.com/pandas-dev/pandas/issues/35658
idx = pd.IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
result = tm.round_trip_pickle(idx, temp_fil... |
380f2e89e9fcf1d949facf2d22a1160b7b58ff5ba2260dcbcb8d62f325d22c09 | Python | 369 | 12 | """Optional integrations for scsims.
These modules are not imported by ``scsims/__init__.py`` and may have
extra dependencies (boto3, etc.). Install them via the appropriate
``pip install scsims[<extra>]`` extra.
"""
try:
from .upload import UploadCallback # noqa: F401
except ModuleNotFoundError:
# boto3 not... |
5945120f95295e57228834e5bb30e03c09730887d306d475b8b2526ee4dc5f00 | Python | 372 | 19 | # -*- coding: utf-8 -*-
from .backend import Backend
from .hdf import HDFBackend, TempHDFBackend
__all__ = ["Backend", "HDFBackend", "TempHDFBackend", "get_test_backends"]
def get_test_backends():
backends = [Backend]
try:
import h5py # NOQA
except ImportError:
pass
else:
b... |
660a0540a60f6b3beb70563a3ba8e99eae759a74885a6d60d515b3226a3718a1 | Python | 372 | 11 | import numpy as np
def l_equiv(Z0, ZL):
return 0.5*np.arccosh(2*(Z0/ZL)**2-1)
def d_equiv(Z0, Ri, gL, l):
return (2/(np.pi*Z0)*np.sqrt(Ri/gL)/np.tanh(l))**(2/3)
def DS_fin_impedance(Gσ, Ginf, τσ, τδ, l, ω):
Yδ = sum( Ginf[i]*np.sqrt(1+ω*τδ*1j)*np.tanh(l[i]*np.sqrt(1+ω*τδ*1j)) for i in range(0,len(Ginf)) ... |
cf43f29fd16c6b8cd08092ef7329c9ba90e5815e1f6f73300426c66749238fe5 | Python | 375 | 17 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("find_ECE", ["find_ECE.pyx"]),
]
setup(
name = 'c_ICE',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
author_email='etseng@pacific... |
de576fc65347b85aca306caf8dea8720d9344a52e979c3679a95e9e3572bb23f | Python | 376 | 14 | import sys
import pandas as pd
X = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True)
if 'fdurGP' in X.columns:
fdur = 'fdurGP'
else:
fdur = 'fdur'
X['time'] = X.groupby(['subject', 'docid'])[fdur].shift(1).fillna(value=0)
X.time = X.groupby(['subject', 'docid']).time.cumsum() / 1000 # Convert ms to s
X... |
20cbf642b40a277bcdc40d1bbe438218f77f71935d4719d36f932f7676576a7d | Python | 377 | 13 | import numpy as np
import pandas as pd
import pandas._testing as tm
class TestSplit:
def test_split_non_utc(self):
# GH#14042
indices = pd.date_range("2016-01-01 00:00:00+0200", freq="s", periods=10)
result = np.split(indices, indices_or_sections=[])[0]
expected = indices._with_fr... |
228bed7e2daea68a248e906a7ee930f6d302f53534683ed2d370b2f1efe582e8 | Python | 378 | 12 | """
just for export
"""
from __future__ import print_function, division, absolute_import
id_to_name = {}
from .mask_artifacts import options_by_diff,\
options_by_height, options_by_bincount
artifact_types = (options_by_diff, options_by_height, options_by_bincount)
for options in artifact_ty... |
a0ee9fab8138c620068bf963670583b08f21be68769925fea8ebdcbe91d8e64a | Python | 378 | 13 | #setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext_modules=[Extension('_dice6', ['dice6.pyx'],libraries=['m'], \
extra_compile_args=["-ffast-math"], include_dirs=[numpy.get_include()])]
setup(
name='fastloop',
ext_mod... |
ac38b83909f1bdcb4497cfd0a6e3f11a43ef2e73bf0a2d674a4099372df52ef5 | Python | 379 | 16 | import pandas as pd
class Finalize:
param_names = ["series", "frame"]
params = [pd.Series, pd.DataFrame]
def setup(self, param):
N = 1000
obj = param(dtype=float)
for i in range(N):
obj.attrs[i] = i
self.obj = obj
def time_finalize_micro(self, param):
... |
2d1a8837b69664b4376b9d5e7d714a73fd08ba7b59e6049e23b50debc3f974a5 | Python | 380 | 10 | import sys, argparse
import pandas as pd
argparser = argparse.ArgumentParser(description='Removes non-fixated tokens from a table of eye-tracking reading time data')
args, unknown = argparser.parse_known_args()
def main():
input = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True)
rm_sac = input[input['Fd... |
71e96335727a7170f7ad4453fb9ea9d41df5ac2b6f1ea302c20422936c7e77d5 | Python | 380 | 16 | # -*- coding: utf-8 -*-
from emcee import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_de_snooker", "test_uniform_de_snooker"]
def test_normal_de_snooker(**kwargs):
kwargs["nsteps"] = 4000
_test_normal(moves.DESnookerMove(), **kwargs)
def test_uniform_de_snooker(**... |
36d019a7525e90663e0e50a460b1fc01122d929baf9ed270e8f9c49cc8ef9f68 | Python | 381 | 9 | # License: see [LICENSE, LICENSES/legged_gym/LICENSE]
import os
from legged_gym import LEGGED_GYM_ROOT_DIR, LEGGED_GYM_ENVS_DIR
from .base.quadruped import Quadruped
from .base.quadruped_config import LeggedRobotCfg, LeggedRobotCfgPPO
from legged_gym.utils.task_registry import task_registry
task_registry.register( "qu... |
661f72e5b13283e4096e14e1f88e8728260b7b162c570a14b6a1c1abf5546866 | Python | 381 | 12 | from distutils.core import setup
setup(
name='NeuralPopulationControl',
version='0.1',
packages=['npc'],
install_requires=['numpy', 'scipy', 'h5py', 'tensorflow-gpu', 'absl-py', 'pillow'],
url='https://github.com/dicarlolab/npc.git',
license='MIT License',
author='Pouya Bashivan',
descr... |
20ceb8746f7c631f31c96e5b9854094072e6a246742b80417bec64823995bbcc | Python | 382 | 16 | from setuptools import setup, Extension
from Cython.Build import cythonize
import numpy
ext_args = dict(
include_dirs=[numpy.get_include()], # not needed anymore
library_dirs=[],
runtime_library_dirs=[],
extra_link_args=[]
)
ext_modules = [
Extension('vegas._vegas', ['src/vegas/_vegas.pyx'], ... |
51296587ef11425023c17e0514a29d570d7ed7906b221c5c16415a2b5dc45320 | Python | 382 | 15 | from .outlier import EM, global_ncc_exclusion, local_ssim_exclusion
from .registration import (
SliceToVolumeRegistration,
VolumeToVolumeRegistration,
stack_registration,
)
from .reconstruction import (
psf_reconstruction,
SRR_CG,
srr_update,
simulate_slices,
slices_scale,
simulated_... |
5d61c066a7920defccf3237b7cf3e7ef123d7ed30c075fabb881023b5eb5265f | Python | 382 | 20 |
'''
TODO: move play_steps here
'''
class Rollout:
def __init__(self, gamma):
self.gamma = gamma
def play_steps(self, env, max_steps_count = 1):
pass
class DiscretePpoRollout(Rollout):
def __init__(self, gamma, lam):
super(Rollout, self).__init__(gamma)
self.lam = lam
... |
9ae6796697960b8e365a21599d3c65ea907561d8adb614cdd2539bfc52aa4ec5 | Python | 382 | 14 | import numpy as np
import pandas as pd
from pandas.tests.copy_view.util import get_array
def test_get_array_numpy():
df = pd.DataFrame({"a": [1, 2, 3]})
assert np.shares_memory(get_array(df, "a"), get_array(df, "a"))
def test_get_array_masked():
df = pd.DataFrame({"a": [1, 2, 3]}, dtype="Int64")
as... |
d4cd63602ac8f5b15eef1a0d74c04323fbb9c574db6123e2c24a38d7eb02469a | Python | 382 | 21 | from .loss import ncc_loss, ssim_loss
from .misc import (
set_seed,
makedirs,
merge_args,
resample,
meshgrid,
gaussian_blur,
MovingAverage,
)
from .psf import get_PSF, resolution2sigma
from .logger import (
log_params,
log_args,
setup_logger,
log_result,
LazyLog,
Trai... |
1995192d3715624c0a229d8a0e04ed6b6490977343a518519fa2fa3756340b54 | Python | 385 | 12 | import pytest
import pandas as pd
class TestSparseAccessor:
@pytest.mark.filterwarnings("ignore:The inplace keyword in Series.drop")
def test_sparse_accessor_updates_on_inplace(self):
ser = pd.Series([1, 1, 2, 3], dtype="Sparse[int]")
return_value = ser.drop([0, 1], inplace=True)
asse... |
1f33209e2cea58f3de031bec53c4e47ba049130c065573b19956d9ff35b00f07 | Python | 385 | 11 | from pathlib import Path
from global_config import config as global_config
config = global_config.copy()
config.update({
'half_precision': True,
'token_sequences_dataset_path': str(Path(global_config['token_sequences_dir'], 'generated_27032020.npz')),
'vocabulary_path': str(Path(global_config['vocabularie... |
d4bfc3f4f1899869bca8e314945f0f92a3f94773c921fcb8e8a9e07f03db1a1b | Python | 385 | 10 | import argparse
from kilosort.gui.launch import launcher
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog = 'Kilosort4',
description = 'spike-sorting + GUI')
parser.add_argument('--filename', default=None, type=str, help='filename of binary file to proc... |
e0d90c43ed63cc9d443ff3f45657b7caa3397c075eb175c4150ff68e1462a48a | Python | 385 | 16 | import torch.nn as nn
class tSequential(nn.Sequential):
def __init__(self, *args, M=None):
super(tSequential, self).__init__(*args)
self.M = M
def forward(self, input):
for module in self:
if hasattr(module, 'M'):
input = module(input, self.M)
e... |
272520c6ca14e308b55e267c8027377e51dea2945f7c9402d61dfe178fdf2c19 | Python | 386 | 15 | from __future__ import print_function # makes this work for python2 and 3
import vegas
import cfcn_f2py
def main():
integ = vegas.Integrator(4 *[[0,1]])
print(integ(cfcn_f2py.fcn, neval=1e4, nitn=10).summary())
print(integ(cfcn_f2py.fcn, neval=1e4, nitn=10).summary())
if __name__ == '__main__':
imp... |
176d263c670729f885a8367c8809e087feb2cac80180eb8256b8cd39ecd47eaf | Python | 387 | 9 | """Automation for issue assignment and the pull request lifecycle.
Decision logic lives in :mod:`core` (pure functions, unit tested), the thin
GitHub API layer in :mod:`client`, and contributor-facing text in
:mod:`messages`. The per-workflow entry points (:mod:`gate`,
:mod:`label_awaiting_review`, :mod:`unassign_inac... |
257ddef4afd6c5dfdb590a2e25863a5e04a46576e92850d329b1b6c51a9437fd | Python | 387 | 16 | import torch
mask2index = lambda mask: torch.nonzero(mask)
def index2mask(idx_arr, n):
mask = torch.zeros(n, dtype=torch.long, device=idx_arr.device)
mask[idx_arr] = 1
return mask.to(torch.bool)
def torch_groupby(arr, groups):
sort_idx = groups.argsort()
arr, groups = arr[sort_idx], groups[sor... |
d2756dd776f669d1f435b17c6f86f1f6eb15defcf150f3cb5e25e8ddf3cc4b3d | Python | 389 | 18 | # handle_random_seed.py
import logging
import numpy as np
logger = logging.getLogger(__name__)
def handle_random_seed(seed=None):
if seed is None:
random_seed = np.random.random() * 2**32
logger.info('Generated random seed: %s', random_seed)
else:
random_seed = seed
logger.i... |
e9ebf7726840299f0087b2dce70eb45b9b58849a1eb983b9c85c24a98e1b78dc | Python | 389 | 13 | """Anomaly-detection task — PyCaret 4.0.
PyCaret 4.0 is OOP-only; the 3.x functional API was removed.
from pycaret.anomaly import AnomalyExperiment
exp = AnomalyExperiment(session_id=42).fit(df)
iforest = exp.create_model("iforest").pipeline
labelled = exp.assign_model(iforest)
"""
from pycaret.tasks... |
34a8d0710ae7768edcf438ccf79c163baa65a6022a41ed8008a82985fe4bc344 | Python | 392 | 28 | from pathlib import Path
import os
REPO_ROOT = Path(__file__).parent.parent.resolve()
STRIDE_EXE = os.environ.get("STRIDE_EXE", "stride")
_3to1 = {
'ALA': 'A',
'CYS': 'C',
'ASP': 'D',
'GLU': 'E',
'PHE': 'F',
'GLY': 'G',
'HIS': 'H',
'ILE': 'I',
'LYS': 'K',
'LEU': 'L',
'MET': 'M',
'ASN': 'N',
'PRO': 'P',
'GLN': 'Q',
'A... |
781761055627b480a355705860dbecfaca3355ba43bb44c78d153377e2fdc2ef | Python | 392 | 15 | from multiligtopic.args import get_args
from multiligtopic.multi_lig_topic import MultiLIGTopic
if __name__ == '__main__':
args = get_args()
print('Starting multiple document interpretation of neural model using Layered Integrated Gradients and BERT Topic')
multi = MultiLIGTopic(args)
multi.fit_topi... |
9deeec993a508aea904b10704c3c6d55d4f6a4a51e813656543c9e589e961c25 | Python | 393 | 20 | import seaborn as sns
orange='#FF922B'
yellow='#FCC419'
lime='#82C91E'
green='#37B24D'
teal='#20C997'
cyan='#3BC9DB'
blue='#228BE6'
indigo='#4263EB'
violet1='#D0BFFF'
violet2='#9775FA'
violet3='#5F3DC4'
grape='#DA77F2'
pink='#F783AC'
red='#F03E3E'
gray='#868E96'
green1= sns.color_palette("tab20c", 20)[11]
green2= sns.... |
c9caefa14024fe43bca7ad5d47cdad1b4e2306b72f7867d3a666de9434b6ed44 | Python | 395 | 20 | #
# Moduel to implement geomtric transformations used in parsing pdb files
#
import numpy as np
def cartesian_to_spherical(r):
# get cartesian coordinates
x = r[0]
y = r[1]
z = r[2]
# get spherical coords from cartesian
r_mag = np.sqrt(np.sum([x_*x_ for x_ in r]))
t = np.arccos(z/r_mag)
... |
0560f1d1c3fc18ee98c06d22e4bb4a28df93fdb5661fdb15b9ff4c280f226bf7 | Python | 396 | 16 | import apnet
import pandas as pd
import numpy as np
from atom_model import AtomModel
mol, mult, vol, val = apnet.load_monomer_dataset('/theoryfs2/common/data/monomer-pickles/hfadz.pkl')
atom_model = AtomModel()
mol_t = mol[:35000]
mult_t = mult[:35000]
mol_v = mol[35000:]
mult_v = mult[35000:]
model = atom_model.tra... |
3ce5ee16f706a1a9ca66c5bec611875139b522029d1c5fa315fcfc493d11c9dd | Python | 396 | 17 | SIZE = 128
OUTPUT = "."
CC359_DATASET_DIR = "/home/ivanitz/Data/cc359/"
NFBS_DATASET_DIR = "/home/ivanitz/Data/nfbs/NFBS_Dataset/"
ADNI_DATASET_DIR = "/home/ivanitz/Data/adni"
CC359_TRAIN = "./cc359_train.tfrecord"
CC359_VAL = "./cc359_val.tfrecord"
NFBS_TRAIN = "./nfbs_train.tfrecord"
NFBS_VAL = "./nfbs_val.tfreco... |
ac04015a94ffab05cbefe309df22bfe1d3a48e561cb9aa5925c542d1c88ad797 | Python | 396 | 14 | import torch
import torch.nn as nn
class SL1Loss(nn.Module):
def __init__(self):
super(SL1Loss, self).__init__()
self.loss = nn.SmoothL1Loss(reduction='mean')
def forward(self, depth_pred, depth_gt, mask=None):
if None == mask:
mask = depth_gt > 0
loss = self.loss(d... |
9d6ce851cafc840d6ade0be9a4be9dae8d442d60c71cf97f185fe8daf3b093ff | Python | 398 | 13 | from dataknead import Knead
import logging
logging.basicConfig(level=logging.DEBUG)
# Convert csv to json
Knead("input/cities.csv").write("output/cities.json")
# Get city names and write to csv
Knead("input/cities.csv").map("city").write("output/city-names.csv")
# Get only cities located in Italy
Knead("input/citie... |
0677cb9f7ff24cd157fd392a0809f396cb5a1fcf1969415da0fde3522c338995 | Python | 399 | 18 | """Initialization for `paccmann.model.model_specifications` submodule."""
from .dnn import dnn_fn
from .rnn import rnn_fn
from .scnn import scnn_fn
from .sa import sa_fn
from .ca import ca_fn
from .mca import mca_fn
# NOTE: model specification factory
MODEL_SPECIFICATION_FACTORY = {
'dnn': dnn_fn,
'rnn': rnn_... |
fb27928521604e1e3b4e73c011c9fb2485a7b69e69384e7701bb7b8fd8f6cb4e | Python | 399 | 13 | import numpy as np
import sys
def max_minNorm(data):
if np.ndim(data) == 3:
max_value = np.max(data,axis=(0,2)).reshape(1,data.shape[1],1)
min_value = np.min(data,axis=(0,2)).reshape(1,data.shape[1],1)
denominator = max_value - min_value
else:
sys.exit("Need dim is 3, but input... |
5471a1dbdf60a49188e93ede8be3f81754d5aa053ebe6e8a34fd9cb37415c047 | Python | 400 | 13 | [style]
based_on_style = pep8
column_limit = 88
coalesce_brackets = true
disable_ending_comma_heuristic = true
indent_dictionary_value = true
indent_closing_brackets = true
split_before_expression_after_opening_paren = true
split_before_bitwise_operator = false
split_before_arithmetic_operator = false
split_before_logi... |
5917fad6d7a1e5165e919678e76435ba994919c8c91affed5f820f85f5c21a05 | Python | 400 | 15 | import os
import sys
from config_sampler import Config
throwaway_script = 'batch_script.slurm'
config = Config()
for job, script in config.generate_sbatch_scripts():
f = open(throwaway_script,'w')
f.write(script)
f.close()
print('Submitting job ' + job)
if os.system('sbatch ' + throwaway_script) !... |
b074b31c0ff9f312c8d506bf995db0a68d8c0f14023ac0c4cd7fc63a643e511d | Python | 401 | 12 | import numpy as np
import chromosight.utils.stats as cus
def test_fdr_correction():
"""
Check if BH correction yields same results obtained from R's p.adjust"""
in_pvals = np.array([0.1, 0.1, 0.05, 0.01])
exp_qvals = np.array([0.1, 0.1, 0.1, 0.04])
obs_qvals = cus.fdr_correction(in_pvals)
asse... |
72b5dfe0a9152fa019203a71f48d4f6042acd9c6d6d38f5595a37107e7796f24 | Python | 403 | 18 | from .transform_convert import axisangle2mat, mat2axisangle
from .transform import (
RigidTransform,
mat_first2last,
mat_last2first,
ax_first2last,
mat_update_resolution,
ax_update_resolution,
mat2euler,
euler2mat,
point2mat,
mat2point,
mat_transform_points,
ax_transform_... |
1280100fd1373759ea5e2228896c8a9ee8809ea18bc611c0145a8b9bcf211e4e | Python | 406 | 10 | from matformer.train_props import train_prop_model
props = [
"e_form",
"gap pbe",
# "mu_b",
"bulk modulus",
"shear modulus",
# "elastic anisotropy",
]
train_prop_model(learning_rate=0.001,name="matformer", dataset="megnet", prop=props[0], pyg_input=True, n_epochs=500, batch_size=64, use_lattice... |
3fd32cfded42dc44fed8eb2f395a01c9adac65af86de7b14f2c4ca56e72a03e5 | Python | 408 | 23 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
if len(sys.argv) <= 1:
sys.exit(0)
def subber(m):
return m.group(0).replace("``", "`")
prog = re.compile(r":(.+):``(.+)``")
for fn in sys.argv[1:]:
print("Fixing links in {0}".format(fn))
with open(fn, "r") as f:
txt = f.r... |
6a55a1a5e51bb039f08efac85602f60c1180becc86a116db4fad4c1f4408e6fe | Python | 408 | 15 | import re
import sys
## reads in this format: <word> <preterm sign> <fork decision> <join decision> <apex sign>/<brink sign>
Q = [ ]
for line in sys.stdin:
m = re.search('^(.*) (.*) (.*) (.*) (.*)',line)
if m is not None:
(w, p, f, j, q) = m.groups()
if f=='1': Q.append('')
if j=='1': Q = Q[:-1]
i... |
0cffa274e040b3e572bfc8598bc3179ce1a821169c66973514814ac3d83a4cd9 | Python | 410 | 16 | """Migration runner that applies all pending data migrations in sequence."""
from . import rename_time_directories
MIGRATIONS = [
rename_time_directories,
# Add other migration modules here as needed
]
def run_migrations() -> None:
"""Runs all pending migrations."""
for migration_module in MIGRATIO... |
1da481d223de5aa4a87dcdf91c55ec3619221222e58e20e7a0678b365f3f4546 | Python | 413 | 18 | from dataknead import Knead, BaseLoader
import yaml
class YamlLoader(BaseLoader):
EXTENSIONS = ["yaml"]
@staticmethod
def read(f, **kwargs):
return yaml.safe_load(f, **kwargs)
@staticmethod
def write(f, data):
yamldata = yaml.dump(data)
f.write(yamldata)
Knead.add_loader(... |
398aff356f0f157f25266ba804e9b9c5f215ceda029fb5edd1872721cda5d8b0 | Python | 413 | 13 | """Clustering task — PyCaret 4.0.
PyCaret 4.0 is OOP-only; the 3.x functional API was removed.
from pycaret.clustering import ClusteringExperiment
exp = ClusteringExperiment(session_id=42).fit(df)
kmeans = exp.create_model("kmeans", num_clusters=4).pipeline
labelled = exp.assign_model(kmeans)
"""
fro... |
685d3e1f992a41f24832d544e494e320ee1e4f2c38e8bc27e070338cedad6912 | Python | 413 | 15 | '''
Created on Feb 16, 2019
@author: abast
This package is contains functions, that modify the cell and / or network after
both have been initalized.
Such a function can for example be used to deactivate specific synapses at a somadistance. '''
import importlib
def get(funname):
module = importlib.... |
aec11b22fb47c6ae56d641bef31b01807bda09b4ebdb655696a3e4d203a1d933 | Python | 414 | 15 | """Algorithms for reconstructions, optimization, density and sensitivity map estimation, etc."""
from mrpro.algorithms import csm, dcf, optimizers, reconstruction, denoiser
from mrpro.algorithms.prewhiten_kspace import prewhiten_kspace
from mrpro.algorithms.varimax import varimax
__all__ = [
'csm',
'dcf',
... |
49e85df45613e7c9ea5c131c3885efa4cec365f97ca5a0cf05072119dad1a15a | Python | 415 | 16 | import sys
import re
'''
Convert linetrees to linetoks by finding all words. Print !ARTICLE delims without modification
'''
with open(sys.argv[1],'r') as iff:
lines = iff.readlines()
for line in lines:
if line=="!ARTICLE\n":
print(line.strip())
else:
words = re.findall(' ([^ \)]+)\)', li... |
58a7ca498178b4b659ef74c0022306aad0bc62df11fd3bb25f0bd3fc9d0374f0 | Python | 416 | 14 | """Runtime introspection — GPU detection, system probes.
Lightweight, side-effect-free helpers the worker + admin routes pull
from to figure out "what can this process do". No dependency on the
DB or the FastAPI app; safe to import from anywhere.
"""
from pycaret_server.runtime.gpu import (
GpuInventory,
dete... |
7f46bc96d0898fa7716f09b16d917a1874cb27b8f948034f7d296838ca7004a4 | Python | 416 | 16 | from psychopy import parallel
class EventController():
def __init__(self, COM='3EFC') -> None:
# hex 2 dec
self.address = int(COM, 16)
# self.address = 12544
self.port = parallel.ParallelPort(self.address)
self.clearEvent()
def sendEvent(self, eventType):
... |
ec460f11cfc6b5ee3005f38df29603cb6d2ebe7650c788c904d9362791355d1a | Python | 416 | 13 | from setuptools import Extension, setup
from Cython.Build import cythonize
import numpy
ext_modules = [
Extension(
'activation_functions',
['activation_functions.pyx'],
extra_compile_args=['-fopenmp', '-ffast-math'],
extra_link_args=['-fopenmp'],
)]
setup(ext_modules = cythoniz... |
d5ab1b86a5c8797cb9cd77afb0b0fa69efb1bc708bf3f1ecd5a4e41e24838a68 | Python | 417 | 7 | from .single_layers import LinearLayer, AntiSymmetricLayer, HamiltonianLayer, ModeKLayer
from .resnet_layers import ResidualLayer, AntiSymmetricResidualLayer, HamiltonianResidualLayer
from .t_single_layers import tLinearLayer, tAntiSymmetricLayer, tHamiltonianLayer
from .t_resnet_layers import tResidualLayer, tAntiSymm... |
f2a2ebbe58498036d7b0a26b4f7035dcc6acf3be53588cab10da5c27271d6109 | Python | 417 | 22 | """
NeuroXAI framework
"""
__version__ = "0.1"
try:
import cv2
except:
raise ImportError(
"NeuroXAI requires Opencv. "
"Install Opencv via `pip install opencv-python`"
) from None
try:
import tensorflow as tf
except ImportError:
raise ImportError(
"NeuroXAI requires TensorF... |
0ea4b4796e4f9afbacb13bf4707adb3903f6693d3c7066d5b382f5587f82014e | Python | 418 | 22 | """
.. module:: tool_seedpaint
:platform: Linux, Windows
:synopsis: Tool for seeded segmentation (not implemented yet)
.. moduleauthor:: Fredrik Nysjo
"""
from tool_common import *
import numpy as np
import scipy as sp
import scipy.sparse
import scipy.sparse.csgraph
import scipy.ndimage
import glm
class Seed... |
5d19d1ec0603c22ea7ea8e422286f1c108b6694bf58f8d66447ddfd767224eb7 | Python | 419 | 16 | import pytest
import numpy as np
from shapeout2.gui.analysis import ana_meta
@pytest.mark.parametrize("input,output", [
(0.0, "0.0 µL/s"),
(np.float64(4.9e-323), "0.0 µL/s"),
(12300.212, "12300.21 µL/s"),
(0.0002546, "0.000255 µL/s"),
])
def test_format_config_key_value_numbers(input, output):
a... |
f31c0f445633a0ccc885c7c6147977310b5411dd277ef01f34da0217f8303bab | Python | 419 | 21 | import sys
skip=True
out = []
last_sentid = 0
for line in sys.stdin:
if line.strip() != '' and not skip:
row = line.strip().split()
if int(row[1]) > last_sentid:
print(' '.join(out))
out = [row[0]]
last_sentid = int(row[1])
else:
out.append(... |
41db8c28482eb11cd6cfbe3a0727c8c0ee59c723c42c88f9acc7e2509774119f | Python | 420 | 16 | import os
import sys
from config import Config
throwaway_script = 'batch_script.slurm'
config = Config()
for job, script in config.generate_sbatch_scripts():
print('writing script')
f = open(throwaway_script,'w')
f.write(script)
f.close()
print('Submitting job ' + job)
if os.system('sbatch ' +... |
80627df0293698077f22a9e1bc07c4c0cd77f6345d82e7c9f70220844d2c381e | Python | 420 | 17 | # -*- coding: utf-8 -*-
try:
from schwimmbad import MPIPool
except ImportError:
class MPIPool(object):
def __init__(self, *args, **kwargs):
raise ImportError(
"The MPIPool from emcee has been forked to "
"https://github.com/adrn/schwimmbad, "
... |
1542773e07620689bf6295b6b2b940fe0bb8855add2e8123b86eb3093226ec79 | Python | 421 | 13 | """Regression task — PyCaret 4.0.
PyCaret 4.0 is OOP-only; the 3.x module-level functional API was removed.
from pycaret.regression import RegressionExperiment
exp = RegressionExperiment(target="medv", session_id=42).fit(df)
best = exp.compare_models().best
preds = exp.predict_model(best).predictions
... |
84891bfc5f87ebf6ceaa074eb1d2fa89ada2a8780930c3a585628aeb84db012c | Python | 421 | 16 | #!/usr/bin/python3
def draw_backbone(scaf, start, end, scale, d, leftmost, topmost, col='black', label=True):
import svgwrite
x1 = leftmost
x2 = x1+(end-start+1)/scale
y1 = topmost
y2 = topmost
d.add(d.line(start = (x1, y1), end = (x2, y2), stroke = col, stroke_width = 1))
if label: d.add(d.text(scaf, insert =... |
8bef7ff266dcab0888c864afb530b27d20bc4afe6e6faa517ce9393ca07de019 | Python | 421 | 15 | from sklearn.utils import resample
from darts.api.dataset import Subset
def dummy_indices(dataset):
""" Get indexes for the dataset """
return [x for x in range(len(dataset))]
def sample(dataset, num_samples, replace=True):
""" Sample the dataset """
data_idx = dummy_indices(dataset)
sample_idx ... |
c9f0d75a9f8bb3cd683310ba5ecc47dc0a9c8af9119d047c821ccb3f5d541845 | Python | 423 | 12 | from .auth_keys import AuthKeys
from .subject import Subject
from .condition import Condition
from .image import Image
from .scanner import Scanner
from .source_dataset import SourceDataset
from .source_dataset_condition import SourceDatasetCondition
from .visit import Visit
from .file_type import FileType
from .prepro... |
de6bcb9c507d8c49b56d2f2b9d8710dcb0c393d58714a6d9ef06cd6270281c65 | Python | 423 | 6 | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and relat... |
f5bb744a1eac933043a3755d3f9289261f85ed4348049a1d5155dc87eafcffd0 | Python | 424 | 8 | """
Global file for table generation
"""
LABEL_DIR = r"C:\Users\jjnunez\PycharmProjects\scar_nlp_data\interm_data\labels"
METHOD_TABLES_DIR = r"C:\Users\jjnunez\PycharmProjects\scar_nlp_psych\tables\method_tables"
RESULT_TABLES_DIR = r"C:\Users\jjnunez\PycharmProjects\scar_nlp_psych\tables\result_tables"
PT_DATA_FILE ... |
9ba667ee6b6575816e045dfeb7bcb49fb453cd5ef98ed70fb1a154b0083ed63e | Python | 425 | 17 | """Global Triton kernel configuration for rl_games.
Triton kernels are enabled by default when triton is installed.
To disable, set the environment variable:
export RLG_NO_TRITON=1
"""
import os
try:
import triton
TRITON_AVAILABLE = True
except ImportError:
TRITON_AVAILABLE = False
USE_TRITON = TRI... |
a759e882ecf3ed22e4a1195e221e5c82ef3fb8ff35cbe3ec299cc996fb4fac37 | Python | 425 | 9 | import tempfile
from esmologs import single_seq_to_hmm
import helpers
def test_foldseek2fasta_1(shared_datadir):
with tempfile.TemporaryDirectory() as output_dir:
# output_dir = "tmp"
single_seq_to_hmm.main(["-i", str(shared_datadir / "SOD_examples.fasta"), "-o", output_dir + "/out.hhm", "--model",... |
c583bbda085158edb8dd92d0c9a2ed92f768c64149b4610d61531860cb26a99f | Python | 427 | 19 | # -*- coding: utf-8 -*-
from emcee import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_de", "test_normal_de_no_gamma", "test_uniform_de"]
def test_normal_de(**kwargs):
_test_normal(moves.DEMove(), **kwargs)
def test_normal_de_no_gamma(**kwargs):
_test_normal(moves.... |
67a33641e7b0497d4373b1839bb873b11153ba490d51424cafaddce98f990046 | Python | 428 | 16 | import pandas
import numpy
trainingSamples = numpy.array([50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000])
allConditions = numpy.zeros((len(trainingSamples), 2), dtype=int)
for i in range(len(trainingSamples)):
allConditions[i, 0] = i
allConditions[i, 1] = trainingSamples[i]
pd = pandas.DataFrame(allCon... |
dc6d0348ce3769719e6f6d9b40f698735caa258f68d3a5dea5e7e0e5f974b45c | Python | 428 | 21 | import activationFunctions
import numpy
import matplotlib.pyplot as plt
leak = 0.01
x = numpy.linspace(-2, 3, 1001)
y = activationFunctions.MMLactivation(x.copy(), leak)
# x2 = numpy.linspace(0, 1, 10)
# y2 = activationFunctions.MMLactivation(x2.copy(), leak)
plt.rcParams["figure.figsize"] = (3,3)
plt.plot(x, y)
#... |
054343b5396899647b05e0a8028d8915f8e5cf43793f32d97923b13e608525e0 | Python | 429 | 12 | from PyQt6 import QtCore, QtWidgets
class MDISubWindowWOButtons(QtWidgets.QMdiSubWindow):
def __init__(self, *args, **kwargs):
super(MDISubWindowWOButtons, self).__init__(*args, **kwargs)
self.setSystemMenu(None)
self.setWindowFlags(QtCore.Qt.WindowType.CustomizeWindowHint
... |
c52ab03896d8b5db671c4b32419a86bcd181278356da97a133836f6e5d40e555 | Python | 430 | 10 | """Removed — use the litpose CLI instead."""
raise SystemExit(
"scripts/converters/dlc2lp.py has been removed.\n"
"Please use the command line interface instead:\n\n"
" To convert a DLC project to a Lightning Pose project:\n"
" litpose convert <dlc_dir> --lp_dir <lp_dir>\n\n"
"For more informat... |
1b523fcc058ac1804363b45d4f6577e0084e455f9e38754f3e0dc431191dcdf9 | Python | 431 | 17 | import json
trashlist = []
filename0 = r"E:\experiment\mal\super\super3.json"
filename1 = r"E:\experiment\mal\super\super3trash.json"
with open(filename0, 'r') as f:
data = json.load(f)
print(len(data))
for i in data:
if bool( list(i.values())[0] ) == False:
trashlist.append(list(i.keys())[0]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.