sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
e6df5a228513e241e623a06fa9fa22cf6226430c52d48f60ad4c8778eaec65be | Python | 977 | 35 | import pandas as pd
import csv
def extract_matching_values(file1_path, file2_path, output_file_path):
df1 = pd.read_csv(file1_path, sep='\t')
df2 = pd.read_csv(file2_path)
matching_values = df1[df1['Index'].isin(df2['Node_Index'])]['Gene']
matching_values.to_csv(output_file_path, index=False, header... |
7dd6c2cbcbdd2ecfa39391a79da3cc489affeeff64beb8210eba80cffefccc77 | Python | 979 | 31 |
import sys
sys.path.append('.')
from plotting.utils import load_results, mesh_name, sim_name, set_plotting_defaults, efcolor, pvscolor, ecscolor
import matplotlib.pyplot as plt
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_results(mesh_name, sim_name)
times = resu... |
8268026bffb885e84d083211b3a7e012d580d90d1de12649e43f4aac22ea9fc6 | Python | 979 | 30 | import os
import re
import setuptools
# for simplicity we actually store the version in the __version__ attribute in the source
here = os.path.realpath(os.path.dirname(__file__))
with open(os.path.join(here, 'torchdiffeq', '__init__.py')) as f:
meta_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(... |
bbf3fd70d5a4fad7d7fa27e1750f2c46eab50b90fc72c86d9ab0430086defb42 | Python | 979 | 43 | """Tests for fooof.core.strings."""
from fooof.core.strings import *
from fooof.core.strings import _format, _no_model_str
###################################################################################################
###############################################################################################... |
261355d0e56a4de33bd7b25ad412e111093cc9f4d35247cae3c298099470aecd | Python | 980 | 56 | """
Created on Jun 25, 2024
@author: mning
"""
from typing import List
# color palette generated from one color here:
# https://mycolor.space/
# OLD
# clr_list_drk = ['#65ABEC',
# '#FFE9D0',
# '#A4CB9B',
# '#D79186',
# '#C1A4D8',
# '#C4887C',
# '... |
801c61ac1617d493e262ae338b80c993556b7fa80a042b683d9bcf5e736188a5 | Python | 981 | 42 | import pandas as pd
from pathlib import Path
base_dir = Path(
"/storage/Arushi/090526_EvoAge/kg_formation/orthology_mapping/Biomart_ensemble/Human_Ortholog_Mapping_3"
)
species_list = [
"Yeast",
"Celegans",
"Drosophila",
"Zebrafish",
"Mouse",
]
for species in species_list:
species_dir = ... |
9202c7156c98115b14feecb0d7d90fc35c84671661d93459ff8815971fdb075d | Python | 981 | 37 | from glob import glob
import numpy as np
import sys
sys.path.append("../")
def getSubjects(dataset, seed, fold, isTrain):
datasetNameToFolderDict = {
"hcpRest" : "./Analysis/Data/hcpRest",
"hcpTask" : "./Analysis/Data/hcpTask",
"abide1" : "./Analysis/Data/abide1"
}
targetFold... |
c537ee57452f75eaca789736c58bed02d7cd76b32d41b1fb16ace9b5cbbfc591 | Python | 981 | 54 | from __future__ import print_function
import sys
def usage():
print("""return FFT grid size for PME
usage:
# checkfft.py A B C
""")
def is_factor(n):
if (n % 2 != 0): return False # favors even number
while n:
flag = False
for x in (2,3,5):
if n % x == 0:
n = n... |
d9f1e317e49f80fbe3c8d67588787fc23a96751fd8a393831f0642d232c13e17 | Python | 981 | 54 | from .distro import (
NORMALIZED_DISTRO_ID,
NORMALIZED_LSB_ID,
NORMALIZED_OS_ID,
LinuxDistribution,
__version__,
build_number,
codename,
distro_release_attr,
distro_release_info,
id,
info,
like,
linux_distribution,
lsb_release_attr,
lsb_release_info,
major... |
573eeaed4bc28a849af7861a60e82221401ad93a21cb02343a8f9fba026b9a74 | Python | 982 | 44 | from neurodesign import geneticalgorithm, generate, msequence
import sys
design_i = sys.argv[1]
EXP = geneticalgorithm.experiment(
TR = 0.68,
P = [.6,.2,.2],
C = [[0.5, 0, -0.5],[0, 0.5, -0.5]],
rho = 0.3,
n_stimuli = 3,
n_trials = 250,
duration = 619,
resolution = 0.136,
... |
4a6338f2b7003758befd25ad42645f723d371f88c67b039c1ea98e13bea8737e | Python | 983 | 35 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..counts._count_words import count_words
from ..counts._count_difficult_words import count_difficult_words
from ._words_per_sentence import words_per_sentence
@typed_cache
def dale_chall_readability_score_v2(text: str, lang: str) ->... |
daba55218537a62939fc02ceb72055a2446319e427a14604cfa8772e7cded307 | Python | 983 | 29 | from __future__ import annotations
import pytest
from textstat.backend import metrics
from .. import resources
@pytest.mark.parametrize(
"text, lang, variant, expected",
[
(resources.EMPTY_STR, "en_US", 1, 0.0),
(resources.EMPTY_STR, "en_US", 2, 0.0),
(resources.EMPTY_STR, "en_US", 2... |
1847b376bd208d8d13a67020aa3a3d2fb4361ad231d853a856a56d3b9b3ec945 | Python | 984 | 28 |
import sys
sys.path.append('.')
sys.path.append('..')
from plotting.utils import load_results, m3tofl, dpi, set_plotting_defaults, efcolor, pvscolor, ecscolor
import matplotlib.pyplot as plt
set_plotting_defaults()
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_r... |
3715502855103510eba5a53a6176effd4af96f45124ed6c02e57d6430e3b5c1b | Python | 984 | 44 | from neurodesign import geneticalgorithm, generate, msequence
import sys
design_i = sys.argv[1]
EXP = geneticalgorithm.experiment(
TR = 0.68,
P = [.6,.2,.2],
C = [[0.5, 0, -0.5],[0, 0.5, -0.5]],
rho = 0.3,
n_stimuli = 3,
n_trials = 250,
duration = 619,
resolution = 0.136,
... |
f49aaa6843028f6623f0f09bc0c6ab29f0b40d0728ea8cff184f5f4dd0453be3 | Python | 985 | 35 | ## ...........................................................................
##
## PIMMS (Polymer Interactions in Multicomponent Mixtures)
## Alex Holehouse, Pappu Lab, Holehouse Lab
## Copyright 2015 - 2026
## ...........................................................................
import time
import random
f... |
f93733e5dea7d5cd9e505fc360d5880941daf13e5b4ea27e8f18128a723ee814 | Python | 985 | 39 | from typing import Literal, List, TypedDict, get_args, NotRequired
from pathlib import Path
DWIStage = Literal["denoising", "degibbs","topup", "eddy", "b1correct", "rician", "designer"]
DiffusionModelType = Literal["smi", "dti", "dki", "wdki"]
def is_valid_dwi_stage(dwi_stage: str) -> bool:
return dwi_stage in ... |
6ef858313fbe4b562ad63c84addd7eaa0a4a89b089cb22033ce3ec1e38a7b2f4 | Python | 986 | 38 | import random
import os
import numpy as np
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
# from torch.autograd import Variable
class StateDataset:
# initial
def __init__(self, mode, num):
self.state = np.loadtxt(mode, dtype=np.int)
self.num = 1... |
68ff624e5d27d47a595883ffd368bffd7c459d230917c8823391229f63112bcd | Python | 987 | 41 | import numpy as np
import pytest
from pandas import (
Series,
array,
)
@pytest.fixture(params=[None, False])
def sort(request):
"""
Valid values for the 'sort' parameter used in the Index
setops methods (intersection, union, etc.)
Caution:
Don't confuse this one with the "sort" fixtu... |
72637dc35697fe49b4f9749599209f37178c48ed567d42386243cf27724e42dd | Python | 987 | 41 | r"""
It's used to check basic rnn features with cpu-only.
For example, it would throw exception if some components are missing
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class SimpleCNN(nn.Module):
def __init__(self):
super().__init__()
self... |
54db1b8098f2902e56d42834079eea51b58bd8cd53c371c0933ef26348df03e8 | Python | 988 | 40 | import pennylane as qml
import tensorflow as tf
nwires, nlayers = 6, 3
coeffs = [-1.0] * nwires + [1.0] * (nwires - 1)
obs = [qml.PauliX(i) for i in range(nwires)] + [
qml.PauliZ(i) @ qml.PauliZ((i + 1) % nwires) for i in range(nwires - 1)
]
Htfim = qml.Hamiltonian(coeffs, obs, True)
dev = qml.device("default.qu... |
f5f7f4cfe72a2174378cfdcbd3d3c22b0340c3c2cbfda0c269ecbd9c85c6f454 | Python | 988 | 36 | """Tests the utils module.
The copyrights of this software are owned by Duke University. Please
refer to the LICENSE and README.md files for licensing instructions. The
source code can be found on the following GitHub repository:
https://github.com/wmglab-duke/ascent
"""
import os
import pickle
import pytest
from sr... |
fb91f75d56fc171e8b674e0a820469b1dc283651ce844d25ab7dbdf5fc8d49e8 | Python | 989 | 37 | """Tests the utils module.
The copyrights of this software are owned by Duke University. Please
refer to the LICENSE and README.md files for licensing instructions. The
source code can be found on the following GitHub repository:
https://github.com/wmglab-duke/ascent
"""
import os
import pickle
import pytest
from s... |
923146740cbe8d741b7584928dc6fca8b2d63cfe80be44086d068e05e62a2626 | Python | 990 | 37 | # Code taken from
# https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url
import requests
def download_file_from_google_drive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params={"... |
067bff68e542a9803f091cc2bf91356dd6ba54d1954754d7a0cb64562c8f11b3 | Python | 991 | 30 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
""" A qualifier for ActiveSiteFinder annotations """
from typing import List
from typing import Set # comment hint # pylint: disable=unused-import
class ActiveSiteFin... |
4dd346efbc2d084ce6dd1feb118f7cd04b3df78e5444c3638fd2bc475eb76f38 | Python | 991 | 45 | import json
import os
import re
from typing import Union
PathLike = Union[str, os.PathLike]
def to_case_insensitive(s: str) -> str:
return re.sub(r"([a-z]+)", r"-\1-", s)
def to_case_sensitive(s: str) -> str:
out = []
for i, part in enumerate(s.split("-")):
if i % 2 == 0:
out.appen... |
53054da56dc58773ca84d885cd98952b4ed6f3bd429853367c6b42e824d6e73d | Python | 991 | 45 | from datetime import datetime
import numpy as np
from pandas import (
DatetimeIndex,
Series,
)
import pandas._testing as tm
def test_series_set_value():
# GH#1561
dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)]
index = DatetimeIndex(dates)
s = Series(dtype=object)
s._set_value(dat... |
66da9a928210da64025c89e1273cd0a75ca7e3b4c8a411140878dfd3ab1aacd3 | Python | 991 | 30 | from typing import Tuple
import torch
class SquareBoundingBox(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, img: Tuple[torch.Tensor, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
img, bounding_box = img
width = bounding_box[2] - bounding_box[0]
... |
f6d1af5ff3863c873d58f5341995dac07d345ae99a58809048b1283fdfa5f9f0 | Python | 991 | 32 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Learnable shifted softplus activation
"""
class ShiftedSoftplus(nn.Module):
def __init__(self, num_features, initial_alpha=1.0, initial_beta=1.0):
super(ShiftedSoftplus, self).__init__()
self._log2 = math.log(2)
... |
64054252823323dbd2fc00f842ba51cc86d40ec0646f913ba5a0f4fa4b6a8757 | Python | 992 | 34 | import os
import yass
from yass import preprocess, cluster, deconvolve, detect
def test_deconvolution(patch_triage_network, path_to_config,
make_tmp_folder):
yass.set_config(path_to_config, make_tmp_folder)
(standardized_path,
standardized_params) = preprocess.run(
os.path... |
657bd1a4f4aeb8555ead4f80ca6c9da8a2a0c459bdebf0c72f54733834e52bf2 | Python | 992 | 30 | import argparse
from BCBio import GFF
#This script simply takes a GFF file and converts it
#into a bed file with 4th column as locus tag
def main(arguments):
coordinates = []
with open(arguments.input_gff_file) as gff_handle:
for seq in GFF.parse(gff_handle):
for features i... |
1152553c27d0d804e41648cd6bc475fd55285bff50f2ae418620f176b531bdb7 | Python | 993 | 44 | from neurodesign import geneticalgorithm, generate, msequence
import sys
design_i = sys.argv[1]
EXP = geneticalgorithm.experiment(
TR = 0.68,
P = [.25,.25,.25,.25],
C = [[0.5,0.5,-0.5,-0.5],[-0.5,0.5,-0.5,0.5]],
rho = 0.3,
n_stimuli = 4,
n_trials = 128,
duration = 368,
resoluti... |
3e20ca5bdba539754b05f318e17230e3d5d7773872778f959a8a832d2084f9e6 | Python | 993 | 36 | import numpy as np
import torch.nn as nn
#exploit or explore
num_enpop = 6
num_depop = 10
class PopEncoder(nn.Module):
"""
One kind of population coding
"""
def __init__(self, step, encode_type):
super(PopEncoder, self).__init__()
self.step = step
self.fun = getattr(self, enco... |
349bbcc6bed74e6d71bc8e4138c148a7533ed57086a7148ae03cec767509e6f4 | Python | 994 | 37 | """
Basic features of ``tc.Circuit`` class support qudits natively
"""
import numpy as np
import tensorcircuit as tc
K = tc.set_backend("tensorflow")
n = 3
# d=3 qudits
ns = [tc.gates.Gate(np.array([1.0, 0.0, 0.0])) for _ in range(n)]
mps = tc.quantum.QuVector([nd[0] for nd in ns])
c = tc.Circuit(n, mps_inputs=mps... |
b849282e74958b8911f3e73914c86911b6bb96e66e9b73de448af121d78678ce | Python | 996 | 40 | from datetime import datetime
import numpy as np
import pytest
from pandas.core.dtypes.cast import maybe_box_native
from pandas import (
Interval,
Period,
Timedelta,
Timestamp,
)
@pytest.mark.parametrize(
"obj,expected_dtype",
[
(b"\x00\x10", bytes),
(int(4), int),
(... |
e143847deb1ce15aa7e9b90b859598b2cbcf89cff4393e470c797b7d1c55a92a | Python | 996 | 36 | #!/usr/bin/env python2.5
import sys
import os
import showmovie
cwd = os.path.abspath(os.path.split(__file__)[0])
types = dict(val=("val%03d_3min", "valseq3minby10_%02d.index"), trn=("trn%03d", "trnseq.index"))
seq = [("trn", 1), ("val", 1), ("trn", 2), ("val", 2), ("trn", 3), ("val", 3), ("trn", 4), ("val",5)]
### ad... |
3964e7005ca2b8874bfe74e80e27ac8551c5a48748c38faf6de8b981e6f0e0cf | Python | 997 | 47 | from music21 import *
#s = converter.parse('../xmlfiles/four_part_hamony/ch4-03_A-major.xml')
s = corpus.parse('bach/bwv65.2.xml')
s.analyze('key')
print(len(s.parts))
s.show()
for i,part in enumerate(s.parts):
print(i)
print('-----------')
for ns in part.flat.notes:
print(ns.pitch)
print(... |
9ede7507f9142031381c707609e9c374531b7f5c60bd7975519b13ed412679e0 | Python | 997 | 37 | """Tests the utils module.
The copyrights of this software are owned by Duke University. Please
refer to the LICENSE and README.md files for licensing instructions. The
source code can be found on the following GitHub repository:
https://github.com/wmglab-duke/ascent
"""
import os
import pickle
import pytest
from sr... |
0ba825c867714acfa1303412b7d8e47ed99195318f30219d21095f0a147d8869 | Python | 998 | 28 | from pandas import (
DataFrame,
Index,
date_range,
)
import pandas._testing as tm
class TestToFrame:
def test_to_frame_datetime_tz(self):
# GH#25809
idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC")
result = idx.to_frame()
expected = DataFrame(i... |
90b0037dc707640f8bd532639714f7c2c3c0472e05d33c77aca0133e00a59c7b | Python | 998 | 30 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
"""SVG output format module
"""
import logging
import os
from typing import Dict, List
from antismash.common.module_results import ModuleResults
from antismash.config im... |
5470d7695095e9784067d71cc61d032e57d2f6c5c0eb61498fa10aee6223774f | Python | 1,000 | 37 | from setuptools import setup, find_packages
REQUIRED = [
'numpy==1.23.5',
'scikit-learn==1.3.0',
'pandas==1.5.0',
'scipy==1.11.3',
'seaborn==0.12.2',
'matplotlib==3.7.2',
'tqdm==4.66.1',
'scanpy==1.9.4',
'anndata==0.9.2',
'scvelo==0.2.5',
'statsmodels==0.14.0',
'torch==2... |
056991021a086502cf3d0e5a7e083743a57ca4111a572c0b7d7037042ec9852b | Python | 1,001 | 35 | from nilearn.plotting import plot_glass_brain
from nilearn import datasets
import numpy as np
import matplotlib.pyplot as plt
cache = "/storage/store2/work/haggarwa/"
atlas = datasets.fetch_atlas_schaefer_2018(
data_dir=cache, n_rois=100, resolution_mm=2
)
display = plot_glass_brain(None, display_mode="r")
colors... |
aa6eb636efc4eb54ceac65f3c4c4989b90a2aa6eea2a10856930cfd102668c9a | Python | 1,002 | 44 | import pytest
jinja2 = pytest.importorskip("jinja2")
from pandas import (
DataFrame,
MultiIndex,
)
from pandas.io.formats.style import Styler
@pytest.fixture
def df():
return DataFrame(
data=[[0, -0.609], [1, -1.228]],
columns=["A", "B"],
index=["x", "y"],
)
@pytest.fixtur... |
54c0cf4d7ca59382c7032b825f75a489c53afdd4721483272b86f6a612c74116 | Python | 1,004 | 30 | """Plots the time and location where an action potential occurred.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
This scri... |
70b390a11183042dea9da49490c71bf32764ffb0b3a897b11bede9b699b2fb95 | Python | 1,004 | 32 | """Contains errors raised for input argument parsing"""
# from python
from typing import Any
class InvalidArgumentError(Exception):
"""Raised when a validation error occurs in parsing a commandlind input
argument"""
def __init__(self, argument_name: str, argument_value: Any):
super().__init__(
... |
2b9792911f064b5af93a45d74c739c57468cffac6993d7963442005be38e2768 | Python | 1,005 | 43 | """
pygments.modeline
~~~~~~~~~~~~~~~~~
A simple modeline parser (based on pymodeline).
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
__all__ = ['get_filetype_from_buffer']
modeline_re = re.compile(r'''
(?: vi | vim... |
3fcf7e24913aeb4434a0c63b44c30aaeef23f29b2d2606a2c8f6fbade47c6e6c | Python | 1,005 | 28 | from atomate.openmx.firetasks.write_inputs import WriteOpenmxFromIOSet
from pymatgen.io.vasp.inputs import Structure
def write_openmx_inputs(structure, openmx_input_set, openmx_dft_data_path, override_default_openmx_params, potcar_spec, magmoms):
write_openmx_inputs = WriteOpenmxFromIOSet(
structure=str... |
c8972e2aaa23f77244d6fc8fe34f699f0803532dad1558251eed9fc251a09a03 | Python | 1,005 | 31 | """Plots the time and location where an action potential occurred.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
This scri... |
5b370a0730ac65aa6e50f30850bec854c8979b52fbcb3038407bf7085e40bb12 | Python | 1,006 | 29 | """ support pyarrow compatibility across versions """
from __future__ import annotations
from pandas.util.version import Version
try:
import pyarrow as pa
_palv = Version(Version(pa.__version__).base_version)
pa_version_under10p1 = _palv < Version("10.0.1")
pa_version_under11p0 = _palv < Version("11... |
561881c347396cfbb357c444ea8455c455437c4443657ad81ba5bdfe7a978a7d | Python | 1,007 | 28 | import sys
sys.path.append("../")
sys.path.append("../../../../")
from api.music_engine_api import EngineAPI
import os
if __name__=="__main__":
musicEngine = EngineAPI()
musicEngine.cortexInit()
input_path = "../testData/"
#--------------------learning process---------------#
for composerName i... |
6ac88f7f3fd35f60e9d26b283631b8de964a45880d62eb12220da279cccaf1ab | Python | 1,007 | 39 | import argparse
from pathlib import Path
import sys
from .version import __version__
from .lib._utils_impl import get_include
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--version",
action="version",
version=__version__,
help="Print the version... |
14afa4d0d397c178bbf4d2731f2608a5dcf926516a7a7f58e9afa7d5f8d3a72d | Python | 1,010 | 44 | from neurodesign import geneticalgorithm, generate, msequence
import sys
design_i = sys.argv[1]
EXP = geneticalgorithm.experiment(
TR = 0.68,
P = [55/100.0,15/100.0,15/100.0,15/100.0],
C = [[0, 0.5, 0, -0.5],[0, 0 , 0.5, -0.5]],
rho = 0.3,
n_stimuli = 4,
n_trials = 160,
duration = ... |
30ff752acb7df1717946ed594465aad3dc1d3c0504ef6759a21d246327ec9ff2 | Python | 1,010 | 37 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..utils._get_lang_root import get_lang_root
from ..utils._get_lang_cfg import get_lang_cfg
from ._syllables_per_word import syllables_per_word
from ._words_per_sentence import words_per_sentence
@typed_cache
def flesch_reading_ease(... |
0143c6d6bab086043be48981e82b52ab27f78ce86f7ae155fb68d313b5ad8304 | Python | 1,011 | 29 | from typing import List, Tuple
import torch
from pypylon import pylon
class Devices:
@classmethod
def get_available_cameras(cls) -> List[str]:
devices = list(pylon.TlFactory.GetInstance().EnumerateDevices())
return [device.GetSerialNumber() for device in devices]
@classmethod
def get... |
aac38ea49e46931aba79d8b9a202aa49bb33712f4546768c620bb9f7a57587ad | Python | 1,011 | 43 | """
Docker Utility helpers for CLI tasks.
"""
from __future__ import annotations
import logging
import docker
from docker.errors import APIError, NotFound
logger = logging.getLogger(__name__)
# lazy singleton so we don't reconnect every call
_docker_client: docker.DockerClient | None = None
def _get_client() ->... |
f71489a0f2f7e36508ed053f0342c1fe370253b8d1837c80a63f48f06083859c | Python | 1,011 | 31 | import numpy as np
import torch
def rotate_vol_2d(vol, angle):
"""Rotates each 2D slice in a volume by an angle
Inputs:
vol: torch Tensor of shape (hr_axis, hr_axis, lr_axis)
angle: angle to rotate
Outputs:
Rotated volume of shape (hr_axis, hr_axis, lr_axis) where rotation occured... |
c5a14619e7785d88a96535f69bba040b11fb2456daa17603fa4a9f526ab056ab | Python | 1,012 | 28 |
import sys
sys.path.append('.')
sys.path.append('..')
from plotting.utils import load_results, m3tofl, dpi, set_plotting_defaults, efcolor, pvscolor, ecscolor
import matplotlib.pyplot as plt
set_plotting_defaults()
if __name__ == '__main__':
sim_name = sys.argv[1]
mesh_name = sys.argv[2]
results = load_r... |
4a7c442c1f5b704f07ebcb5850337750a30c3eefac11f6f04e52d49fc5a2ad5f | Python | 1,015 | 30 | import numpy as np
class TestAutoCorr:
def test_autocorr(self, datetime_series):
# Just run the function
corr1 = datetime_series.autocorr()
# Now run it with the lag parameter
corr2 = datetime_series.autocorr(lag=1)
# corr() with lag needs Series of at least length 2
... |
023b2e5e452a7794d4a4fc9de0c399e60f59500e65ce95b9a151fdebe6817e34 | Python | 1,016 | 29 | ## ...........................................................................
##
## PIMMS (Polymer Interactions in Multicomponent Mixtures)
## Alex Holehouse, Pappu Lab, Holehouse Lab
## Copyright 2015 - 2026
## ...........................................................................
import sys
from . import par... |
07a1ce347a27fe219e7cab6f4c1fef46f63b52084a6c798b52a8013c7dfa979c | Python | 1,016 | 36 | from sklearn.metrics import mean_squared_error
from scipy.stats.stats import pearsonr
from copy import copy
def ForwardPropFeatureImp(model, X_true, Y_true, mp):
'''
Leave one feature out importance
'''
try:
df_grid = mp.df_grid
except:
H_grid = mp.plot_grid()
df_grid = ... |
90dd862795c0de005cd9df8ebe923b37bce19941839c5a7a54f52165d098f1c9 | Python | 1,016 | 43 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ._sentences_per_word import sentences_per_word
from ._syllables_per_word import syllables_per_word
@typed_cache
def crawford(text: str, lang: str) -> float:
r"""Calculate the Crawford index for the text.
https://legible.es... |
9ebb6424c1fc528438d23973d0230c9df58a2e4d79b70f20cdb3c35d9b27e8e5 | Python | 1,016 | 37 | """Contains modules for CLI parameters, both user input and constants"""
from .cli_validations import (
validate_not_empty_dir,
validate_input_mode,
validate_binning_cluster_workflow,
validate_binning_query_workflow,
validate_alignment_mode,
validate_extend_strategy,
validate_includelist_al... |
d1a657c53b6e826dafb6ab734a1d93859b7cc46687109517e4dff3ff547c2140 | Python | 1,016 | 33 | from rna3db.parser import Chain, Residue
import unittest
class TestRNAWrappers(unittest.TestCase):
def test_basic_residue(self):
res = Residue("G", "G", 1)
self.assertEqual(res.index, 1)
self.assertEqual(res.three_letter_code, "G")
def test_residue_atoms(self):
res = Residue("... |
2651417c48b1b998b0f7a95165cf3cc1747dfb9b8eb7be2004252a977db51fac | Python | 1,017 | 31 | # NB: This is for the Timestamp.timestamp *method* specifically, not
# the Timestamp class in general.
from pytz import utc
from pandas._libs.tslibs import Timestamp
import pandas.util._test_decorators as td
import pandas._testing as tm
class TestTimestampMethod:
@td.skip_if_windows
def test_timestamp(self... |
d726cd75acee1ddd6bdd9381a4e8a21f2a8a29ed09c7bda71df9119e4922c840 | Python | 1,020 | 32 | from __future__ import annotations
import pytest
from textstat.backend import counts
from .. import resources
@pytest.mark.parametrize(
"text,max_size,expected",
[
("", 1, 0),
("a", 1, 1),
("a ", 1, 1),
("a b", 1, 2),
("They're here, and they're there.", 1, 0),
... |
2ed0833b84de3212d60224c6889113dd83fc44ee93dce42a99da49f091f7f758 | Python | 1,021 | 40 | """ common utilities """
from __future__ import annotations
from typing import (
Any,
Literal,
)
def _mklbl(prefix: str, n: int):
return [f"{prefix}{i}" for i in range(n)]
def check_indexing_smoketest_or_raises(
obj,
method: Literal["iloc", "loc"],
key: Any,
axes: Literal[0, 1] | None =... |
ce135a7157e661a1be0077b65bf42cbfb7d981838f30014e8b19218b3af47d57 | Python | 1,021 | 36 | import os
import numpy as np
fiber_length = 12500 # [um]
delta_zs = 5 # [um]
x, y = 0, 0
fiber_index = 99
def write(x_coord: float, y_coord: float, z_coords: list[float], path: str):
"""
:param path:
"""
with open(path, 'w') as f:
f.write(str(len(z_coords)) + ' ')
f.write("\n")
... |
b23fc3a322aaae9eae900de27468561d77220669cb7fb219b5b8d73533b8d610 | Python | 1,022 | 35 | #!/usr/bin/env python3.7
"""Generate a heatmap of activation thresholds.
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent.
No... |
adc740286c8b53dc2c705a977fdbce8fee69a8796616fd8d8f0533b27d22e9ea | Python | 1,023 | 30 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
import unittest
from minimock import mock... |
b6ce60864f20e8f6172a976c05da2f057c4f18edaaabbe45115cc18230157d1c | Python | 1,023 | 39 | import pytest
from pandas import (
DataFrame,
Series,
)
import pandas._testing as tm
class TestPipe:
def test_pipe(self, frame_or_series):
obj = DataFrame({"A": [1, 2, 3]})
expected = DataFrame({"A": [1, 4, 9]})
if frame_or_series is Series:
obj = obj["A"]
... |
0f62b4a9f306229fea990fb01b49e06ddc3f48ed4bc50c549e6e75dd6ab6ce2f | Python | 1,025 | 35 | import argparse
import pandas as pd
import numpy as np
import os, sys, shutil, importlib, glob
from tqdm.notebook import tqdm
import celloracle as co
from celloracle import motif_analysis as ma
from genomepy import Genome
import scanpy as sc
import pyarrow.parquet as pq
import mycelloracle
def load_tfidf(f) -> pd.Data... |
7c99754c8b519f5f601b0a2ea9383ef333d45b762a401a8696dadf3d0b351fdc | Python | 1,025 | 39 | import os
import platform
from pip._vendor.rich import inspect
from pip._vendor.rich.console import Console, get_windows_console_features
from pip._vendor.rich.panel import Panel
from pip._vendor.rich.pretty import Pretty
def report() -> None: # pragma: no cover
"""Print a report to the terminal with debugging ... |
6f366330b2688e81d374a996165d8a2b5263877d6a8513cfe65f22631b203d3a | Python | 1,027 | 32 | import MDAnalysis as mda
from ase.io import read
from MDAnalysis.coordinates.DCD import DCDWriter
import os
import argparse
def traj2dcd(trajpath,output_name):
if not os.path.exists(trajpath):
return
atoms = read(trajpath,index='::1')
u = mda.Universe(pdbtop, atoms[0][:prot_atom_num].get_positions(... |
2adc368c4bd9f6717260e5188e1922c53853cc6b3d463f5b26ee723305cf92aa | Python | 1,028 | 40 | import logging
from .CNN_model import get_shifts_and_labels
logger = logging.getLogger(__name__)
def get_nn_shifts(mols, batch_size=16):
"""
Predicts shifts from rdkit Mol objects.
Arguments:
- list of lists of RDKit mol objects
Returns:
- list of lists of 13C chemical shifts for each atom ... |
778b7a9e44d094de731cac1e41511169bb18df68ad820581175db80c64666c55 | Python | 1,028 | 39 | """
2008-04-11, C. Schmidt-Hieber
Some helper functions for least-squares mimization using SciPy
"""
from scipy.optimize import leastsq
import numpy as np
import stf
def fexpbde(p,x):
tpeak = p[3]*p[1]*np.log(p[3]/p[1])/(p[3]-p[1])
adjust = 1.0/((1.0-np.exp(-tpeak/p[3]))-(1.0-np.exp(-tpeak/p[1])));
e1=np.... |
7a05e683f94410bc56bf358ca960cd506e74c7d49f1824a5f3c2c5a25c7eed3a | Python | 1,028 | 37 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..utils._get_lang_cfg import get_lang_cfg
from ..counts._count_syllables import count_syllables
from ..counts._count_words import count_words
from ..counts._count_sentences import count_sentences
@typed_cache
def szigriszt_pazos(tex... |
82d6163efa3f9a2172d304c12e12e91226ca825febd0ae363d1c67d5f9619d31 | Python | 1,030 | 40 | # main.py
import argparse
import logging
from cli.build_cli.register_build import register_build_commands
from cli.lib.common.logger import setup_logging
from cli.test_cli.register_test import register_test_commands
logger = logging.getLogger(__name__)
def main():
# Define top-level parser
parser = argpar... |
b589cbf28c468b8692356babd261bc0c03fbac2eb2ba16bf33024ef31c3472b2 | Python | 1,030 | 28 | import urllib.parse
class PackageIndex:
"""Represents a Package Index and provides easier access to endpoints"""
__slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"]
def __init__(self, url: str, file_storage_domain: str) -> None:
super().__init__()
self.url = ur... |
28713e91eb4e3f23bbf85b127dcbd1f76465e7eeef22a3094b53e26982a927d2 | Python | 1,031 | 38 | import torch
from torch import nn
class PolynomialCutoff(nn.Module):
def __init__(self, r_max, p=6):
r"""Polynomial cutoff, as proposed in DimeNet: https://arxiv.org/abs/2003.03123
Parameters
----------
r_max : float
Cutoff radius
p : int
Power us... |
f6ffb5c5a842f53660dbc1537c11b5e6f5827270c1d5b7d6cfb7a34f4783ad5c | Python | 1,031 | 27 | from typing import Any, TypeAlias
import numpy as np
# NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and
# `np.bytes_` are already subclasses of their builtin counterpart
_CharLike_co: TypeAlias = str | bytes
# The 6 `<X>Like_co` type-aliases below represent all scalars that can be
# coerced i... |
0b48685105229e7e7a40190b802599a4d619bbac694cacb4b53634b42ffccf8e | Python | 1,032 | 27 | import argparse
from wandb_utils import WandbLogger
from utils.general import LOGGER
WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
def create_dataset_artifact(opt):
logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused
if not logger.wandb:
LOGGER.info("install wand... |
7d6e3dcd4077b32305b0aa5fd684413b487cb669d3c113f7cd43ebb01d11db63 | Python | 1,032 | 41 | """distutils.command
Package containing implementation of all the standard Distutils
commands.
"""
def test_na_writable_attributes_deletion():
a = np.NA(2)
attr = ['payload', 'dtype']
for s in attr:
assert_raises(AttributeError, delattr, a, s)
__revision__ = "$Id: __init__.py,v 1.3 2005/05/16 1... |
6c6efb78570d0ddd960b03f1aa477d25d5c32bd1825e1013aaa2e117eb610da6 | Python | 1,035 | 40 | import setuptools
import os
with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding='utf-8') as readme:
long_description = readme.read()
setuptools.setup(
name='subs2vec',
version='0.9.6',
packages=['subs2vec'],
package_data={
'subs2vec': ['datasets/*/*.tsv', 'paper_resu... |
bbcfcd9dd6c5e318fb9deed061b65401acd639536079816b8bc9976e6c5830eb | Python | 1,035 | 31 | import math
import torch
from torch.nn.parameter import Parameter
from torch.nn import functional as F
from torch.nn import Module
class CosineClassifier(Module):
def __init__(self, in_features, n_classes, sigma=True):
super(CosineClassifier, self).__init__()
self.in_features = in_features
... |
c71a7e5408fbe22a19d065d3aff83c59a3f5da90e0adb8fb071cb95856828e35 | Python | 1,036 | 44 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
from smac.env.pettingzoo import StarCraft2PZEnv
def main():
"""
Runs an env object with random actions.
"""
env = StarCraft2PZEnv.env()
episodes = 10
... |
02e32417ae2d40e828438d8371e98112567c3aefd77e1cca408a217e05271481 | Python | 1,038 | 30 | import pytest
from nablaDFT import model_registry
from torch_geometric.data import Batch
from tests.decorators import withCUDA
@withCUDA
@pytest.mark.model
@pytest.mark.parametrize(
"model_name",
["DimeNet++", "Equiformer-v2", "ESCN-OC", "GemNet-OC", "Graphormer3D-small"],
)
def test_pyg_lightning_model(mode... |
d96c4c6233bd05bf408af76ebb57a68fe2ba320ee544a64dedb6bbfafbd366b4 | Python | 1,038 | 21 | import numpy as np
def check_action(action,dim):
null_action = np.zeros(dim,dtype=float)-1
message = "none"
if not isinstance(action,np.ndarray):
message = "Action is not a numpy array. Action was not used."
action = null_action
elif action.ndim != 1:
message = f"Action has... |
3c2a451e474c48cc3c3e871e29b96f0af28ec3287628ae96b7a905bd7dcb3e0b | Python | 1,039 | 34 | import json
import csv
from pathlib import Path
from typing import List
import torch
def save_model(save_folder: Path, best_weights: dict, last_weights: dict, best_stats: dict, last_stats: dict, log: List[dict]):
save_folder.mkdir(parents=True, exist_ok=True)
best_model_file = save_folder / "best_weights.pt... |
62ccdf3b8805207d5fe0befe5598c7e6c532b1bec19eb1a1a2c4a1ed24877bd0 | Python | 1,041 | 44 | """Test functions for FOOOF plots."""
import numpy as np
from fooof.plts.templates import *
from fooof.tests.utils import plot_test
###################################################################################################
#####################################################################################... |
c03823c5af6f888abeb01c6ebe9349789a40785700f03093a6f6acb4bb9e3a62 | Python | 1,041 | 33 | # License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.
# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=no-self-use,protected-access,missing-docstring
import unittest
from argparse import Names... |
ddf67475680aacfae07465fa1c6acf483ea031ec44b48fae626cbd5d9dbdbf82 | Python | 1,042 | 33 | """Backward-compatible source-tree shim for the packaged Python API."""
from __future__ import annotations
import sys
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
_SRC = Path(__file__).resolve().parent / "src"
if str(_SRC) not in sys.path:
sys.path.insert(0, str(_... |
5d7de47877358b1c1bc098648290b628f07a854f91a9444d586a0946d906d2d9 | Python | 1,043 | 42 | """
Parameterized Hamiltonian (Pulse control/Analog simulation) with AD/JIT support using jax ode solver
"""
import optax
from jax.experimental.ode import odeint
import tensorcircuit as tc
K = tc.set_backend("jax")
tc.set_dtype("complex128")
hx = tc.quantum.PauliStringSum2COO([[1]])
hz = tc.quantum.PauliStringSum2CO... |
962e76b469a3baacfc2b26533ee81bde7ba22bac3952e9176ecafed840387d16 | Python | 1,044 | 45 | """ Creates numpy array from an H5 file containing auxiliary spike events
Author: Drew B. Headley
"""
import numpy as np
import h5py
def load_spike_aux_h5(fpath):
"""
Loads an H5 file that contains somatic action potential times and the
converts them to a numpy array of integer simulation time steps
... |
11a1febd018cc446c3dee47b6985afca9386721b46918850d7904ce126efdd18 | Python | 1,045 | 45 | from __future__ import annotations
import re
from ..utils._typed_cache import typed_cache
from ..selections._list_words import list_words
@typed_cache
def count_complex_arabic_words(text: str, rm_apostrophe: bool = True) -> int:
"""
Count complex arabic words. Complex arabic words are word with
more tha... |
ba6d1ee3518ebc1453429eadca2ef90c5a52711dc273b14fa9913e1d02de57da | Python | 1,046 | 45 | """ Creates numpy array from an H5 file containing somatic spike events
Author: Drew B. Headley
"""
import numpy as np
import h5py
def load_spike_h5(fpath):
"""
Loads an H5 file that contains somatic action potential times and the
converts them to a numpy array of integer simulation time steps
Par... |
d0d6536faf3cdc630e34f6b40f8e91ff1681fbd78e8787399f14e6d7810426d2 | Python | 1,047 | 33 | #!/usr/bin/env python3.7
"""Generate dose-response curves (% fibers activated as a function of stimulation amplitude).
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub reposito... |
b9ad0552cf0ebca043f29846d8bc91214feee230e7d08eb9b5ea039cd1312c44 | Python | 1,049 | 46 | from __future__ import annotations
from ..utils._typed_cache import typed_cache
from ..counts._count_long_words import count_long_words
from ..counts._count_sentences import count_sentences
@typed_cache
def rix(text: str) -> float:
r"""Calculate the RIX for `text`
A Rix ratio is the number of long words div... |
648bdb7ec88a1776dfb092d08e0f8f3587a1578055a9ce9b482ce5ac3f5fc58b | Python | 1,050 | 26 | import numpy as np
from tkinter import messagebox
def calculate_baseline(app, window_size=50, percentile=30):
if app.time is None or app.df_f is None:
messagebox.showwarning(title="Warning", message="No data loaded.")
return
window_size = int(window_size)
percentile = float(percentile)
... |
8188a17902b7674070768fb451a1c8c9f5c6a662f5fd4be830ff45548a73b653 | Python | 1,050 | 42 | import pytest
import pandas as pd
from pandas.core.arrays import period_array
class TestReductions:
def test_min_max(self):
arr = period_array(
[
"2000-01-03",
"2000-01-03",
"NaT",
"2000-01-02",
"2000-01-05",
... |
a9e620498cddc00022dee0225d84337bb3a69da42c1d707882fadc912605b9cb | Python | 1,050 | 37 | #!/usr/bin/env python3.7
"""Generate mock sample morphology.
The copyrights of this software are owned by Duke University. Please
refer to the LICENSE and README.md files for licensing instructions. The
source code can be found on the following GitHub repository:
https://github.com/wmglab-duke/ascent
"""
import os
i... |
2b87f4a5579fa51dfc7d5492c3c6987ccf4f6fdce1e0026c7c0838882145f005 | Python | 1,051 | 31 | #!/usr/bin/env python
# ========================= #
# Training of network model #
# ========================= #
# Usage: python <path-to-this-file>/train.py <your_config>.ini [-n NUM_THREADS]
# Default train config file is DeepH-E3/deephe3/default_configs/train_default.ini
import os
import argparse
parser = argpars... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.